Last active
December 8, 2017 09:50
-
-
Save tierpod/728a52d513af6cd86f1795247a0b1804 to your computer and use it in GitHub Desktop.
Example for wrapper around ExecStart= for success/failed service notifications
This file contains 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/python3 | |
# try this for long-running processes: | |
# | |
# $ cat example.service | |
# ... | |
# Type=simple | |
# ExecStart=systemd-notify-wrapper.py "/opt/scripts/long-running.sh -a -b FLAG" "%n" | |
# ... | |
# | |
# send "successful complete" notification if exit code valid | |
# send "failure" notification otherwise, add "systemctl status example" to notification | |
import shlex | |
import subprocess | |
import sys | |
import time | |
cmd = sys.argv[1] | |
service = sys.argv[2] | |
rc_valid = [0,] | |
receivers = "user1,user2".split(",") | |
start_time = time.time() | |
proc = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) | |
print("proc started, pid %d" % proc.pid) | |
while proc.poll() is None: | |
print(proc.stdout.readline().rstrip().decode("utf-8")) | |
rc = proc.poll() | |
delta_time = round(time.time() - start_time, 2) | |
if delta_time > 3600: | |
ts = "%sh" % delta_time/3600 | |
elif delta_time > 60: | |
ts = "%sm" % delta_time/60 | |
else: | |
ts = "%ss" % delta_time | |
if rc in rc_valid: | |
print("proc done with exit code %d" % rc) | |
msg = "service %s complete in %s" % (service, ts) | |
else: | |
print("proc failed with exit code %d" % rc) | |
try: | |
output = subprocess.check_output(["/bin/systemctl", "status", "-q", service], stderr=subprocess.STDOUT) | |
except subprocess.CalledProcessError as err: | |
if err.output: | |
output = err.output | |
msg = """service %s failed in %s | |
Details: | |
%s""" % (service, ts, output.decode("utf-8")) | |
print("send '%s' to '%s'" % (msg, receivers)) | |
exit(rc) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment