Skip to content

Instantly share code, notes, and snippets.

@lutter
Last active December 21, 2015 07:39
Show Gist options
  • Save lutter/6273067 to your computer and use it in GitHub Desktop.
Save lutter/6273067 to your computer and use it in GitHub Desktop.
Example of a systemd unit file and the script that it runs as a daemon. The script is from https://github.com/puppetlabs/razor-el-mk though I edited it a little to make the point a little clearer.
#!/usr/bin/env ruby
# This is the /usr/local/bin/mk referenced in mk.service, with slight edits for readability
require 'mk/script'
def usage(outcome, message = nil)
...
end
if ARGV[0] == "--daemon"
daemon = true
ARGV.shift
else
daemon = false
end
# Figure out, and dispatch, to our command.
command = ARGV.shift or usage(false, 'No command was supplied')
MK::Script.respond_to?(command) or usage(false, "Unknown command #{command.inspect}")
result = false
begin
loop do
result = MK::Script.send(command, *ARGV)
break unless daemon
sleep 15
puts "\nRunning at #{Time.now}"
end
rescue Exception => e
# FIXME: Be more discriminating about errors here; in particular,
# do not die in daemon mode if we have network trouble
# This would otherwise catch SystemExit, which we kind of don't want to do.
usage(false, "error running #{command}: #{e}")
end
exit result
[Unit]
Description=Microkernel agent
[Service]
Type=simple
WorkingDirectory=/var/lib/mk
StandardInput=null
StandardOutput=syslog
StandardError=inherit
SyslogIdentifier=microkernel
ExecStart=/usr/local/bin/mk --daemon register
# This is the killer: systemd will automatically restart the script
# if it dies (e.g., because of a SEGV) as long as that doesn't
# happen too often
Restart=always
[Install]
WantedBy=multi-user.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment