aboutsummaryrefslogtreecommitdiff
blob: 38b7d9a731647708dca4cdb88fcced12ed2ea342 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#!/usr/bin/env python

import atexit
import os
import signal
import sys
import time

class Daemon:
    """ Adopted from Sander Marechal's "A simple unix/linux daemon in Python"
        See: http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/

        To use, inherit by a subclass which overrides run() and does all the
        work.  You start the daemon with

            d = MyDaemon(pidfile, foo='1', bar='2')  # Any **kwargs after pidfile
            d.start()   # to start the daemon

        All signal handling should be defined in a subfunction within run().

        Note: This isn't completely general daemon code as it doesn't close stdout/stderr.
        Rather these are redirected to /var/log/grs/grs-daemon-<pid>.err to capture any
        exceptions for debugging.
    """

    def __init__(self, pidfile, **kwargs):
        # Since this will be used as a super class, we'll accept any **kwargs
        # and insert them to our internal __dict__.
        self.pidfile = pidfile
        for k in kwargs:
            self.__dict__[k] = kwargs[k]


    def daemonize(self):
        try:
            pid = os.fork()
            if pid > 0:
                sys.exit(0)
        except OSError as err:
            sys.stderr.write('fork #1 failed: %s\n' % err)
            sys.exit(1)

        os.chdir('/')
        os.setsid()
        os.umask(0o22)

        try:
            pid = os.fork()
            if pid > 0:
                sys.exit(0)
        except OSError as err:
            sys.stderr.write('fork #2 failed %s\n' % err)
            sys.exit(1)

        # Dup stdin to /dev/null, and stdout and stderr to grs-daemon-<pid>.err
        si = open(os.devnull, 'r')
        os.dup2(si.fileno(), sys.stdin.fileno())

        os.makedirs('/var/log/grs', mode=0o755, exist_ok=True)
        se = open('/var/log/grs/grs-daemon-%d.err' % os.getpid(), 'a+')

        sys.stdout.flush()
        os.dup2(se.fileno(), sys.stdout.fileno())
        sys.stderr.flush()
        os.dup2(se.fileno(), sys.stderr.fileno())

        # Use atexit to remove the pidfile when we shutdown.
        # No matter where the exit is initiated, eg from Execute.py
        # we are sure that atexit() will run and delete the pidfile.
        atexit.register(self.delpid)
        with open(self.pidfile,'w') as pf:
            pf.write('%d\n' % os.getpid())


    def delpid(self):
        os.remove(self.pidfile)


    def run(self):
        pass


    def start(self):
        # If there's a pidfile when we try to startup, then:
        # 1) If the pidfile is stale, remove it and startup as usual.
        # 2) If we're already running, then don't start a second instance.
        try:
            with open(self.pidfile, 'r') as pf:
                pid = int(pf.read().strip())
        except IOError:
            pid = None

        if pid:
            if not os.path.exists('/proc/%d' % pid):
                sys.stderr.write('unlinking stale pid file %s\n' % self.pidfile)
                os.unlink(self.pidfile)
            else:
                sys.stderr.write('process running with pid = %d\n' % pid)
                return

        self.daemonize()
        self.run()