samedi 14 septembre 2013

Create a daemon on Ubuntu

This tutorial is only valid if you have installed UPSTART
By default Raspbian distribution use SysVInit not UPSTART so this tutorial is not valid ...

1) Install python-daemon and python-lockfile
   sudo apt-get install python-daemon python-lockfile

2) create a python script

mydaemon.py:

#!/usr/bin/env python

import os

import subprocess
import time
import datetime
import requests
import commands
import logging

from daemon import runner

class App():
  
    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/tty'
        self.stderr_path = '/dev/tty'
        self.pidfile_path =  '/var/run/mydaemon/mydaemon.pid'
        self.pidfile_timeout = 5
          
    def run(self):

        while True:
            logger.debug("Debug message")
            logger.info("Info message")
            logger.warn("Warning message")
            logger.error("Error message")
            time.sleep(60)

app = App()
logger = logging.getLogger("DaemonLog")
logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler = logging.FileHandler("/var/log/mydaemon/mydaemon.log")
handler.setFormatter(formatter)
logger.addHandler(handler)


daemon_runner = runner.DaemonRunner(app)
#This ensures that the logger file handle does not get closed during daemonization
daemon_runner.daemon_context.files_preserve=[handler.stream]
daemon_runner.do_action()


3) Start/Stop

 > python mydaemon.py
usage: mydaemon.py start|stop|restart
> python mydaemon.py start
started with pid 8699
> python mydaemon.py stop
Terminating on signal 15

4)  Create a startup configuration

create a file name "mydaemon.conf" in /etc/init

description "MyDaemon Service"
author "you"
start on runlevel [234]
stop on runlevel [0156]
chdir /mydirectory
exec /mydirectory/mydaemon.py
respawn

then reload configuration:
sudo initctl reload-configuration

now you can start daemon with :
sudo start mydaemon

and stop it with
sudo stop mydaemon

and the daemon will be launched at startup and kill at shutdown !

5) Troubleshoot

If you've got an error with (ImportError: cannot import name runner), check that the 'daemon' if the right one:

root@raspberrypi ~/ $ python
Python 2.7.3 (default, Jan 13 2013, 11:20:46)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import daemon
>>> print daemon.__file__
/usr/lib/pymodules/python2.7/daemon/__init__.pyc

if you have not the __init__.pyc, may be you've installed a module that is also named daemon (like with a commande 'pip install daemon')


Aucun commentaire:

Enregistrer un commentaire