Search code examples
phpubuntuupstart

Run PHP script with Upstart after reboot


I have the following Upstart script. When I run the following command service worker-1 start, everything works perfect. I can see running workers with ps aux | grep php. I can also use service worker-1 stop which I need to restart/update workers. But unfortunately this script works only partially on reboot. The script is executed (start: Job is already running: worker-1 when I try service worker-1 start) but I do not see any running workers with ps aux | grep php and of course service worker-1 stop returns stop: Unknown instance:. Do you have any idea what can be wrong?

description "Starts/kills workers."
author "Jiri Mihal"
start on (started php5-fpm and started mysql)
stop on shutdown

pre-start script
    echo "[`date`] Workers started" >> /var/log/worker-1.log
    exec 2>>/var/log/worker-1.log
end script

post-start script
    echo $$ > /var/run/worker-1.pid
    for i in `seq 1 5`;
    do
        exec php /home/jiri/workers/dlapi.workers/workers/RpcWorkerLauncher.php Worker-1 >/dev/null 2>&1 &
    done
end script

post-stop script
    read -r FIRSTLINE < /var/run/worker-1.pid
    kill $(($FIRSTLINE + 2))
    kill $(($FIRSTLINE + 3))
    kill $(($FIRSTLINE + 4))
    kill $(($FIRSTLINE + 5))
    kill $(($FIRSTLINE + 6))
    rm /var/run/worker-1.pid
    echo "[`date`] Workers stopped" >> /var/log/worker-1.log
end script

Solution

  • The script above is almost correct. The main problem was that PHP script initiated RabbitMQ worker but RabbitMQ server was not ready.

    I made some additional tweaks and here is a working solution:

    description "Starts/kills workers."
    author "Jiri Mihal"
    start on (rabbitmq-server-running or started rabbitmq-server)
    stop on (shutdown or rabbitmq-server-stopped or stopping rabbitmq-server)
    
    env WORKER=Workername
    env COUNT=5
    
    pre-start script
        echo "[`date`] Workers started" >> /var/log/worker-$WORKER.log
    end script
    
    post-start script
        for i in `seq 1 $COUNT`;
        do
            exec php /home/jiri/workers/dlapi.workers/workers/RpcWorkerLauncher.php $WORKER >/dev/null 2>&1 &
            if [ $i = 1 ]; then
               echo $! > /var/run/worker-$WORKER.pid
            fi
        done
    end script
    
    post-stop script
        read -r PID < /var/run/worker-$WORKER.pid
        for i in `seq 1 $COUNT`;
        do
            kill $(($PID + $i - 1))
        done
        rm /var/run/worker-$WORKER.pid
        echo "[`date`] Workers stopped" >> /var/log/worker-$WORKER.log
    end script