Skip to main content

Wondering how to start/stop a Python script from init.d ?


If you just looking for the solution please go to solution heading directly!!

So I have been asked to start my python server at the time of boot up. As I am pretty new to Python and have never done this, I have to go and find some help from none other than our best bud google.
So when I googled I had found couple solution like

http://www.pietervanos.net/knowledge/start-python-script-from-init-d/

The problem with the above solution is that when you want to stop your Python script using the above solution it kills all of the python scripts running on the machine. Obviously we don't want to kill other Python script, don't we?

And had found couple of other solutions which I was not able to understand or I could not make them work. So the solution which I am using is.

Solution :

The plan is to make your Python script in my case my Python server to store its pid in some file, lets say in location /var/run/your_script.pid.
So I am making your life easy, use this below function to do it  :D
def store_pid():
    """ Writes the PID into a pidfile as /var/run/your_script.pid """
    pidfile = "/var/run/your_script.pid"
    pid = str(os.getpid())
    if os.path.exists(pidfile):
        os.remove(pidfile)

    file(pidfile, 'w').write(pid)

So as you see one has to
import os;
for this piece of code to work.

So once you have this function, its your responsibility to call this function at the right place in your Python script. Cause you need to take care of the situation where some user is trying to run your script again at that time you may loose your old PID file and hence never able to stop the script with out killing it explicitly.

Once you figure it out where to call it and how to handle the situation lets dig into the init script !
So again lets not make you look around the places for example inti script and all so find the script below !!
#!/bin/sh
#
# source function library
. /etc/rc.d/init.d/functions

RETVAL=0
prog="PATH_TO_YOUR_SCRIPT"
# Users can connect to server through any of the assiged IP.
# This location and file must be same as the one created in your script.
pidfile="/var/run/your_script.pid"
lock_file=/var/lock/subsys/you_script_name

start() {
    $prog &
    echo "Starting $prog"

    RETVAL=$?
    [ "$RETVAL" = 0 ] && touch $lock_file
    echo
}

stop() {
    killproc -p $pidfile
    #rm -f $LOCK_FILE
    rm -f $pidfile

    RETVAL=$?
    [ "$RETVAL" = 0 ] && touch $lock_file
    echo
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        start
        ;;
    status)
        status $prog
        RETVAL=$?
        ;;
    *)
        echo $"Usage: $0 {start|stop|restart|status}"
      RETVAL=1
esac
exit $RETVAL


One of the most import thing to do to make your script run at the start time is
chkconfig --add <your_init.d_script>
chkconfig --level 345 <your_init.d_script> on

So now lets discuss some of the problems.

When we use the normal init.d script to start and stop, it gives you warning if that program is already running ! unfortunately I could not figure it out how to do it with this.
So one has to carefully handle the situation where someone tries to start the already running script by calling the store pid in appropriate locations !!

FYI, OS I was running.


# uname -a 
Linux Dell620 2.6.32-220.17.1.el6.x86_64 #1 SMP Wed May 16 00:01:37 BST 2012 x86_64 x86_64 x86_64 GNU/Linux
# cat /etc/redhat-release 
CentOS release 6.2 (Final)

Please do let me know in the comment, if this method is wrong or if there is any other better method to do the same.

                                                                                                                           - Cheers :)

Comments

Popular posts from this blog

Enable stats GUI on haproxy.

Add bottom snippet to the haproxy.conf below the defaults section. listen  stats         bind 19.41.259.10:1234         mode            http         log             global         maxconn 10         clitimeout      100s         srvtimeout      100s         contimeout      100s         timeout queue   100s         stats enable         stats hide-version         stats refresh 30s         stats show-node         stats auth admin:password         stats uri  /haproxy?stats Make sure you are updating the IP address on the bind to your VIP and if you want, you can change the port also. One can even change the uri on the last line of the above snippet, like stats uri /haproxy_stats or whatever one wants. To make sure you have not done any mistake in the config file, one can use the following command to validate. haproxy -c -f haproxy.cfg Once everything looks good, restart the haproxy process and stats GUI should be available at 19.41.259.10:1234/hapro

Sending a SIGHUP signal to some external process from Python script

Code : import psutil import os import signal pids = psutil.get_pid_list() for pid in pids: if psutil.Process(pid).name == "process_name": os.kill(pid,signal.SIGHUP) break Steps to follow. 1.Get the PID of the process, in this case  "process_name"   to which you want to send out a SIGHUP signal. 2.Use os.kill(pid,sig) command to send out the SIGHUP signal to that process. 1.Get the PID of the process to which you want to send out a SIGHUP signal. One has to install a package called psutil by the following command. easy_install psutil Check out the following links for more details https://code.google.com/p/psutil/ https://pypi.python.org/pypi/psutil use psutil.get_pid_list() to get all of the PIDs. psutil.get_pid_list() works in the following manner.  pids = [ int ( x ) for x in os . listdir ( '/proc' ) if x . isdigit ()] return pids once you get all the PIDs get the PID you are i

How to enable Openstack Octavia, LBaaS V2 with devstack.

Little Intro to Octavia. Octavia is a service manager for Openstack Load balancer as a service. Neutron LBaaS V2 plugin talks to Octavia through Octavia driver. Octavia driver talks to Octavia api(o-api) and that in turn talks to Octavia control worker(o-cw). Neutron LBaaS V2 Plugin ----> Octavia plugin driver -----> o-api ----> o-cw Other than o-api and o-cw Octavia has 2 more components, housekeeping(o-hk) and health manager(o-hm). o-api Octavia api server which receives all the request from octavia LBaaS driver and passes it to o-cw. o-cw It's the main workhorse, it creates the load balancer VMs( amphorae ), configures them. o-hk keeps track of spare amphorae. o-hm Manages the health of the amphorae through heartbeats, collects the stats and takes care of fail over by creating a new amphora when it fails to get the heartbeat. How to enable Openstack Octavia, LBaaS V2 with Devstack. Since octavia uses a VM for loadbalancer its needs good a