|
| 1 | +''' |
| 2 | + *** |
| 3 | + Modified generic daemon class |
| 4 | + *** |
| 5 | + |
| 6 | + Author: http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/ |
| 7 | + www.boxedice.com |
| 8 | + |
| 9 | + License: http://creativecommons.org/licenses/by-sa/3.0/ |
| 10 | + |
| 11 | + Changes: 23rd Jan 2009 (David Mytton <[email protected]>) |
| 12 | + - Replaced hard coded '/dev/null in __init__ with os.devnull |
| 13 | + - Added OS check to conditionally remove code that doesn't work on OS X |
| 14 | + - Added output to console on completion |
| 15 | + - Tidied up formatting |
| 16 | + 11th Mar 2009 (David Mytton <[email protected]>) |
| 17 | + - Fixed problem with daemon exiting on Python 2.4 (before SystemExit was part of the Exception base) |
| 18 | + 13th Aug 2010 (David Mytton <[email protected]> |
| 19 | + - Fixed unhandled exception if PID file is empty |
| 20 | +''' |
| 21 | + |
| 22 | +# Core modules |
| 23 | +import atexit |
| 24 | +import os |
| 25 | +import sys |
| 26 | +import time |
| 27 | +import signal |
| 28 | +import errno |
| 29 | + |
| 30 | +class Daemon(object): |
| 31 | + """ |
| 32 | + A generic daemon class. |
| 33 | + |
| 34 | + Usage: subclass the Daemon class and override the run() method |
| 35 | + """ |
| 36 | + def __init__(self, pidfile, stdin=os.devnull, stdout=os.devnull, stderr=os.devnull, home_dir='.', umask=022, verbose=1): |
| 37 | + self.stdin = stdin |
| 38 | + self.stdout = stdout |
| 39 | + self.stderr = stderr |
| 40 | + self.pidfile = pidfile |
| 41 | + self.home_dir = home_dir |
| 42 | + self.verbose = verbose |
| 43 | + self.umask = umask |
| 44 | + self.daemon_alive = True |
| 45 | + |
| 46 | + def daemonize(self): |
| 47 | + """ |
| 48 | + Do the UNIX double-fork magic, see Stevens' "Advanced |
| 49 | + Programming in the UNIX Environment" for details (ISBN 0201563177) |
| 50 | + http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 |
| 51 | + """ |
| 52 | + try: |
| 53 | + pid = os.fork() |
| 54 | + if pid > 0: |
| 55 | + # Exit first parent |
| 56 | + sys.exit(0) |
| 57 | + except OSError, e: |
| 58 | + sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror)) |
| 59 | + sys.exit(1) |
| 60 | + |
| 61 | + # Decouple from parent environment |
| 62 | + os.chdir(self.home_dir) |
| 63 | + os.setsid() |
| 64 | + os.umask(self.umask) |
| 65 | + |
| 66 | + # Do second fork |
| 67 | + try: |
| 68 | + pid = os.fork() |
| 69 | + if pid > 0: |
| 70 | + # Exit from second parent |
| 71 | + sys.exit(0) |
| 72 | + except OSError, e: |
| 73 | + sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror)) |
| 74 | + sys.exit(1) |
| 75 | + |
| 76 | + if sys.platform != 'darwin': # This block breaks on OS X |
| 77 | + # Redirect standard file descriptors |
| 78 | + sys.stdout.flush() |
| 79 | + sys.stderr.flush() |
| 80 | + si = file(self.stdin, 'r') |
| 81 | + so = file(self.stdout, 'a+') |
| 82 | + if self.stderr: |
| 83 | + se = file(self.stderr, 'a+', 0) |
| 84 | + else: |
| 85 | + se = so |
| 86 | + os.dup2(si.fileno(), sys.stdin.fileno()) |
| 87 | + os.dup2(so.fileno(), sys.stdout.fileno()) |
| 88 | + os.dup2(se.fileno(), sys.stderr.fileno()) |
| 89 | + |
| 90 | + def sigtermhandler(signum, frame): |
| 91 | + self.daemon_alive = False |
| 92 | + signal.signal(signal.SIGTERM, sigtermhandler) |
| 93 | + signal.signal(signal.SIGINT, sigtermhandler) |
| 94 | + |
| 95 | + if self.verbose >= 1: |
| 96 | + print "Started" |
| 97 | + |
| 98 | + # Write pidfile |
| 99 | + atexit.register(self.delpid) # Make sure pid file is removed if we quit |
| 100 | + pid = str(os.getpid()) |
| 101 | + file(self.pidfile,'w+').write("%s\n" % pid) |
| 102 | + |
| 103 | + def delpid(self): |
| 104 | + os.remove(self.pidfile) |
| 105 | + |
| 106 | + def start(self, *args, **kwargs): |
| 107 | + """ |
| 108 | + Start the daemon |
| 109 | + """ |
| 110 | + |
| 111 | + if self.verbose >= 1: |
| 112 | + print "Starting..." |
| 113 | + |
| 114 | + # Check for a pidfile to see if the daemon already runs |
| 115 | + try: |
| 116 | + pf = file(self.pidfile,'r') |
| 117 | + pid = int(pf.read().strip()) |
| 118 | + pf.close() |
| 119 | + except IOError: |
| 120 | + pid = None |
| 121 | + except SystemExit: |
| 122 | + pid = None |
| 123 | + |
| 124 | + if pid: |
| 125 | + message = "pidfile %s already exists. Is the daemon already running?\n" |
| 126 | + sys.stderr.write(message % self.pidfile) |
| 127 | + |
| 128 | + # Remove stale pid files |
| 129 | + try: |
| 130 | + os.kill(pid, 0) |
| 131 | + except OSError, why: |
| 132 | + if why[0] == errno.ESRCH: |
| 133 | + print('Removing stale pidfile %s' % self.pidfile) |
| 134 | + os.remove(self.pidfile) |
| 135 | + else: |
| 136 | + sys.exit("Can't check status of PID %s from pidfile %s: %s" % |
| 137 | + (pid, self.pidfile, why[1])) |
| 138 | + else: |
| 139 | + sys.exit("daemon is already running with PID %s\n" % pid) |
| 140 | + |
| 141 | + # Start the daemon |
| 142 | + self.daemonize() |
| 143 | + self.run(*args, **kwargs) |
| 144 | + |
| 145 | + def stop(self): |
| 146 | + """ |
| 147 | + Stop the daemon |
| 148 | + """ |
| 149 | + |
| 150 | + if self.verbose >= 1: |
| 151 | + print "Stopping..." |
| 152 | + |
| 153 | + # Get the pid from the pidfile |
| 154 | + try: |
| 155 | + pf = file(self.pidfile,'r') |
| 156 | + pid = int(pf.read().strip()) |
| 157 | + pf.close() |
| 158 | + except IOError: |
| 159 | + pid = None |
| 160 | + except ValueError: |
| 161 | + pid = None |
| 162 | + |
| 163 | + if not pid: |
| 164 | + message = "pidfile %s does not exist. Not running?\n" |
| 165 | + sys.stderr.write(message % self.pidfile) |
| 166 | + |
| 167 | + # Just to be sure. A ValueError might occur if the PID file is empty but does actually exist |
| 168 | + if os.path.exists(self.pidfile): |
| 169 | + os.remove(self.pidfile) |
| 170 | + |
| 171 | + return # Not an error in a restart |
| 172 | + |
| 173 | + # Try killing the daemon process |
| 174 | + try: |
| 175 | + while 1: |
| 176 | + |
| 177 | + # Note: kill -SIGTERM will work, doing it from python will not. |
| 178 | + # I don't feel like finding out why right now. FIXME |
| 179 | + |
| 180 | + os.kill(pid, signal.SIGKILL) |
| 181 | + time.sleep(0.1) |
| 182 | + except OSError, err: |
| 183 | + err = str(err) |
| 184 | + if err.find("No such process") > 0: |
| 185 | + if os.path.exists(self.pidfile): |
| 186 | + os.remove(self.pidfile) |
| 187 | + else: |
| 188 | + print str(err) |
| 189 | + sys.exit(1) |
| 190 | + |
| 191 | + if self.verbose >= 1: |
| 192 | + print "Stopped" |
| 193 | + |
| 194 | + def restart(self): |
| 195 | + """ |
| 196 | + Restart the daemon |
| 197 | + """ |
| 198 | + self.stop() |
| 199 | + self.start() |
| 200 | + |
| 201 | + def run(self): |
| 202 | + """ |
| 203 | + You should override this method when you subclass Daemon. It will be called after the process has been |
| 204 | + daemonized by start() or restart(). |
| 205 | + """ |
| 206 | + |
0 commit comments