Last active
July 16, 2020 11:02
-
-
Save soofstad/911c53a8dd0b7a6f3b32e7a2c96a9517 to your computer and use it in GitHub Desktop.
Sensu check for puppet-last-run in native python3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python3 | |
import argparse | |
import datetime | |
parser = argparse.ArgumentParser(description='Check Puppet status') | |
parser.add_argument('--summary-file', dest='puppet_status', | |
default="/opt/puppetlabs/puppet/cache/state/last_run_summary.yaml", | |
help=f"path to the puppet last_run_summary.yaml file. Defaults to '/opt/puppetlabs/puppet/cache/state/last_run_summary.yaml'") | |
parser.add_argument('--warn-age', type=int, default=3600, | |
help="Exits with '2'(warning) if last run older then this value(seconds). Defaults to 3600") | |
parser.add_argument('--crit-age', type=int, default=7200, | |
help="Exits with '1'(critical) if last run older then this value(seconds). Defaults to 7200") | |
parser.add_argument('--ignore-failures', action="store_true", | |
help="Failures in the puppet run does not affect the exit status. Default 'False'") | |
args = parser.parse_args() | |
status = {} | |
last_run = 0 | |
last_run_age = 0 | |
message = "" | |
def pretty_seconds(seconds: int): | |
days = seconds // (24 * 3600) | |
seconds = seconds % (24 * 3600) | |
hours = seconds // 3600 | |
seconds = seconds % 3600 | |
minutes = seconds // 60 | |
if days: | |
return f"{days}d:{hours}h:{minutes}m" | |
else: | |
return f"{hours}h:{minutes}m" | |
# All this to avoid none-standardlib dependencies. Like PyYaml | |
with open(args.puppet_status, "r") as stream: | |
for line in stream.readlines(): | |
if not line[0] == " ": | |
continue | |
stripped = line.strip() | |
key, value = stripped.split(": ", 1) | |
status[key] = value | |
if status.get("last_run"): | |
last_run = int(status["last_run"]) | |
last_run_age = int(datetime.datetime.now().timestamp()) - last_run | |
print(f"Puppet last run {pretty_seconds(last_run_age)} ago") | |
else: | |
print(f"Missing information about the last run timestamp") | |
exit(2) | |
if last_run_age > args.crit_age: | |
exit(2) | |
elif last_run_age > args.warn_age: | |
exit(1) | |
elif not args.ignore_failures and bool(int(status.get("failure", "0"))): | |
print(f"The last puppet run completed with {status.get('failure')} failures") | |
exit(1) | |
else: | |
exit(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment