Tuesday, February 26, 2013

Options to run PHP scripts as daemons


PHP is mostly used as a front-end scripting language in a stateless fashion. What if you need to run a
PHP script like a daemon? An example use case would be a gearman worker or a PHP client for a message queue.

First, why is this an issue? You can just write a PHP program and start it from command line (that is what we will do in DEV env). However in real life this is an issue because the program started from command line
  •  + Should survive reboots
  •  + Should have ability to handle signals
  •  + Should spawn/kill workers depending on system load
What are our options? Let me list them below. My money would be on supervisord.

1) Write your own program that can do monitoring and spawn more child.
  •  + Example in PHP power programming
  •  + Example in Steven's Unix programming

Also see
The problems is that to pull it off you really need to be an accomplished Unix programmer.

2) using init.d standard scripts . init.d script would call a shell script that will start our PHP worker

Problems
  1.  - we have to understand / do infrastructure pieces
  2.  - graceful handling of signals
  3.  - restart when child dies

3) DJB's daemon tools at http://cr.yp.to/daemontools.html

people swear by it. However I have not used it.


4) nohup and screen technique - Run scripts in GNU screen and come out of SSH.

  1.  + issue: no supervision - job may do bad thing and die 
  2.  + some watch script is needed. Too flaky.

5) python daemons at http://pypi.python.org/pypi/python-daemon/

Also see sander marechal's script (python2)
http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/

6) Try upstart with respawn on Ubuntu
 + should work, atleast theoretically. That is how I was running php-fcgi daemon in Ubuntu Lucid.

7) Gearman Manager
PECL extension did not work for me. I have used PEAR version in my DEV enviroment.

7) Perp
http://b0llix.net/perp/

8) supervisord
http://supervisord.org/

@see also using gearman with supervisord
http://stackoverflow.com/questions/8217848/running-gearman-workers-in-the-background

9) libslack daemon (used by kestrel) - http://libslack.org/daemon/


10) Others

phpdeamon - http://phpdaemon.net/
Fat controller - http://fat-controller.sourceforge.net/getting-started.html

Daemonize - http://software.clapper.org/daemonize/
restartd - https://launchpad.net/ubuntu/+source/restartd/

PEAR system_deamon


PHP-daemon
https://github.com/shaneharter/PHP-Daemon

© Life of a third world developer
Maira Gall