auto-starting on reboot without root

There are "correct" ways to execute programs automatically when a computer is rebooted. Unfortunately, it's different in different distributions. There's the complicated System V, and there's Ubuntu's newer solution, Upstart.

Neither is trivial to understand, especially for something you'll do rarely, if ever. But the worst part is that they both require root access to the server. If you don't have it you're usually screwed, and if you do have it but aren't seasoned, you'll probably make mistakes and, at the very least, have some public downtime for the reboots you'll need to do in order to test your solution.

What I'm about to describe is maybe a little dirty, but it works and I have found it useful -- especially on shared hosts and dedicated managed hosts which give the user very little access to the filesystem.

This technique solves two problems for me very nicely:

  1. Make sure Supervisor starts if the server is rebooted, so it can get my site and any other daemons running.
  2. For a case too simple for Supervisor, just make sure a given app is running after a reboot or if it's killed by the OS for any reason.

The Method

Create a simple bash that uses the pgrep command to see if a process is running. If not, just launch the process.

Then, schedule that script to run under cron once per minute.

Ta da!

Example

This is a simple example of how to make sure Redis is running:

#!/usr/bin/env/bash

pgrep -f redis-server -U username || /path/to/redis-server /path/to/redis.conf

Notes:

  • pgrep checks for running processes
  • The -f flag searches the full command line, not just the process name. For example, if you were checking for a Python script named foo.py, then by default pgrep would find a process named python, not foo.py. The -f flag tells pgrep to check the entire command.
  • the -U flag tells pgrep to only match that process if it's run by a specific user. It does you no good if someone else happens to be running a process with the same name as the one you want.
  • The || operator is the bash or operator. The commands following || will only be executed if the previous statement failed. The opposite of this is the && (and) operator.

The cron task:

* * * * * /home/username/bin/ensure_redis.sh

This runs every minute. Yes, it's wasteful and inelegant to run it every minute, but it's not a burden on the system and when it's what you have to work with, it's much better than your site going down or spewing errors.

Comments !

blogroll

social