forked from kbytesys/pynagsystemd
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathcheck_systemd.py
executable file
·2093 lines (1708 loc) · 67.7 KB
/
check_systemd.py
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
"""
``check_system`` is a `Nagios <https://www.nagios.org>`_ / `Icinga
<https://icinga.com>`_ monitoring plugin to check systemd. This Python script
will report a degraded system to your monitoring solution. It can also be used
to monitor individual systemd services (with the ``-u, --unit`` parameter) and
timers units (with the ``-t, --dead-timers`` parameter).
To learn more about the project, please visit the repository on `Github
<https://github.com/Josef-Friedrich/check_systemd>`_.
Monitoring scopes
=================
* ``units``: State of unites
* ``timers``: Timers
* ``startup_time``: Startup time
* ``performance_data``: Performance data
Data sources
============
* D-Bus (``dbus``)
* Command line interface (``cli``)
This plugin is based on a Python package named `nagiosplugin
<https://pypi.org/project/nagiosplugin/>`_. ``nagiosplugin`` has a fine-grained
class model to separate concerns. A Nagios / Icinga plugin must perform these
three steps: data `acquisition`, `evaluation` and `presentation`.
``nagiosplugin`` provides for this three steps three classes: ``Resource``,
``Context``, ``Summary``. ``check_systemd`` extends this three model classes in
the following subclasses:
Acquisition (``Resource``)
==========================
* :class:`UnitsResource` (``context=units``)
* :class:`TimersResource` (``context=timers``)
* :class:`StartupTimeResource` (``context=startup_time``)
* :class:`PerformanceDataResource` (``context=performance_data``)
Evaluation (``Context``)
========================
* :class:`UnitsContext` (``context=units``)
* :class:`TimersContext` (``context=timers``)
* :class:`StartupTimeContext` (``context=timers``)
* :class:`PerformanceDataContext` (``context=performance_data``)
Presentation (``Summary``)
==========================
* :class:`SystemdSummary`
"""
from __future__ import annotations
import argparse
import logging
import re
import subprocess
from abc import abstractmethod
from dataclasses import dataclass
from datetime import datetime
from typing import (
Any,
Generator,
Generic,
Iterable,
Literal,
MutableSequence,
NamedTuple,
Optional,
Sequence,
TypeVar,
Union,
cast,
get_args,
overload,
)
try:
import nagiosplugin
from nagiosplugin.check import Check
from nagiosplugin.context import Context, ScalarContext
from nagiosplugin.error import CheckError
from nagiosplugin.metric import Metric
from nagiosplugin.performance import Performance
from nagiosplugin.range import Range
from nagiosplugin.resource import Resource
from nagiosplugin.result import Result, Results
from nagiosplugin.state import Critical, Ok, ServiceState, Warn
from nagiosplugin.summary import Summary
except ImportError:
print("Failed to import the NagiosPlugin library.")
exit(3)
is_dbus = True
try:
# Look for gi https://gnome.pages.gitlab.gnome.org/pygobject
from gi.repository.Gio import BusType, DBusProxy, DBusProxyFlags
except ImportError:
# Fallback to the command line interface source.
is_dbus = False
__version__: str = "4.1.0"
ActiveState = Literal[
"active", "reloading", "inactive", "failed", "activating", "deactivating"
]
"""From the `D-Bus interface of systemd documentation
<https://www.freedesktop.org/software/systemd/man/org.freedesktop.systemd1.html#Properties1>`_:
``ActiveState`` contains a state value that reflects whether the unit
is currently active or not. The following states are currently defined:
* ``active``,
* ``reloading``,
* ``inactive``,
* ``failed``,
* ``activating``, and
* ``deactivating``.
``active`` indicates that unit is active (obviously...).
``reloading`` indicates that the unit is active and currently reloading
its configuration.
``inactive`` indicates that it is inactive and the previous run was
successful or no previous run has taken place yet.
``failed`` indicates that it is inactive and the previous run was not
successful (more information about the reason for this is available on
the unit type specific interfaces, for example for services in the
Result property, see below).
``activating`` indicates that the unit has previously been inactive but
is currently in the process of entering an active state.
Conversely ``deactivating`` indicates that the unit is currently in the
process of deactivation.
"""
SubState = Literal[
"abandoned",
"activating-done",
"activating",
"active",
"auto-restart",
"cleaning",
"condition",
"deactivating-sigkill",
"deactivating-sigterm",
"deactivating",
"dead",
"elapsed",
"exited",
"failed",
"final-sigkill",
"final-sigterm",
"final-watchdog",
"listening",
"mounted",
"mounting-done",
"mounting",
"plugged",
"reload",
"remounting-sigkill",
"remounting-sigterm",
"remounting",
"running",
"start-chown",
"start-post",
"start-pre",
"start",
"stop-post",
"stop-pre-sigkill",
"stop-pre-sigterm",
"stop-pre",
"stop-sigkill",
"stop-sigterm",
"stop-watchdog",
"stop",
"tentative",
"unmounting-sigkill",
"unmounting-sigterm",
"unmounting",
"waiting",
]
"""From the `D-Bus interface of systemd documentation
<https://www.freedesktop.org/software/systemd/man/org.freedesktop.systemd1.html#Properties1>`_:
``SubState`` encodes states of the same state machine that
``ActiveState`` covers, but knows more fine-grained states that are
unit-type-specific. Where ``ActiveState`` only covers six high-level
states, ``SubState`` covers possibly many more low-level
unit-type-specific states that are mapped to the six high-level states.
Note that multiple low-level states might map to the same high-level
state, but not vice versa. Not all high-level states have low-level
counterparts on all unit types.
All sub states are listed in the file `basic/unit-def.c
<https://github.com/systemd/systemd/blob/main/src/basic/unit-def.c>`_
of the systemd source code:
* automount: ``dead``, ``waiting``, ``running``, ``failed``
* device: ``dead``, ``tentative``, ``plugged``
* mount: ``dead``, ``mounting``, ``mounting-done``, ``mounted``,
``remounting``, ``unmounting``, ``remounting-sigterm``,
``remounting-sigkill``, ``unmounting-sigterm``,
``unmounting-sigkill``, ``failed``, ``cleaning``
* path: ``dead``, ``waiting``, ``running``, ``failed``
* scope: ``dead``, ``running``, ``abandoned``, ``stop-sigterm``,
``stop-sigkill``, ``failed``
* service: ``dead``, ``condition``, ``start-pre``, ``start``,
``start-post``, ``running``, ``exited``, ``reload``, ``stop``,
``stop-watchdog``, ``stop-sigterm``, ``stop-sigkill``, ``stop-post``,
``final-watchdog``, ``final-sigterm``, ``final-sigkill``, ``failed``,
``auto-restart``, ``cleaning``
* slice: ``dead``, ``active``
* socket: ``dead``, ``start-pre``, ``start-chown``, ``start-post``,
``listening``, ``running``, ``stop-pre``, ``stop-pre-sigterm``,
``stop-pre-sigkill``, ``stop-post``, ``final-sigterm``,
``final-sigkill``, ``failed``, ``cleaning``
* swap: ``dead``, ``activating``, ``activating-done``, ``active``,
``deactivating``, ``deactivating-sigterm``, ``deactivating-sigkill``,
``failed``, ``cleaning``
* target:``dead``, ``active``
* timer: ``dead``, ``waiting``, ``running``, ``elapsed``, ``failed``
"""
LoadState = Literal[
"stub", "loaded", "not-found", "bad-setting", "error", "merged", "masked"
]
"""
`src/basic/unit-def.c#L95-L103 <https://github.com/systemd/systemd/blob/1f901c24530fb9b111126381a6ea101af8040e65/src/basic/unit-def.c#L95-L103>`_
From the `D-Bus interface of systemd documentation
<https://www.freedesktop.org/software/systemd/man/org.freedesktop.systemd1.html#Properties1>`_:
``LoadState`` contains a state value that reflects whether the
configuration file of this unit has been loaded. The following states
are currently defined:
* ``loaded``,
* ``error`` and
* ``masked``.
``loaded`` indicates that the configuration was successfully loaded.
``error`` indicates that the configuration failed to load, the
``LoadError`` field contains information about the cause of this
failure.
``masked`` indicates that the unit is currently masked out (i.e.
symlinked to /dev/null or suchlike).
Note that the ``LoadState`` is fully orthogonal to the ``ActiveState``
(see below) as units without valid loaded configuration might be active
(because configuration might have been reloaded at a time where a unit
was already active).
"""
UnitType = Literal[
"service",
"service",
"socket",
"target",
"device",
"mount",
"automount",
"timer",
"swap",
"path",
"slice",
"scope",
]
T = TypeVar("T")
"""For UnitCache. Can not be an inner typevar because of pylance"""
class Logger:
"""A wrapper around the Python logging module with 3 debug logging levels.
1. ``-d``: info
2. ``-dd``: debug
3. ``-ddd``: verbose
"""
__logger: logging.Logger
__BLUE = "\x1b[0;34m"
__PURPLE = "\x1b[0;35m"
__CYAN = "\x1b[0;36m"
__RESET = "\x1b[0m"
__INFO = logging.INFO
__DEBUG = logging.DEBUG
__VERBOSE = 5
def __init__(self) -> None:
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("%(message)s"))
logging.basicConfig(handlers=[handler])
self.__logger = logging.getLogger(__name__)
def set_level(self, level: int) -> None:
# NOTSET=0
# custom level: VERBOSE=5
# DEBUG=10
# INFO=20
# WARN=30
# ERROR=40
# CRITICAL=50
if level == 1:
self.__logger.setLevel(logging.INFO)
elif level == 2:
self.__logger.setLevel(logging.DEBUG)
elif level > 2:
self.__logger.setLevel(5)
def __log(self, level: int, color: str, msg: str, *args: object) -> None:
a: list[str] = []
for arg in args:
a.append(color + str(arg) + self.__RESET)
self.__logger.log(level, msg, *a)
def info(self, msg: str, *args: object) -> None:
"""Log on debug level ``1``: ``-d``.
:param msg: A message format string. Note that this means that you can
use keywords in the format string, together with a single
dictionary argument. No ``%`` formatting operation is performed on
``msg`` when no args are supplied.
:param args: The arguments which are merged into ``msg`` using the
string formatting operator.
"""
self.__log(self.__INFO, self.__BLUE, msg, *args)
def debug(self, msg: str, *args: object) -> None:
"""Log on debug level ``2``: ``-dd``.
:param msg: A message format string. Note that this means that you can
use keywords in the format string, together with a single
dictionary argument. No ``%`` formatting operation is performed on
``msg`` when no args are supplied.
:param args: The arguments which are merged into ``msg`` using the
string formatting operator.
"""
self.__log(self.__DEBUG, self.__PURPLE, msg, *args)
def verbose(self, msg: str, *args: object) -> None:
"""Log on debug level ``3``: ``-ddd``
:param msg: A message format string. Note that this means that you can
use keywords in the format string, together with a single
dictionary argument. No ``%`` formatting operation is performed on
``msg`` when no args are supplied.
:param args: The arguments which are merged into ``msg`` using the
string formatting operator.
"""
self.__log(self.__VERBOSE, self.__CYAN, msg, *args)
def show_levels(self) -> None:
msg = "log level %s (%s): %s"
self.info(msg, 1, "info", "-d")
self.debug(msg, 2, "debug", "-dd")
self.verbose(msg, 3, "verbose", "-ddd")
logger = Logger()
class Source:
class BaseUnit:
name: str
"""The name of the system unit, for example ``nginx.service``. In the
command line table of the command ``systemctl list-units`` is the
column containing unit names titled with “UNIT”.
"""
class Unit(BaseUnit):
"""This class bundles all state related informations of a systemd unit in a
object. This class is inherited by the class ``DbusUnit`` and the
attributes are overwritten by properties.
"""
active_state: ActiveState
sub_state: SubState
load_state: LoadState
@staticmethod
def __check_active_state(state: object) -> ActiveState:
states: tuple[ActiveState] = get_args(ActiveState)
if state in states:
# https://github.com/python/mypy/issues/9718
return state # type: ignore
raise ValueError(f"Invalid active state: {state}")
@staticmethod
def __check_sub_state(state: object) -> SubState:
states: tuple[SubState] = get_args(SubState)
if state in states:
return state # type: ignore
raise ValueError(f"Invalid sub state: {state}")
@staticmethod
def __check_load_state(state: object) -> LoadState:
states: tuple[LoadState] = get_args(LoadState)
if state in states:
return state # type: ignore
raise ValueError(f"Invalid load state: {state}")
def __init__(
self,
name: str,
active_state: Optional[object] = None,
sub_state: Optional[object] = None,
load_state: Optional[object] = None,
) -> None:
self.name = name
self.active_state = self.__check_active_state(active_state)
self.sub_state = self.__check_sub_state(sub_state)
self.load_state = self.__check_load_state(load_state)
logger.debug(
"Create unit object: name: %s, active_state: %s, sub_state: %s, load_state: %s",
self.name,
self.active_state,
self.sub_state,
self.load_state,
)
def convert_to_exitcode(self) -> ServiceState:
"""Convert the different systemd states into a Nagios compatible
exit code.
:return: A Nagios compatible exit code: 0, 1, 2, 3
"""
if opts.expected_state and opts.expected_state.lower() != self.active_state:
return Critical
if self.load_state == "error" or self.active_state == "failed":
return Critical
return Ok
@dataclass
class Timer(BaseUnit):
"""
# Dbus doc
# readonly t NextElapseUSecRealtime = ...;
# readonly t NextElapseUSecMonotonic = ...;
# readonly t LastTriggerUSec = ...;
# readonly t LastTriggerUSecMonotonic = ...;
# NextElapseUSecRealtime contains the next elapsation point on the CLOCK_REALTIME clock in miscroseconds since the epoch, or 0 if this timer event does not include at least one calendar event.
# Similarly, NextElapseUSecMonotonic contains the next elapsation point on the CLOCK_MONOTONIC clock in microseconds since the epoch, or 0 if this timer event does not include at least one monotonic event.
# https://github.com/systemd/systemd/blob/e0270bab43a4c37028ee32ae853037df22999767/src/systemctl/systemctl-list-units.c#L668-L671'
# TABLE_TIMESTAMP, t->next_elapse,
# TABLE_TIMESTAMP_LEFT, t->next_elapse,
# TABLE_TIMESTAMP, t->last_trigger.realtime,
# TABLE_TIMESTAMP_RELATIVE_MONOTONIC, t->last_trigger.monotonic,
# https://github.com/systemd/systemd/blob/e0270bab43a4c37028ee32ae853037df22999767/src/core/dbus-timer.c#L111
# SD_BUS_PROPERTY("NextElapseUSecRealtime", "t", bus_property_get_usec, offsetof(Timer, next_elapse_realtime), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
# SD_BUS_PROPERTY("NextElapseUSecMonotonic", "t", property_get_next_elapse_monotonic, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
# BUS_PROPERTY_DUAL_TIMESTAMP("LastTriggerUSec", offsetof(Timer, last_trigger), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
"""
name: str
last: Optional[int]
"""Timestamp"""
next: Optional[int]
"""Timestamp"""
class NameFilter:
"""This class stores all system unit names (e. g. ``nginx.service`` or
``fstrim.timer``) and provides a interface to filter the names by regular
expressions."""
__unit_names: set[str]
def __init__(self, unit_names: Sequence[str] = ()) -> None:
self.__unit_names = set(unit_names)
def __iter__(self) -> Generator[str, None, None]:
for name in sorted(self.__unit_names):
yield name
@staticmethod
def match(unit_name: str, regexes: str | Sequence[str]) -> bool:
"""
Match multiple regular expressions against a unit name.
:param unit_name: The unit name to be matched.
:param regexes: A single regular expression (``include='.*service'``) or a
list of regular expressions (``include=('.*service', '.*mount')``).
:return: True if one regular expression matches"""
if isinstance(regexes, str):
regexes = [regexes]
for regex in regexes:
try:
if re.match(regex, unit_name):
return True
except Exception:
raise CheckSystemdRegexpError(
"Invalid regular expression: '{}'".format(regex)
)
return False
def add(self, unit_name: str) -> None:
"""Add one unit name.
:param unit_name: The name of the unit, for example ``apt.timer``.
"""
self.__unit_names.add(unit_name)
def get(self) -> set[str]:
"""Get all stored unit names."""
return self.__unit_names
def filter(
self,
include: str | Sequence[str] | None = None,
exclude: str | Sequence[str] | None = None,
) -> Generator[str, None, None]:
"""
List all unit names or apply filters (``include`` or ``exclude``) to
the list of unit names.
:param include: If the unit name matches the provided regular
expression, it is included in the list of unit names. A single
regular expression (``include='.*service'``) or a list of regular
expressions (``include=('.*service', '.*mount')``).
:param exclude: If the unit name matches the provided regular
expression, it is excluded from the list of unit names. A single
regular expression (``exclude='.*service'``) or a list of regular
expressions (``exclude=('.*service', '.*mount')``).
"""
match = Source.NameFilter.match
for name in sorted(self.__unit_names):
output: Optional[str] = name
if include and not match(name, include):
output = None
if output and exclude and match(name, exclude):
output = None
if output:
yield output
class Cache(Generic[T]):
"""This class is a container class for systemd units."""
__units: dict[str, T]
__name_filter: Source.NameFilter
def __init__(self) -> None:
self.__units = {}
self.__name_filter = Source.NameFilter()
def __iter__(self) -> Generator[T, None, None]:
for name in self.__name_filter:
yield self.__units[name]
def add(self, name: str, unit: T) -> None:
self.__units[name] = unit
self.__name_filter.add(name)
def get(self, name: Optional[str] = None) -> T | None:
if name:
return self.__units[name]
return None
def filter(
self,
include: str | Sequence[str] | None = None,
exclude: str | Sequence[str] | None = None,
) -> Generator[T, None, None]:
"""
List all units or apply filters (``include`` or ``exclude``) to
the list of unit.
:param include: If the unit name matches the provided regular
expression, it is included in the list of unit names. A single
regular expression (``include='.*service'``) or a list of regular
expressions (``include=('.*service', '.*mount')``).
:param exclude: If the unit name matches the provided regular
expression, it is excluded from the list of unit names. A single
regular expression (``exclude='.*service'``) or a list of regular
expressions (``exclude=('.*service', '.*mount')``).
"""
for name in self.__name_filter.filter(include=include, exclude=exclude):
yield self.__units[name]
@property
def count(self) -> int:
return len(self.__units)
def count_by_states(
self,
states: Sequence[str],
include: str | Sequence[str] | None = None,
exclude: str | Sequence[str] | None = None,
) -> dict[str, int]:
states_normalized: list[dict[str, str]] = []
counter: dict[str, int] = {}
for state_spec in states:
# state_proerty:state_value
# for example: active_state:failed
state_property = state_spec.split(":")[0]
state_value = state_spec.split(":")[1]
state: dict[str, str] = {
"property": state_property,
"value": state_value,
"spec": state_spec,
}
states_normalized.append(state)
counter[state_spec] = 0
for unit in self.filter(include=include, exclude=exclude):
for state in states_normalized:
if getattr(unit, state["property"]) == state["value"]:
counter[state["spec"]] += 1
return counter
_user: bool = False
def _round_1(
self,
value: float,
) -> float:
return round(value, 1)
def _usec_to_sec(
self,
usec: int,
) -> int:
return int(usec / 1_000_000)
@staticmethod
def get_interface_name_from_unit_name(unit_name: str) -> str:
"""
:param name: for example apt-daily.service
:return: org.freedesktop.systemd1.Service
"""
name_segments = unit_name.split(".")
interface_name = name_segments[-1]
return "org.freedesktop.systemd1.{}".format(interface_name.title())
@staticmethod
def get_interface_name_from_object_path(object_path: str) -> str:
"""
:param object_path: for example
``/org/freedesktop/systemd1/unit/apt_2ddaily_2eservice``
:return: org.freedesktop.systemd1.Service
"""
name_segments = object_path.split("_2e")
interface_name = name_segments[-1]
return "org.freedesktop.systemd1.{}".format(interface_name.title())
@staticmethod
def is_unit_type(unit_name_or_object_path: str, type_name: UnitType) -> bool:
return (
re.match(".*(\\.|_2e)" + type_name + "$", unit_name_or_object_path)
is not None
)
def set_user(self, user: bool) -> None:
self._user = user
@abstractmethod
def get_unit(self, name: str) -> Source.Unit: ...
@property
@abstractmethod
def _all_units(self) -> Generator[Source.Unit, Any, None]: ...
@property
def units(self) -> Source.Cache[Source.Unit]:
cache: Source.Cache[Source.Unit] = Source.Cache()
for unit in self._all_units:
cache.add(unit.name, unit)
return cache
@property
@abstractmethod
def startup_time(self) -> float | None: ...
@property
@abstractmethod
def _all_timers(self) -> list[Source.Timer]: ...
@property
def timers(self) -> Source.Cache[Source.Timer]:
cache: Source.Cache[Source.Timer] = Source.Cache()
for timer in self._all_timers:
cache.add(timer.name, timer)
return cache
class CliSource(Source):
class Table:
"""This class reads the text tables that some systemd commands like
``systemctl list-units`` or ``systemctl list-timers`` produce."""
header_row: str
body_rows: list[str]
column_lengths: list[int]
columns: list[str]
def __init__(self, stdout: str) -> None:
"""
:param stdout: The standard output of certain systemd command line
utilities.
:param expected_column_headers: The expected column headers
(for example ``('UNIT', 'LOAD', 'ACTIVE')``)
"""
rows: list[str] = stdout.splitlines()
self.header_row = CliSource.Table.__normalize_header(rows[0])
self.column_lengths = CliSource.Table.__detect_lengths(self.header_row)
self.columns = CliSource.Table.__split_row(
self.header_row, self.column_lengths
)
counter = 0
for line in rows:
# The table footer is separted by a blank line
if line == "":
break
counter += 1
self.body_rows = rows[1:counter]
@staticmethod
def __normalize_header(header_row: str) -> str:
"""Normalize the header row
:param header_row: The first line of a systemd table output.
"""
return header_row.lower()
@staticmethod
def __detect_lengths(header_row: str) -> list[int]:
"""
:param header_row: The first line of a systemd table output.
:return: A list of column lengths in number of characters.
"""
column_lengths: list[int] = []
match = re.search(r"^ +", header_row)
if match:
whitespace_prefix_length = match.end()
column_lengths.append(whitespace_prefix_length)
header_row = header_row[whitespace_prefix_length:]
word = 0
space = 0
for char in header_row:
if word and space >= 1 and char != " ":
column_lengths.append(word + space)
word = 0
space = 0
if char == " ":
space += 1
else:
word += 1
return column_lengths
@staticmethod
def __split_row(line: str, column_lengths: list[int]) -> list[str]:
columns: list[str] = []
right = 0
for length in column_lengths:
left = right
right = right + length
columns.append(line[left:right].strip())
columns.append(line[right:].strip())
return columns
@property
def row_count(self) -> int:
"""The number of rows. Only the body rows are counted. The header row
is not taken into account."""
return len(self.body_rows)
def check_header(self, column_header: Sequence[str]) -> None:
"""Check if the specified column names are present in the header row of
the text table. Raise an exception if not.
:param column_headers: The expected column headers
(for example ``('UNIT', 'LOAD', 'ACTIVE')``)
"""
for column_name in column_header:
if self.header_row.find(column_name.lower()) == -1:
msg = (
"The column heading '{}' couldn’t found in the "
"table header. Possibly the table layout of systemctl "
"has changed."
)
raise ValueError(msg.format(column_name))
def get_row(self, row_number: int) -> dict[str, str]:
"""Retrieve a table row as a dictionary. The keys are taken from the
header row. The first row number is 0.
:param row_number: The index number of the table row starting at 0.
"""
body_columns = CliSource.Table.__split_row(
self.body_rows[row_number], self.column_lengths
)
result: dict[str, str] = {}
index = 0
for column in self.columns:
if column == "":
key = "column_{}".format(index)
else:
key = column
result[key] = body_columns[index]
index += 1
return result
def list_rows(self) -> Generator[dict[str, str], None, None]:
"""List all rows."""
for i in range(0, self.row_count):
yield self.get_row(i)
@staticmethod
def __execute_cli(args: str | Sequence[str]) -> str | None:
"""Execute a command on the command line (cli = command line interface))
and capture the stdout. This is a wrapper around ``subprocess.Popen``.
:param args: A list of programm arguments.
:raises nagiosplugin.CheckError: If the command produces some stderr output
or if an OSError exception occurs.
:return: The stdout of the command.
"""
try:
p = subprocess.Popen(
args,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
)
stdout, stderr = p.communicate()
logger.debug("Execute command on the command line: %s", " ".join(args))
except OSError as e:
raise CheckError(e)
if p.returncode != 0:
raise CheckError(
"The command exits with a none-zero return code ({})".format(
p.returncode
)
)
if stderr:
raise CheckError(stderr)
if stdout:
result = stdout.decode("utf-8")
logger.verbose("stdout:\n%s", result)
return result
return None
@staticmethod
def __convert_to_sec(fmt_timespan: str) -> float:
"""Convert a timespan format string to seconds. Take a look at the
systemd `time-util.c
<https://github.com/systemd/systemd/blob/master/src/basic/time-util.c>`_
source code.
:param fmt_timespan: for example ``2.345s`` or ``3min 45.234s`` or
``34min left`` or ``2 months 8 days``
:return: The seconds
"""
for replacement in [
["years", "y"],
["months", "month"],
["weeks", "w"],
["days", "d"],
]:
fmt_timespan = fmt_timespan.replace(" " + replacement[0], replacement[1])
seconds = {
"y": 31536000, # 365 * 24 * 60 * 60
"month": 2592000, # 30 * 24 * 60 * 60
"w": 604800, # 7 * 24 * 60 * 60
"d": 86400, # 24 * 60 * 60
"h": 3600, # 60 * 60
"min": 60,
"s": 1,
"ms": 0.001,
}
result: float = 0
for span in fmt_timespan.split():
match = re.search(r"([\d\.]+)([a-z]+)", span)
if match:
value = match.group(1)
unit = match.group(2)
result += float(value) * seconds[unit]
return round(float(result), 3)
@staticmethod
def __convert_to_timestamp(date_format: str) -> int:
return int(
datetime.strptime(date_format, "%a %Y-%m-%d %H:%M:%S %Z").timestamp()
)
def get_unit(self, name: str) -> Source.Unit:
stdout = CliSource.__execute_cli(
[
"systemctl",
"show",
"--property",
"Id",
"--property",
"ActiveState",
"--property",
"SubState",
"--property",
"LoadState",
name,
]
)
if stdout is None:
raise CheckSystemdError(f"The unit '{name}' couldn't be found.")
rows = stdout.splitlines()
properties: dict[str, str] = {}
for row in rows:
index_equal_sign = row.index("=")
properties[row[:index_equal_sign]] = row[index_equal_sign + 1 :]
logger.debug("Properties of unit '%s': %s", name, properties)
return Source.Unit(
name=properties["Id"],
active_state=properties["ActiveState"],
sub_state=properties["SubState"],
load_state=properties["LoadState"],
)
@property
def _all_units(self) -> Generator[Source.Unit, None, None]:
command = ["systemctl", "list-units", "--all"]
if self._user:
command += ["--user"]
stdout = CliSource.__execute_cli(command)
if stdout:
table_parser = self.Table(stdout)
table_parser.check_header(("unit", "active", "sub", "load"))
for row in table_parser.list_rows():
yield self.Unit(
name=row["unit"],
active_state=row["active"],
sub_state=row["sub"],
load_state=row["load"],
)
@property
def startup_time(self) -> float | None:
stdout = None
try:
stdout = CliSource.__execute_cli(["systemd-analyze"])
except CheckError:
pass
if stdout:
# First line:
# Startup finished in 1.672s (kernel) + 21.378s (userspace) =
# 23.050s
# On raspian no second line
# Second line: