Repository navigation
Expand file tree
/
Copy pathicinga.py
More file actions
1118 lines (986 loc) · 41.5 KB
/
Copy pathicinga.py
File metadata and controls
1118 lines (986 loc) · 41.5 KB
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python3
# -*- coding: utf-8; py-indent-offset: 4 -*-
#
# Author: Linuxfabrik GmbH, Zurich, Switzerland
# Contact: info (at) linuxfabrik (dot) ch
# https://www.linuxfabrik.ch/
# License: The Unlicense, see LICENSE file.
# https://github.com/Linuxfabrik/lib/blob/main/CONTRIBUTING.md
"""This module tries to make accessing the Icinga2 API and the configuration of the
Icinga Director easier."""
__author__ = 'Linuxfabrik GmbH, Zurich/Switzerland'
__version__ = '2026110305'
import base64
import html
import json
import re
import time
import urllib.parse
from string import Template
from . import shell, txt, url
# Take care of Icinga and throttle the amount of requests, don't overload it
# with too fast subsequent api-calls.
DEFAULT_SLEEP = 1.0
# Director keeps keys starting with this prefix in the vars of services generated by
# "apply for" rules (`CustomVariables::RESERVED_OVERRIDE_HANDOFF_KEY`, Director 1.12.1).
# They are bookkeeping, not variables anybody sets.
DIRECTOR_RESERVED_PREFIX = '__director'
def api_post(
uri,
username,
password,
data=None,
method_override='',
insecure=False,
no_proxy=False,
proxy=None,
timeout=3,
):
"""
Send a low-level POST request to the Icinga API.
This function manually crafts a POST request to the Icinga REST API, adding basic authentication
headers and optionally overriding the HTTP method via `X-HTTP-Method-Override`.
Parameters
----------
uri : str
Full API endpoint URL (e.g., `https://icinga.example.com:5665/v1/objects/services`).
username : str
API username.
password : str
API password.
data : dict, optional
Payload to send with the request. Defaults to `None`.
method_override : str, optional
If set, override HTTP method (e.g., `'GET'`). Defaults to `''`.
insecure : bool, optional
Disable SSL certificate verification. Defaults to `False`.
no_proxy : bool, optional
Bypass proxy. Defaults to `False`.
proxy : str, optional
Proxy to reach the target through, overriding the one the environment names.
Defaults to `None`, which leaves the choice to the environment.
timeout : int, optional
Timeout for the request in seconds. Defaults to `3`.
Returns
-------
tuple (bool, object)
The result from the `url.fetch_json` call.
Notes
-----
- Collapses repeated slashes in the path of the URI (`//v1`, from a base URL with a
trailing slash). The host is left alone, `v1.icinga.example.com` included.
- Pauses execution for a short duration after sending the request (`DEFAULT_SLEEP`).
Examples
--------
>>> uri = 'https://icinga.example.com:5665/v1/objects/services'
>>> data = {
... 'filter': 'match("special-service", service.name)',
... 'attrs': ['name', 'state', 'acknowledgement'],
... }
>>> result = lib.base.coe(
... lib.icinga.api_post(
... uri,
... args.USERNAME,
... args.PASSWORD,
... data=data,
... method_override='GET',
... timeout=3,
... )
... )
"""
# Only the path: replacing `//v1` in the whole URI also hit the `//` after the
# scheme of a host such as `v1.icinga.example.com`.
try:
parts = urllib.parse.urlsplit(uri)
except ValueError as e:
# a bracketed host that is no IP address, refused by urlsplit() since gh-103848
# (CPython 3.9.21, 3.10.16, 3.11.4, 3.12.0, and backports)
return False, f'Cannot read the URL "{txt.sanitize_sensitive_data(uri)}": {e}'
uri = urllib.parse.urlunsplit(
parts._replace(path=re.sub(r'/{2,}', '/', parts.path))
)
headers = {
'Accept': 'application/json',
'Authorization': f'Basic {txt.to_text(base64.b64encode(txt.to_bytes(f"{username}:{password}")))}',
}
if method_override:
headers['X-HTTP-Method-Override'] = method_override
result = url.fetch_json(
uri,
data=data or {},
encoding='serialized-json',
header=headers,
insecure=insecure,
no_proxy=no_proxy,
proxy=proxy,
timeout=timeout,
)
time.sleep(DEFAULT_SLEEP)
return result
def build_icingaweb2_url(base_url, hostname, servicename=None):
"""
Build an Icinga Web 2 detail URL for a host or a service.
Composes the Icinga DB module's host or service detail URL from a base Icinga Web 2 URL and the
object name(s). A service URL is built when `servicename` is a non-empty string, otherwise a
host URL.
The object names are treated as untrusted: they are URL-encoded (including `/`, `&`, `?`, `#`,
quotes and spaces), so a name cannot inject extra query parameters or break out of the URL. The
returned link is meant to be embedded verbatim in notifications (mail, chat), so the function
also pins the scheme to `http`/`https` and never emits a `javascript:`, `data:` or `file:` URL
from a malformed base URL.
Parameters
----------
base_url : str
Base Icinga Web 2 URL, e.g. `https://example.com/icingaweb2`.
hostname : str
Host object name.
servicename : str, optional
Service object name. When a non-empty string, a service
detail URL is built; otherwise a host detail URL. Defaults to `None`.
Returns
-------
str or None
The composed URL, or `None` when `base_url`/`hostname` is missing, not a
string, or when `base_url` does not use the `http`/`https` scheme.
Notes
-----
- Callers that embed the URL in HTML must still HTML-escape it; encoding a URL is not the same
as escaping it for an HTML attribute.
Examples
--------
>>> build_icingaweb2_url('https://example.com/icingaweb2', 'web01')
'https://example.com/icingaweb2/icingadb/host?name=web01'
>>> build_icingaweb2_url('https://example.com/icingaweb2', 'web01', 'http')
'https://example.com/icingaweb2/icingadb/service?name=http&host.name=web01'
"""
if not isinstance(base_url, str) or not isinstance(hostname, str):
return None
if not base_url or not hostname:
return None
try:
scheme = urllib.parse.urlsplit(base_url).scheme.lower()
except ValueError:
return None
if scheme not in ('http', 'https'):
return None
if isinstance(servicename, str) and servicename:
query = urllib.parse.urlencode(
{'name': servicename, 'host.name': hostname},
quote_via=urllib.parse.quote,
)
path = f'icingadb/service?{query}'
else:
query = urllib.parse.urlencode(
{'name': hostname},
quote_via=urllib.parse.quote,
)
path = f'icingadb/host?{query}'
return urllib.parse.urljoin(f'{base_url}/', path)
# The object classes of a basket that are compared, with the name a human knows them
# by and the field that names an object. Fields left out of the comparison: `uuid`
# (the key), icons, `notes`/`notes_url` of services (typically a description that is
# reworded over time) and `description` of Service Sets.
_BASKET_CLASSES = (
('Datafield', 'Datafield', 'varname'),
('Command', 'Command', 'object_name'),
('HostTemplate', 'Host Template', 'object_name'),
('ServiceTemplate', 'Service Template', 'object_name'),
('ServiceSet', 'Service Set', 'object_name'),
)
_HOST_TEMPLATE_FIELDS = (
'accept_config', 'action_url', 'address', 'address6', 'api_key', 'check_command',
'check_interval', 'check_period', 'check_timeout', 'command_endpoint', 'disabled',
'display_name', 'enable_active_checks', 'enable_event_handler', 'enable_flapping',
'enable_notifications', 'enable_passive_checks', 'enable_perfdata', 'event_command',
'flapping_threshold_high', 'flapping_threshold_low', 'groups', 'has_agent',
'imports', 'master_should_connect', 'max_check_attempts', 'notes', 'notes_url',
'object_name', 'object_type', 'retry_interval', 'template_choice', 'volatile',
'zone',
) # fmt: skip
_SERVICE_FIELDS = (
'action_url', 'apply_for', 'assign_filter', 'check_command', 'check_interval',
'check_period', 'check_timeout', 'command_endpoint', 'disabled', 'display_name',
'enable_active_checks', 'enable_event_handler', 'enable_flapping',
'enable_notifications', 'enable_passive_checks', 'enable_perfdata', 'event_command',
'flapping_threshold_high', 'flapping_threshold_low', 'groups', 'host', 'imports',
'max_check_attempts', 'object_name', 'object_type', 'retry_interval', 'service_set',
'template_choice', 'use_agent', 'use_var_overrides', 'volatile', 'zone',
) # fmt: skip
# The directory part of every path in a command line, POSIX or Windows. A command is
# compared without it, so the same plugin installed into another directory, on
# another platform or under another distribution compares equal.
_COMMAND_DIRECTORY = re.compile(
r'[A-Za-z]:\\(?:[^\\"\'\r\n]*\\)*' # C:\Program Files\...\, spaces included
r'|(?<![^\s"\'])/(?:[^\s"\'/]*/)*' # /usr/lib64/nagios/plugins/
)
# Sub-objects that are added or removed as a whole: `<group>.<name>.<field>`
_BASKET_GROUPS = ('arguments', 'fields', 'services')
def _as_dict(value):
"""Return `value` if it is a dict, an empty dict otherwise. Baskets are input."""
return value if isinstance(value, dict) else {}
def _basket_datafield_uuid(basket, datafield_id):
"""Return the uuid of the data field a field binding points to, by its id."""
field = _as_dict(_as_dict(_as_dict(basket).get('Datafield')).get(str(datafield_id)))
return field.get('uuid') or str(datafield_id)
def _basket_flatten(basket, cls, obj):
"""Flatten one basket object into `{field: value}` for the comparison. Director
serializes the same object in several shapes, and only the content counts. A
field is a tuple of names, since a name (a service, an argument, a variable) may
contain a dot itself.
"""
flat = {}
if cls == 'Datafield':
for key in ('datatype', 'format', 'varname'):
flat[(key,)] = obj.get(key)
for key, value in _as_dict(obj.get('settings')).items():
flat[('settings', key)] = value
return flat
if cls == 'Command':
for name, arg in _as_dict(obj.get('arguments')).items():
if not isinstance(arg, dict):
arg = {'value': arg} # the short form of an argument
for key, value in arg.items():
flat[('arguments', name, key)] = value
command = obj.get('command') if isinstance(obj.get('command'), str) else ''
flat[('command',)] = _COMMAND_DIRECTORY.sub('', command)
for key in ('imports', 'is_string', 'methods_execute', 'object_name'):
flat[(key,)] = obj.get(key)
for key in ('object_type', 'timeout', 'zone'):
flat[(key,)] = obj.get(key)
elif cls == 'ServiceSet':
for key in ('assign_filter', 'object_name', 'object_type'):
flat[(key,)] = obj.get(key)
services = obj.get('services')
if isinstance(services, list): # the format of older baskets
services = {
s.get('object_name'): s for s in services if isinstance(s, dict)
}
for name, service in _as_dict(services).items():
if isinstance(service, dict):
for key, value in _basket_flatten(
basket, 'ServiceTemplate', service
).items():
flat[('services', name, *key)] = value
return flat
else:
fields = _HOST_TEMPLATE_FIELDS if cls == 'HostTemplate' else _SERVICE_FIELDS
for key in fields:
flat[(key,)] = obj.get(key)
flat[('disabled',)] = obj.get('disabled', False)
bindings = obj.get('fields')
for binding in bindings if isinstance(bindings, list) else []:
if isinstance(binding, dict):
uuid = _basket_datafield_uuid(basket, binding.get('datafield_id'))
# `is_required` does not survive an export and an import unchanged
flat[('fields', uuid, 'var_filter')] = binding.get('var_filter')
for key, value in _as_dict(obj.get('vars')).items():
flat[('vars', key)] = value
return flat
def _basket_index(basket, cls, anchor):
"""Return `{uuid (or name): (name, flat object)}` for one object class."""
index = {}
for key, obj in _as_dict(_as_dict(basket).get(cls)).items():
if not isinstance(obj, dict):
continue
name = obj.get(anchor) or key
index[obj.get('uuid') or name] = (name, _basket_flatten(basket, cls, obj))
return index
def _basket_group(field):
"""Return the `(<group>, <name>)` sub-object a flat field belongs to, or None."""
if len(field) >= 3 and field[0] in _BASKET_GROUPS:
return field[:2]
return None
def _basket_change(field, live, shipped, varnames):
"""Build one change: the service of a Service Set goes into its own key, and a
field binding is named by the variable of its data field instead of its uuid.
"""
service = None
if field[0] == 'services' and len(field) >= 2:
service, field = field[1], field[2:]
field = list(field)
if len(field) >= 2 and field[0] == 'fields' and field[1] in varnames:
field[1] = varnames[field[1]]
return {
'field': '.'.join(field),
'live': live,
'service': service,
'shipped': shipped,
}
def director_basket_diff(live, shipped):
"""
Compare the objects of a Director basket with what the Director holds.
Covers the data fields, commands, host templates, service templates and Service
Sets of `shipped`. Objects are matched by their uuid. An object that exists only
in `live` is not reported: importing `shipped` leaves it alone.
Parameters
----------
live : dict
The objects in the Director, as `director_basket_dump()` returns them.
shipped : dict
The basket to compare with, for example the one that ships with the
Linuxfabrik Monitoring Plugins.
Returns
-------
list of dict
One entry per object of `shipped` that is missing in `live` or differs from
it, sorted by class and name: `class` (for example `'Service Template'`),
`name`, `missing` (bool) and `changes`, a list of `{'field', 'live',
'service', 'shipped'}`. `live` and `shipped` are `None` on the side a field
is missing on. `service` names the service of a Service Set the field
belongs to, `None` otherwise. `field` is the path of the field, its parts
joined with dots (`vars.cpu_usage_warning`, `arguments.--warning.value`). A
sub-object (a command argument, a field binding, a service of a Service Set)
that exists on one side only is one change, named after the sub-object (a
service with an empty `field`), with its fields as the value.
Notes
-----
- Values are compared with `director_same_value()`, which absorbs the ways the
Director serializes the same value differently in an export.
- A basket without a `Datafield` section, as after `icingacli director migrate
datafields`, is compared without data fields.
"""
varnames = {}
for basket in (live, shipped):
for field in _as_dict(_as_dict(basket).get('Datafield')).values():
if isinstance(field, dict) and field.get('uuid'):
varnames[field['uuid']] = field.get('varname') or field['uuid']
result = []
for cls, label, anchor in _BASKET_CLASSES:
live_index = _basket_index(live, cls, anchor)
for key, (name, theirs) in sorted(
_basket_index(shipped, cls, anchor).items(), key=lambda item: item[1][0]
):
if key not in live_index:
result.append(
{'changes': [], 'class': label, 'missing': True, 'name': name}
)
continue
ours = live_index[key][1]
groups_live = {_basket_group(f) for f in ours} - {None}
groups_shipped = {_basket_group(f) for f in theirs} - {None}
one_sided = groups_live ^ groups_shipped
changes = []
for group in sorted(one_sided):
sides = []
for flat in (ours, theirs):
members = {
'.'.join(f[2:]): v
for f, v in flat.items()
if _basket_group(f) == group
}
sides.append(members or None)
changes.append(_basket_change(group, *sides, varnames))
for field in sorted(set(ours) | set(theirs)):
if _basket_group(field) in one_sided:
continue
if director_same_value(ours.get(field), theirs.get(field)):
continue
changes.append(
_basket_change(field, ours.get(field), theirs.get(field), varnames)
)
if changes:
result.append(
{'changes': changes, 'class': label, 'missing': False, 'name': name}
)
return result
def director_basket_dump(name='export', timeout=30):
"""
Return the current state of the objects of a Director basket.
Runs `icingacli director basket dump`, which builds a snapshot of the objects the
basket covers in memory, without storing it. The basket definition has to cover
the object types the caller wants to compare.
Parameters
----------
name : str, optional
The name of the basket definition in the Director. Defaults to `'export'`.
timeout : int or float, optional
Seconds the call may take. Defaults to `30`, as the dump takes 4 to 10
seconds (Director 1.12.1, about 700 commands and 5000 data fields).
Returns
-------
tuple (bool, dict or str)
`(True, basket)` or `(False, message)`.
"""
if not isinstance(name, str) or not name:
return (False, 'director_basket_dump() needs the name of a basket.')
success, name = shell.safe_cli_value(name, 'basket name')
if not success:
return (False, name)
success, result = director_cli(['basket', 'dump', '--name', name], timeout=timeout)
if not success:
return (False, result)
if not isinstance(result, dict):
return (False, f'The Icinga Director returned no objects for basket "{name}".')
return (True, result)
def director_cli(argv, timeout=8):
"""
Run `icingacli director <argv>` and return its parsed JSON output.
`icingacli` reads the Icinga Director configuration as the account running it, so
no credentials are needed, but that account has to be able to read the Icinga Web 2
configuration (on most installations: be a member of the group `icingaweb2`).
Parameters
----------
argv : list of str
The arguments after `icingacli director`, for example
`['hosts', 'fetch', '--json', '--no-pretty']`. Every element is passed as one
argument, no shell is involved. A value in a positional slot (an object name)
has to be guarded by the caller, see `shell.safe_cli_value()`, or use
`director_host_services()`, which does it.
timeout : int or float, optional
Seconds the call may take. Defaults to `8`.
Returns
-------
tuple (bool, any)
`(True, data)` with the parsed JSON, or `(False, message)`.
Notes
-----
- The output carries the variables of the configuration, credentials included,
so no part of stdout ever goes into a message. Of stderr, only the first line
is passed on, redacted with `txt.sanitize_sensitive_data()` and cut to 200
characters.
- An account that cannot read the configuration gets `ERROR: Cannot read enabled
modules. Config directory "/etc/icingaweb2" is not readable` with exit code 1
(Icinga Web 2.14 on Rocky 10). The message then says how to fix it.
Examples
--------
>>> success, hosts = director_cli(['hosts', 'fetch', '--json', '--no-pretty'])
"""
if not isinstance(argv, (list, tuple)) or not argv:
return (False, 'director_cli() needs a non-empty list of arguments.')
if not all(isinstance(arg, str) and '\0' not in arg for arg in argv):
return (False, 'director_cli() only takes strings without NUL bytes.')
what = f'`icingacli director {" ".join(argv[:2])}`'
success, result = shell.shell_exec(
['icingacli', 'director', *argv], timeout=timeout
)
if not success:
return (False, f'{what} failed: {result}')
stdout, stderr, retc = result
if retc != 0:
first_line = next((line for line in stderr.splitlines() if line.strip()), '')
msg = f'{what} failed with exit code {retc}'
if first_line:
msg += f': {txt.sanitize_sensitive_data(first_line.strip())[:200]}'
msg += '.'
if 'not readable' in first_line or 'permission denied' in first_line.lower():
msg += (
' The account running this has to be able to read the Icinga Web 2'
' configuration, for example as a member of the group `icingaweb2`.'
)
return (False, msg)
try:
return (True, json.loads(stdout))
except ValueError:
return (False, f'{what} did not return valid JSON.')
# A runtime macro such as `$cpu_usage_warning$` or `$service.vars.cpu_usage_warning$`.
# `$$` is an escaped dollar sign and does not match.
_MACRO = re.compile(r'\$([A-Za-z0-9_.\-]+)\$')
# Macros starting with one of these name an object attribute, not a service variable.
_MACRO_OBJECTS = ('command', 'host', 'icinga', 'notification', 'service', 'user')
def _macro_vars(value):
"""Return the names of the service variables that the runtime macros in `value`
refer to. `value` may be any JSON-serializable structure.
"""
names = set()
for macro in _MACRO.findall(json.dumps(value, ensure_ascii=False)):
if macro.startswith('service.vars.'):
macro = macro[len('service.vars.') :]
elif macro.split('.')[0] in _MACRO_OBJECTS:
continue
# a dictionary member such as `$disks.root$` belongs to the variable `disks`
names.add(macro.split('.')[0])
return names
def director_command_vars(commands, name, _seen=()):
"""
Return the names of the variables a check command uses.
Collects the variables that the macros in the command line, the arguments, the
environment and the variables of the command refer to, including those of the
commands it imports.
Parameters
----------
commands : dict
The commands as `icingacli director commands fetch --json` returns them,
keyed by name. Fetch them without `--resolved`: the resolved export does not
contain the arguments of imported commands (Director 1.12.1), which is what
the `-sudo` variants of a command consist of.
name : str
The name of the check command.
Returns
-------
set or None
The variable names, or `None` if the command is unknown, so that a caller can
tell "uses nothing" from "cannot tell".
Examples
--------
>>> director_command_vars(
... {'cmd-check-load': {'arguments': {'--warning': '$load_warning$'}}},
... 'cmd-check-load',
... )
{'load_warning'}
"""
if not isinstance(commands, dict):
return None
obj = commands.get(name)
if not isinstance(obj, dict) or name in _seen:
return None
seen = (*_seen, name)
names = _macro_vars(
{key: obj.get(key) for key in ('arguments', 'command', 'env', 'vars')}
)
for parent in obj.get('imports') or []:
names |= director_command_vars(commands, parent, seen) or set()
return names
def director_host_services(host, timeout=8):
"""
Return the services of a host with their resolved variables, as the Icinga
Director computes them.
Covers the services of Service Sets (also those assigned by filter), of apply
rules, of host templates and of the host itself, with their templates resolved,
but without the overrides stored on the host. This is the default every service
on the host has before "Modify".
Parameters
----------
host : str
The name of the host object.
timeout : int or float, optional
Seconds the call may take. Defaults to `8`.
Returns
-------
tuple (bool, list or str)
`(True, services)`, a list of service dicts with `object_name`,
`check_command`, `service_set` and `vars` among others, or
`(False, message)`.
Notes
-----
- Uses `icingacli director host show --resolved --with-services --all-services`.
The REST API of the Director does not offer `--all-services`: its
`withServices` returns the services of the host object only.
- Takes 0.5 to 1.2 seconds per host (Director 1.12.1, about 130 services).
"""
success, host = shell.safe_cli_value(host, 'host name')
if not success:
return (False, host)
if not isinstance(host, str) or not host:
return (False, 'director_host_services() needs a host name.')
success, result = director_cli(
[
'host',
'show',
host,
'--json',
'--resolved',
'--with-services',
'--all-services',
'--no-defaults',
'--no-pretty',
],
timeout=timeout,
)
if not success:
return (False, result)
services = result.get('services') if isinstance(result, dict) else None
if not isinstance(services, list):
return (False, f'The Icinga Director returned no services for host "{host}".')
return (True, services)
def director_inherited_overrides(hosts, name, varname, _seen=()):
"""
Return the overrides of service variables a host inherits from its host templates.
Icinga Director renders the override variable with `+=`, so Icinga 2 adds the
entries of every imported host template in import order, and those of the host
itself last. An entry for a service name replaces the one inherited for the same
name as a whole, it is not merged with it.
Parameters
----------
hosts : dict
Hosts and host templates as `icingacli director hosts fetch --json` returns
them, keyed by name.
name : str
The host (or host template). Its own overrides are left out.
varname : str
The name of the override variable, `_override_servicevars` unless the
Director setting `override_services_varname` was changed.
Returns
-------
dict
`{service name: {variable: value}}`.
"""
if not isinstance(hosts, dict):
return {}
obj = hosts.get(name)
if not isinstance(obj, dict) or name in _seen:
return {}
seen = (*_seen, name)
overrides = {}
for parent in obj.get('imports') or []:
overrides.update(director_inherited_overrides(hosts, parent, varname, seen))
overrides.update(director_own_overrides(hosts.get(parent), varname))
return overrides
# Variable names whose values are treated as secrets even if the Director does not
# mark them as hidden or sensitive.
_SENSITIVE_NAME = re.compile(
r'(api.?key|community|credential|pass|private.?key|secret|token)', re.IGNORECASE
)
def director_is_sensitive(name, sensitive_vars=None):
"""
Return True if the value of the variable `name` must not be shown.
Parameters
----------
name : str
The variable name.
sensitive_vars : set, optional
The names `director_sensitive_vars()` returned.
Returns
-------
bool
True if `name` is in `sensitive_vars`, or if it contains `api-key`,
`community`, `credential`, `pass`, `private-key`, `secret` or `token`.
"""
if not isinstance(name, str):
return False
return name in (sensitive_vars or set()) or bool(_SENSITIVE_NAME.search(name))
def director_own_overrides(obj, varname):
"""
Return the overrides of service variables stored on a host or host template.
Parameters
----------
obj : dict
The host or host template as `icingacli director hosts fetch --json` returns
it.
varname : str
The name of the override variable, `_override_servicevars` unless the
Director setting `override_services_varname` was changed.
Returns
-------
dict
`{service name: {variable: value}}`. Entries that are not a dictionary are
left out.
"""
own_vars = (obj.get('vars') or {}) if isinstance(obj, dict) else {}
own = own_vars.get(varname) if isinstance(own_vars, dict) else None
if not isinstance(own, dict):
return {}
return {
service: service_vars
for service, service_vars in own.items()
if isinstance(service_vars, dict)
}
def _is_nullish(value):
"""An unset and an empty value have the same effect on a check command."""
return value is None or value in ('', [], {})
def director_same_value(a, b):
"""
Compare two variable values the way they reach a check plugin.
The Icinga Director stores the same number once as a number and once as a string
(`25` vs `"25"`), so scalars are compared by their text and as numbers. Booleans
never equal numbers. Unset and empty values are the same. Lists are compared by
their members, so a reordered list is not a change. Dictionaries are compared key
by key.
Parameters
----------
a, b : any
The two values, as decoded from the JSON of the Director.
Returns
-------
bool
Examples
--------
>>> director_same_value(25, '25')
True
>>> director_same_value(['/tmp', '/boot'], ['/boot', '/tmp'])
True
>>> director_same_value(True, 1)
False
"""
if _is_nullish(a) and _is_nullish(b):
return True
if isinstance(a, bool) or isinstance(b, bool):
return a is b
if isinstance(a, (int, float, str)) and isinstance(b, (int, float, str)):
if str(a) == str(b):
return True
try:
return float(a) == float(b)
except ValueError:
return False
if isinstance(a, list) and isinstance(b, list):
return (
len(a) == len(b)
and all(any(director_same_value(x, y) for y in b) for x in a)
and all(any(director_same_value(x, y) for x in a) for y in b)
)
if isinstance(a, dict) and isinstance(b, dict):
keys = {k for k, v in a.items() if not _is_nullish(v)}
keys |= {k for k, v in b.items() if not _is_nullish(v)}
return all(director_same_value(a.get(k), b.get(k)) for k in keys)
return False
def director_sensitive_vars(datafields, customproperties):
"""
Return the names of the variables the Icinga Director marks as secret.
Parameters
----------
datafields : list
As `icingacli director export datafields` returns them. A data field with the
visibility "hidden" counts.
customproperties : list
As `icingacli director export customproperties` returns them (Director 1.12
and later). A custom variable of the type "sensitive", or with a member of that
type at any depth, counts.
Returns
-------
set
The variable names.
"""
names = set()
for field in datafields if isinstance(datafields, list) else []:
if not isinstance(field, dict):
continue
settings = field.get('settings') or {}
if isinstance(settings, dict) and settings.get('visibility') == 'hidden':
names.add(field.get('varname'))
def is_sensitive(prop):
if not isinstance(prop, dict):
return False
if prop.get('value_type') == 'sensitive':
return True
items = prop.get('items') or {}
return isinstance(items, dict) and any(map(is_sensitive, items.values()))
for prop in customproperties if isinstance(customproperties, list) else []:
if is_sensitive(prop):
names.add(prop.get('key_name'))
names.discard(None)
return names
def director_used_vars(command_vars, service_vars):
"""
Return the variables that reach a check command, directly or indirectly.
Extends the variables the check command uses by those that the values of used
variables refer to, for example a variable whose value is `$other_variable$`.
Parameters
----------
command_vars : set
As `director_command_vars()` returns them.
service_vars : dict
The variables of the service, as they apply on the host.
Returns
-------
set
"""
used = set(command_vars or ())
service_vars = service_vars if isinstance(service_vars, dict) else {}
todo = list(used)
while todo:
name = todo.pop()
for ref in _macro_vars(service_vars.get(name)) - used:
used.add(ref)
todo.append(ref)
return used
# Base64-encoded Icinga logo (PNG, 100x35 px).
_LOGO_PNG_BASE64 = """
iVBORw0KGgoAAAANSUhEUgAAAGQAAAAjCAQAAADItmcLAAAAAmJLR0QA/4ePzL8AAAAJcEhZcwAA
CxMAAAsTAQCanBgAAAAHdElNRQfhChAQLB+jeuiSAAAFCklEQVRYw9WYf0yVVRjHP5d7uYAo6JKf
Ggm4NtY0S1PyF6FLW239wRICLfmnQEv+snJmtbExwVzRD2eWs5xDpQbD5la2tlolRKHJQmqZrulF
B1oKBMiFe5/+uIeX9733fbkX18a95/3jfc/zPOc553vOeX69MHGzU0MPLrYT4W0Xop5NkQ3krAak
IbwXGhWE/4/JV0S2fG4jCH3khPdCbUElDjKTTg7xV2SfSBYNREfCQn02kk4dW035m6hnJHL2/UsE
YV0AfS5NxEYGBN+J9ABeHjQ5jwZum47L5DFmhJ+xR1POJZ7gGjW4iWMj84nnHAUUMmAyqoB6HHSx
lKvheDpOdnKAzXRpQbCXFaaSrYq/I3yv2mt4NBiCMOwHZTrL2cIVxS0L3zhykSw/SjMrgAQWsohF
pNNBOwPsYT4nKLawoCkHspB2E5lqUkimg3bO8QceRY1hOJyuksPQW2AqM0oNF/D6UYdNPKAd8ARI
ms16D9Pp4obl9kZhwxuCJou2zmAfY89aE8lCPiDbsAVNuJX8D6zRcZbxIXm6fgy7+VtJ/sTKAM2z
qeWG4p+l2AJoFXUkWgNJZSgARj8xAXJJjCLUa/1nGDaM8fKqxvsT4ZLWu48Og6SHaoPmB3Q+0/cc
87s1ACUIwpGJzmRvAJAaE6l7EYQ21VvNCILgpplmBtS4ZxX3FoKowBvL74p7mZ81yS2a3hSuKlon
LfSq79qA+X9UHjXVGkiCSlfGnlPYgwJpVxdqrroajQhCt1q8Hohvm1zkAxDHOwjCv5qn3I8gXCEX
gHjF95BpmH2ptro3JjqT9bTRgeDlIictClw9kFS17ESdKXciCNP8gDjpQ/CySqfpMwShSjkLH/8h
Hb8BQXjSMPsRDcg168w8mSaygVk4gFROkBQEyP0IwnsG/jJ+4ZBy7eNAFqhLE+hevlK3QX/OY2lr
M98YzDqFYYQRLiAIJVZAanna0C81PT49kFwE4WXLEx4H8ohJ7T9Pp+kuBKExiGd9HUE4TimC0GJe
sxdh0/kigKPkU2tqJ8YmIQdfj4Hm1XFsIWiKphyAtznGdSCXJeMBcQbrmcdNfqOE5/0Uuckmj4N0
TEGwXsIGHMAA++hWtKdIA1poBQ6wC6jw+UcHGZxW/sZDpTZgvG0jh/NTkjx9wWz1PYtt2mp8BuDz
ca8QTRHb6YEo3lIwwM6LJr+Hmtgd0sX5v5vofkAlq/diHlbnUkcdb9IHOH05uMNQ4CaRwK2wyQNX
s5Y57NFRKtR7g0GunGpGovyMb/J7P6LqFH2L5QVDvhVa8/hp6uYopwAYUttcZDounQJw0ESpRrpM
/6Sn912Axw1uej+leIifZKI/iGBjOYn0arRHAXABUEYM8DXvGqK8z+DrIYlftcJ2ZYhT6uOIXeWq
42niRgRhFKdfHMlHED41aMpAEM6o3ncqRkRr9dFNBGEN4MCFIIZMGpx0I4jvx4mdLBaTQ1zIe2fM
tSrURnzLVspoxIsgfBQQEIMDyVNjz/MSm9nHIILQig0oRBCTwq8SQfjkzswwE0H4XnOUxwNy5jMk
KO51hCFswCoE4bBBU5pKOMfajgBNLjIAOIwgPGdiIW7EskQL6uNP4tblOVHspF9XjXysM9lKPOwF
YBptDAY4gUZGdFYKxVoqLwifk6ZlZW5Om/4urMLD+7Y7do52P38Xw93MxE4/LvosJf1HmdHszCEJ
BwO4DMHAidvyR5b7P+7cOe8ELUP1AAAAAElFTkSuQmCC"""
def get_logo():
"""
Return the Icinga logo as PNG image bytes.
Provides the bundled Icinga logo as a 100x35 px PNG.
Returns
-------
bytes
The decoded PNG image data.
Examples
--------
>>> get_logo()[:8]
b'\\x89PNG\\r\\n\\x1a\\n'
"""
return base64.b64decode(_LOGO_PNG_BASE64)
def get_service(
uri,
username,
password,
servicename,
attrs='state',
insecure=False,
no_proxy=False,
proxy=None,
timeout=3,
):
"""
Query a service object from the Icinga API.
This function sends a high-level request to the Icinga `/v1/objects/services` endpoint
to retrieve attributes for a specific service, identified by its `__name`.
Parameters
----------
uri : str
Base API URL (e.g., `https://icinga.example.com:5665`).
username : str
API username.
password : str
API password.
servicename : str
Unique service name, typically in the format `hostname!service`.
attrs : str, optional
Comma-separated list of attributes to retrieve. Defaults to `'state'`.
insecure : bool, optional
Disable SSL certificate verification. Defaults to `False`.
no_proxy : bool, optional
Ignore proxy settings. Defaults to `False`.
proxy : str, optional
Proxy to reach the target through, overriding the one the environment names.
Defaults to `None`, which leaves the choice to the environment.
timeout : int, optional
Request timeout in seconds. Defaults to `3`.
Returns
-------
tuple (bool, object)
The result from the Icinga API request.
Notes
-----
- The `servicename` must match the `__name` attribute exactly. It is passed as a
filter variable, so quotes, backslashes and glob characters in it are taken
literally.
- Uses a `GET` override on a `POST` request (`X-HTTP-Method-Override` header).
Examples
--------
>>> uri = 'https://icinga.example.com:5665'
>>> result = lib.base.coe(
... lib.icinga.get_service(
... uri,
... args.USERNAME,
... args.PASSWORD,
... servicename='hostname!special-service',
... attrs='state,acknowledgement',
... )
... )
>>> print(result['result'][0]['attrs'])
"""
uri = f'{uri.rstrip("/")}/v1/objects/services'
# The name travels in `filter_vars`, so it is a value and never part of the
# filter expression: a `"` in it could otherwise add a filter of its own, and a
# trailing `\\` (a Windows path) broke the parse. `==` rather than `match()`,
# which compares globs and would let a `*` in the name select other services.