I set up a Python application as a Linux service using Upstart script.
description "AAE client app"
start on runlevel [2345]
stop on runlevel [!2345]
respawn
env PATH=/home/ec2-user/aae_client/env/bin
env PROGRAM_NAME="aae"
env USERNAME="ec2-user"
# Main script to be run
script
echo "[`date -u +%Y-%m-%dT%T.%3NZ`] (sys) Ready to run..." >> /var/log/$PROGRAM_NAME.sys.log
export HOME="/home/ec2-user"
echo $$ > /var/run/$PROGRAM_NAME.pid
cd /home/ec2-user/aae_client
exec python -m app.run >> /var/log/$PROGRAM_NAME.sys.log 2>&1
end script
I want to stop the service when sys.exit
is called inside the python code due to some exception being caught.
if not config_path:
logger.error('Environment variable AAE_CLIENT_CONFIG_PATH is not set')
sys.exit()
As it turns out, sys.exit
did terminate the current process, but somehow the service keeps getting respawned. If I run status [service]
again and again, it would show the service running every time with a new PID.
Is there a way to kill the service completely within the code?
The short answer is that it respawns the process whenever it exits because that's what you told it to do. That's what the
respawn
directive is for.If you want to respawn but not immediately, you can add a post-stop delay.
The "Delay Respawn of a Job" section of the Upstart Cookbook gives this example:
You can modify the sleep to whatever is appropriate for your service.