PHP and Upstart

Up until recently I’d been using cron jobs to “kickstart” any failed/exited rabbitMQ consumers. It works, but didn’t come without its own problems, for example:

  • Cron jobs can be no more granular than 1 minute intervals, so if a cron fails, its could take up-to a minute to restart.
  • There is no simple way to terminate/start or restart a process.

So I did a bit of googling, I wanted something similar to forever.js, but for PHP. What I found was ubuntu service called upstart, its not specific to PHP; it is in-fact used by the OS to maintain system services.

With this wealth of information I was able to put together something along the lines of this:

###A simple example:

description "Sample Upstart Script"
author  "Ben Squire"

start on (net-device-up
          and local-filesystems
          and runlevel [2345])

stop on shutdown

respawn
respawn limit unlimited

script
    sudo -u root php -f /some/path/cli.php sample:command >> /var/logs/consumer.log 2>&1
end script

stored in:

/etc/init/example.conf

A really simple explanation:

  • This description and author are just descriptive information (i.e. not required)
  • The start-on parameters are events that the script is listening for, when all three of these events are triggered, this script will be launched.
  • Stop describes when upstart should stop the process (on shutdown in this case).
  • Respawn & Respawn limit describe if the process should be relaunched and how often the relaunch should be attempted (unlimited in this script).
  • The line between script and end-script describes the actual command that this upstart script is managing, you can see in the example above that I am triggering the PHP script and piping the output into a log file.

Manually controlling this service

Since we called the upstart script example.conf we can start, stop, restart and check the status our upstart script by running:

> start example
example start/running, process 26131

> stop example
example stop/waiting

> restart example
example start/running, process 26136

> status example
example start/running, process 26136

Note:

In the main example above,

(net-device-up and local-filesystems and runlevel [2345])

Is used to target a series of events used by our AWS EC2s boot process. Initially this was set to “startup”, but the scripts kept failing as either the the network interface was not yet active (preventing connection to our rabbitMQ service) or the file system was not yet writeable (preventing log output). This information was gratefully taken from here.

This is only a v.brief overview of what upstart is capable of and only a fraction of the available configuration, but it should be enough to get your started, good luck!

Ben Squire

Read more posts by this author.

Leicestershire, United Kingdom https://squired.co.uk