Wednesday, July 9, 2014

Upstart

If you have ever have a problem with php forking, upstart will be your good friend.

What is upstart?
In short: service management daemon

"Upstart is an event-based replacement for the /sbin/init daemon which handles starting of tasks and services during boot, stopping them during shutdown and supervising them while the system is running."

Let's make it clear (from our perspective):
You can start any of your (php) scripts as a daemon (even with arguments) with a handy toolset: status / start / stop / restart

Config your job (e.g. a script)
Pretend that you have a my-awesome-app.php, which you want to start as daemon on every system boot. Your script can easily become fragile, so you also want to monitor it with a respawn mechanism.

First, you have to create an upstart config and place it in the /etc/init directory. In this case it will be this one: /etc/init/my-awesome-app.conf

# /etc/init/my-awesome-app.conf
description "daemonized awesome app"
version "1.0"
author "adammbalogh"

# restart my app on a crash
respawn
# stop restarting my app if it crashes more than 5 times in 30 sec
respawn limit 5 30

# start my script after nginx started
start on started nginx
# stop it on system shutdown
stop on runlevel S

# run as user and group
setuid www-data
setgid www-data

script
  exec php /home/user/public_html/my-awesome-app.php
end script

After you've created this conf file, just start your app with upstart: sudo start my-awesome-app.conf

Misc
You can also create pre or post scripts with a simple statement.

pre-start script
  exec touch /tmp/myapp.log
end script

If you want to use configuration variable you can do it too.

env BYE=goodbye
post-start script
  exec echo $BYE >> /tmp/myapp.log
end script

Finally, a useful cmd which lists all jobs and their states: initctl list

No comments:

Post a Comment