From e95167262b0eb188234a260ba596501a7530600c Mon Sep 17 00:00:00 2001 From: Mike Gerber Date: Sat, 17 Dec 2016 17:12:36 +0100 Subject: [PATCH] Use dbus-python to query system state and failed units --- README.md | 4 +++- check_systemd_state | 50 +++++++++++++++++++++++++++------------------ 2 files changed, 33 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index e58ddc6..cd6c6e4 100644 --- a/README.md +++ b/README.md @@ -12,5 +12,7 @@ these commands: $ systemctl list-units $ systemctl status +Requires python-dbus. + License: Public Domain. Keep my name in it if you like. -Author: Mike Gerber 2015 +Author: Mike Gerber 2015, 2016 diff --git a/check_systemd_state b/check_systemd_state index dc37d4e..2b008e2 100755 --- a/check_systemd_state +++ b/check_systemd_state @@ -7,29 +7,39 @@ import subprocess import sys -def find_systemctl(): - systemctls = [ '/bin/systemctl', '/usr/bin/systemctl' ] - for systemctl in systemctls: - if posixpath.exists(systemctl): - return systemctl +try: + import dbus +except ImportError: + print("UNKNOWN: Please install python-dbus") + sys.exit(3) -systemctl = find_systemctl() -if not systemctl: - print('System WARN: systemctl not found') - sys.exit(1) +bus = dbus.SystemBus() +proxy = bus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1') + + +def get_system_state(): + """Get system state.""" + properties_manager = dbus.Interface(proxy, 'org.freedesktop.DBus.Properties') + system_state = properties_manager.Get('org.freedesktop.systemd1.Manager', 'SystemState') + return system_state -try: - state = subprocess.check_output([systemctl, 'is-system-running']) - state = state.strip() -except subprocess.CalledProcessError as e: - state = e.output.strip() - print('System NOT OK: {}'.format(state)) - sys.exit(2) -if state in ['running', 'starting']: - print('System OK: {}'.format(state)) +def get_failed_units(): + """Get a list of failed system units.""" + units = proxy.ListUnits(dbus_interface='org.freedesktop.systemd1.Manager') + failed_units = [] + for u in units: + service, _, loaded, active, state = u[:5] + if active == 'failed': + failed_units.append(service) + return failed_units + + +system_state = get_system_state() +if system_state in ['running', 'starting']: + print('System OK: {}'.format(system_state)) sys.exit(0) else: - print('System NOT OK: {}'.format(state)) - sys.exit(0) + print('System NOT OK: {}, failed: {}'.format(system_state, " ".join(get_failed_units()))) + sys.exit(2)