summaryrefslogtreecommitdiff
path: root/plugins/modules/vyos_logging_global.py
blob: 09fdd6b5c577fe86b692ebb19bb008cab785a7fb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
#!/usr/bin/python
# -*- coding: utf-8 -*-
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import absolute_import, division, print_function


__metaclass__ = type

DOCUMENTATION = r"""
---
module: vyos_logging_global
short_description: Manage syslog configuration on VyOS devices using REST API
description:
  - Manages syslog (logging) configuration on VyOS devices via the REST API.
  - Supports console, file, host, user, and global logging targets with
    per-target facility and severity configuration.
  - Uses REST API (C(connection=httpapi)) instead of CLI.
version_added: "1.0.0"
author:
  - Sagar Paul (@KB-perByte)

options:
  config:
    description: Logging configuration.
    type: dict
    suboptions:
      console:
        description: Logging to serial console.
        type: dict
        suboptions:
          facilities:
            description: List of syslog facilities to log to the console.
            type: list
            elements: dict
            suboptions:
              facility:
                description: Syslog facility name (e.g. local7, all, kern).
                type: str
              severity:
                description: Minimum severity level to log (e.g. err, debug, all).
                type: str
      files:
        description: Logging to local files.
        type: list
        elements: dict
        suboptions:
          path:
            description: Path to the log file on the device.
            type: str
          archive:
            description: Log file archive/rotation settings.
            type: dict
            suboptions:
              file_num:
                description: Number of archived log files to keep.
                type: int
              size:
                description: Maximum size of log file in kilobytes before rotation.
                type: int
          facilities:
            description: List of syslog facilities to log to this file.
            type: list
            elements: dict
            suboptions:
              facility:
                description: Syslog facility name.
                type: str
              severity:
                description: Minimum severity level to log.
                type: str
      global_params:
        description: Global syslog parameters (maps to C(system syslog global)).
        type: dict
        suboptions:
          archive:
            description: Global log archive/rotation settings.
            type: dict
            suboptions:
              file_num:
                description: Number of archived log files to keep.
                type: int
              size:
                description: Maximum size of log file in kilobytes before rotation.
                type: int
          facilities:
            description: List of syslog facilities for global logging.
            type: list
            elements: dict
            suboptions:
              facility:
                description: Syslog facility name.
                type: str
              severity:
                description: Minimum severity level to log.
                type: str
          marker_interval:
            description: Interval in seconds between marker log entries.
            type: int
          preserve_fqdn:
            description: Use the fully qualified domain name in syslog messages.
            type: bool
      hosts:
        description: Logging to remote syslog hosts.
        type: list
        elements: dict
        suboptions:
          hostname:
            description: IP address or hostname of the remote syslog server.
            type: str
          port:
            description: UDP/TCP port on the remote syslog server (default 514).
            type: int
          protocol:
            description: Transport protocol (udp or tcp).
            type: str
          facilities:
            description: List of syslog facilities to forward to this host.
            type: list
            elements: dict
            suboptions:
              facility:
                description: Syslog facility name.
                type: str
              severity:
                description: Minimum severity level to forward.
                type: str
              protocol:
                description: Per-facility protocol override (udp or tcp).
                type: str
      users:
        description: Logging to local user terminals.
        type: list
        elements: dict
        suboptions:
          username:
            description: Local username whose terminal receives log messages.
            type: str
          facilities:
            description: List of syslog facilities to send to this user.
            type: list
            elements: dict
            suboptions:
              facility:
                description: Syslog facility name.
                type: str
              severity:
                description: Minimum severity level to send.
                type: str

  running_config:
    description: Used only with state C(parsed).
    type: str

  state:
    description:
      - Desired state of the logging configuration.
    type: str
    default: merged
    choices:
      - merged
      - replaced
      - overridden
      - deleted
      - gathered
      - rendered
      - parsed
"""

EXAMPLES = r"""
- name: Merge logging configuration
  vyos.rest.vyos_logging_global:
    config:
      console:
        facilities:
          - facility: local7
            severity: err
      files:
        - path: logFile
          archive:
            file_num: 2
          facilities:
            - facility: local6
              severity: emerg
      hosts:
        - hostname: 172.16.0.1
          port: 223
          facilities:
            - facility: local7
              severity: all
            - facility: all
              protocol: udp
      users:
        - username: vyos
          facilities:
            - facility: local7
              severity: debug
      global_params:
        archive:
          file_num: 2
          size: 111
        facilities:
          - facility: cron
            severity: debug
        marker_interval: 111
        preserve_fqdn: true
    state: merged

- name: Delete all logging configuration
  vyos.rest.vyos_logging_global:
    state: deleted

- name: Gather current logging configuration
  vyos.rest.vyos_logging_global:
    state: gathered
"""

RETURN = r"""
before:
  description: Logging configuration before this module ran.
  returned: when state is merged, replaced, overridden or deleted
  type: dict
after:
  description: Logging configuration after this module ran.
  returned: when changed
  type: dict
commands:
  description: List of API command tuples sent to the device.
  returned: always
  type: list
gathered:
  description: Current logging configuration from the device.
  returned: when state is gathered
  type: dict
saved:
  description: Result of save_config after applying changes.
  returned: when changes are applied
  type: dict
"""

from ansible.module_utils.basic import AnsibleModule
from ansible_collections.vyos.rest.plugins.module_utils.vyos import VyOSModule


# ------------------------------------------------------------
# Normalization
# ------------------------------------------------------------


def normalize_config(cfg):
    result = {
        "console": {"facilities": {}},
        "global": {"facilities": {}},
        "hosts": {},
        "files": {},
        "users": {},
    }

    for f in cfg.get("console", {}).get("facilities", []):
        result["console"]["facilities"][f["facility"]] = f.get("severity")

    gp = cfg.get("global_params", {})
    for f in gp.get("facilities", []):
        result["global"]["facilities"][f["facility"]] = f.get("severity")
    if gp.get("archive"):
        result["global"]["archive"] = gp["archive"]
    if gp.get("marker_interval"):
        result["global"]["marker_interval"] = gp["marker_interval"]
    if gp.get("preserve_fqdn"):
        result["global"]["preserve_fqdn"] = True

    for h in cfg.get("hosts", []):
        host = {"port": h.get("port"), "facilities": {}}
        for f in h.get("facilities", []):
            host["facilities"][f["facility"]] = {k: v for k, v in f.items() if k != "facility"}
        result["hosts"][h["hostname"]] = host

    for f in cfg.get("files", []):
        facilities = {x["facility"]: x.get("severity") for x in f.get("facilities", [])}
        result["files"][f["path"]] = {
            "archive": f.get("archive"),
            "facilities": facilities,
        }

    for u in cfg.get("users", []):
        result["users"][u["username"]] = {
            "facilities": {f["facility"]: f.get("severity") for f in u.get("facilities", [])},
        }

    return result


def normalize_running(raw):
    result = {
        "console": {"facilities": {}},
        "global": {"facilities": {}},
        "hosts": {},
        "files": {},
        "users": {},
    }

    if not raw:
        return result

    for f, data in raw.get("console", {}).get("facility", {}).items():
        result["console"]["facilities"][f] = data.get("level")

    g = raw.get("global", {})
    for f, data in g.get("facility", {}).items():
        result["global"]["facilities"][f] = data.get("level")
    if "archive" in g:
        result["global"]["archive"] = g["archive"]
    if "marker" in g and "interval" in g["marker"]:
        result["global"]["marker_interval"] = g["marker"]["interval"]
    if "preserve-fqdn" in g:
        result["global"]["preserve_fqdn"] = True

    for host, data in raw.get("host", {}).items():
        h = {"port": data.get("port"), "facilities": {}}
        for f, fd in data.get("facility", {}).items():
            h["facilities"][f] = {
                "severity": fd.get("level"),
                "protocol": fd.get("protocol"),
            }
        result["hosts"][host] = h

    for path, data in raw.get("file", {}).items():
        facilities = {}
        for f, fd in data.get("facility", {}).items():
            facilities[f] = fd.get("level")
        result["files"][path] = {
            "archive": data.get("archive"),
            "facilities": facilities,
        }

    for user, data in raw.get("user", {}).items():
        facilities = {}
        for f, fd in data.get("facility", {}).items():
            facilities[f] = fd.get("level")
        result["users"][user] = {"facilities": facilities}

    return result


# ------------------------------------------------------------
# Diff helpers
# ------------------------------------------------------------


def diff_facilities(base, want, have, state):
    cmds = []
    want_keys = set(want)
    have_keys = set(have)

    for f in want_keys:
        if f not in have_keys or want[f] != have[f]:
            path = base + ["facility", f]
            if want[f]:
                path += ["level", want[f]]
            cmds.append(("set", path))

    if state in ["replaced", "deleted"]:
        for f in have_keys - want_keys:
            cmds.append(("delete", base + ["facility", f]))

    return cmds


def diff_map(base, want, have, state):
    cmds = []
    w = set(want)
    h = set(have)

    if state in ["merged", "replaced"]:
        for k in w - h:
            cmds.append(("set", base + [k]))

    if state in ["replaced", "deleted"]:
        for k in h - w:
            cmds.append(("delete", base + [k]))

    return cmds


# ------------------------------------------------------------
# Build commands
# ------------------------------------------------------------


def build_commands(want, have, state):
    cmds = []

    if state == "overridden":
        cmds.append(("delete", ["system", "syslog"]))
        state = "merged"

    cmds += diff_facilities(
        ["system", "syslog", "console"],
        want["console"]["facilities"],
        have["console"]["facilities"],
        state,
    )

    cmds += diff_facilities(
        ["system", "syslog", "global"],
        want["global"]["facilities"],
        have["global"]["facilities"],
        state,
    )

    cmds += diff_map(
        ["system", "syslog", "file"],
        want["files"],
        have["files"],
        state,
    )

    cmds += diff_map(
        ["system", "syslog", "host"],
        want["hosts"],
        have["hosts"],
        state,
    )

    cmds += diff_map(
        ["system", "syslog", "user"],
        want["users"],
        have["users"],
        state,
    )

    return cmds


# ------------------------------------------------------------
# Running config
# ------------------------------------------------------------


def get_running_config(vyos):
    raw = vyos.get_config(["system", "syslog"])
    return normalize_running(raw)


# ------------------------------------------------------------
# Main
# ------------------------------------------------------------


def main():
    argument_spec = dict(
        config=dict(type="dict"),
        running_config=dict(type="str"),
        state=dict(
            default="merged",
            choices=[
                "merged",
                "replaced",
                "overridden",
                "deleted",
                "gathered",
                "rendered",
                "parsed",
            ],
        ),
    )

    module = AnsibleModule(argument_spec, supports_check_mode=True)
    vyos = VyOSModule(module)

    state = module.params["state"]
    config = module.params.get("config") or {}

    if state == "gathered":
        module.exit_json(gathered=get_running_config(vyos))

    want = normalize_config(config)
    have = get_running_config(vyos)

    if state == "deleted":
        want = {
            "console": {"facilities": {}},
            "global": {"facilities": {}},
            "hosts": {},
            "files": {},
            "users": {},
        }

    commands = build_commands(want, have, state)

    if module.check_mode:
        module.exit_json(changed=bool(commands), commands=commands, before=have)

    if commands:
        response = vyos.apply_commands(commands)
        saved = vyos.save_config()
        module.exit_json(
            changed=True,
            before=have,
            after=want,
            commands=commands,
            saved=saved,
            response=response,
        )

    module.exit_json(changed=False, before=have, after=have, commands=[])


if __name__ == "__main__":
    main()