Example Starting A Script With Systemd
2017.01.19 by John Boteler
I modified a script originally written by Anthony Minessale II that responds to particular events emitted by the FreeSWITCH conference module. During development it was natural to stop and start the script manually whenever I needed to edit it. But when it came time to install it for continuous use I realized that I didn't know how to start the script automatically.
Click here to expand Table of Contents
It's a perl script, but I discovered that you can't use that
param name="startup-script" line in autoload_configs/perl.conf.xml since that only works with embedded scripts running in the FreeSWITCH mod_perl instance; my script runs totally external to FreeSWITCH using the perl interpreter and simply awaits events over the Event Socket and responds to them as needed.
Ken Rice suggested systemd since that not only is easy to configure, but handles logging of stdout as well. It worked great!
You tell systemd what to do in a "unit file" stored in /etc/systemd/system which is where local variants go so that they won't be overwritten by updates to installed packages.
[Unit] section indicates that the script requires freeswitch.service, and moreover FreeSWITCH must be running before the script can be invoked. Without the
After directive systemd would start FreeSWITCH and the script in parallel. In this case it is not mandatory to have FreeSWITCH running first, but it is pointless for the script to try to connect to the event socket when it can't possibly be there yet.
[Service] section of the unit file tells systemd exactly how to run the script, including the user and group under which to start it and what to do if it fails. I chose
Type=simple because this perl script is long-running, never forks, and never exits under normal circumstances. I chose
Restart=on-failure to restart the script if it does not start properly, but not if I simply kill it for maintenance. If I had chosen
Restart=always then systemd would restart the script behind my back while I'm trying to work on it and we don't want that!
[Install] section connects this script to the boot sequence of events by tying it to FreeSWITCH. This section is necessary to invoke the
systemd enable command which creates a symbolic link to this unit file from a sub-directory created for FreeSWITCH targets.
systemd unit file
# I doubt the WorkingDirectory is actually needed for this trivial example, but I used it just in case
I was amazed at how quickly and cleanly everything started when I rebooted the machine to observe how it all worked. I gather that there is a faction of die-hards who loathe systemd, but times change so I am happy to report that systemd makes the job of starting services and scripts much simpler. I know I struggled enough times with SysV init scripts that I welcome this new systemd of doing things.