File: daemon.py

package info (click to toggle)
pglistener 4
  • links: PTS
  • area: main
  • in suites: buster, stretch
  • size: 224 kB
  • ctags: 132
  • sloc: python: 594; perl: 364; sh: 120; sql: 89; makefile: 2
file content (231 lines) | stat: -rw-r--r-- 6,557 bytes parent folder | download
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231

import errno
import os
import pwd
import re
import select
import sys
import syslog
import time
import socket

import psycopg2
import psycopg2.extensions

def close_stdio():
    fh = file(os.devnull, 'r')
    os.dup2(fh.fileno(), 0)
    fh.close()

    fh = file(os.devnull, 'w')
    os.dup2(fh.fileno(), 1)
    os.dup2(fh.fileno(), 2)
    fh.close()

class FakeStderr:
    def write(self, s):
        for line in s.rstrip().splitlines():
            syslog.syslog(syslog.LOG_ERR, line)

def daemonize(pidfile):
    # Open the PID file before we fork, so that our parent will see an error
    # if we fail.
    fd = os.open(pidfile, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0644)
    fh = os.fdopen(fd, 'w')
    pid = os.fork()

    if pid != 0:
        os._exit(0)

    os.setsid()
    pid = os.fork()

    if pid != 0:
        fh.write('%d\n' % pid)
        fh.close()
        os._exit(0)

    close_stdio()
    sys.stderr = FakeStderr()

def format_dsn(dsn):
    matches = re.findall('([^\s=]+)=(\S+)', dsn)
    acc = []

    for k, v in matches:
        if k != 'password':
            acc.append('%s=%s' % (k, v))

    return ' '.join(acc)

class Daemon:
    def __init__(self, listeners):
        self.connections = {}
        self.listeners = listeners
        self.sleeptime = 1
        self.last_sleep = 0

    def err(self, message):
        syslog.syslog(syslog.LOG_ERR, message)

    def info(self, message):
        syslog.syslog(syslog.LOG_INFO, message)

    def sleep(self):
        # Reset if stuff has been fine for five minutes
        if time.time() > self.last_sleep + 300:
            self.sleeptime = 1

        time.sleep(sleeptime)
        if sleeptime < 128:
            sleeptime *= 2
        self.last_sleep = time.time()

    def _make_connection(self, dsn):
        return psycopg2.connect(dsn)

    def make_connection(self, dsn):
        while True:
            self.info("connecting to: %s" % format_dsn(dsn))

            try:
                return self._make_connection(dsn)
            except psycopg2.DatabaseError, e:
                self.err("error: %s" % e)
                self.sleep()

    def query(self, listener):

        while True:
            connection = self.connections[listener.dsn]
            cursor = connection.cursor()
            if hasattr(socket, 'SO_KEEPALIVE'):
                fd = None
                try:
                    fd = cursor.fileno()
                except AttributeError:
                    fd = cursor.connection.fileno()
                except AttributeError:
                    pass
                else:
                    s = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
                    # avoid unix sockets
                    if type(s.getsockname()) == type(()):
                        s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)

            try:
                cursor.execute(listener.query)
                return cursor.fetchall()
            except psycopg2.DatabaseError, e:
                self.err("error: %s" % e)
                self.err("reconnecting and retrying")
                self.connections[listener.dsn] = \
                    self.make_connection(listener.dsn)
                self.sleep()

    def get_notifications(self, conn, cursor = None):
        # Newer psycopg needs poll, but older doesn't have it.
        try:
            conn.poll()
        except AttributeError:
            conn.cursor().isready()
        notifications = [name for pid, name in conn.notifies]
        conn.notifies[:] = []
        return notifications

    def wait_for_notifications(self):
        connections = self.connections.values()

        # Backwards compatibility
        if not hasattr(connections[0], 'fileno'):
            connections = [x.cursor() for x in connections]

        try:
            readables, _, _ = select.select(connections, [], [], None)
        except select.error, (err, strerror):
            if err == errno.EINTR:
                return []
            else:
                raise

        notifications = set()

        for obj in readables:
            conn = obj
            if hasattr(obj, 'connection'):
                # conn is a cursor, not a connection
                conn = conn.connection
            try:
                notifications.update(
                    self.get_notifications(conn))
            except psycopg2.DatabaseError, e:
                # Probably end of file due to losing the connection.
                # Reconnect.

                self.err(str(e))

                for dsn, c in self.connections.iteritems():
                    if c is conn:
                        self.connections[dsn] = self.make_connection(dsn)
                self.sleep()

        return notifications

    def update(self, listener):
        self.info("updating: %s (%s)" %
            (listener.name, listener.destination))
        results = self.query(listener)
        listener.do_write(results, listener.destination)
        listener.do_posthooks()

    def do_iteration(self):
        notifications = self.wait_for_notifications()

        for notification in notifications:
            self.info("got notification: %s" % notification)

        for listener in self.listeners:
            if notifications & set(listener.notifications):
                self.update(listener)

    def loop(self):
        while True:
            self.do_iteration()

    def listen(self):
        for dsn, conn in self.connections.iteritems():
            listens = []
            cursor = conn.cursor()

            for listener in self.listeners:
                if listener.dsn == dsn:
                    self.info("%s: listening for: %s" %
                        (listener.name, ' '.join(listener.notifications)))
                    listens.extend(listener.notifications)

            for listen in listens:
                cursor.execute('listen \"%s\"' % listen)

    def openlog(self):
        syslog.openlog('pglistener', syslog.LOG_PID, syslog.LOG_DAEMON)

    def run(self):
        self.info('starting up')

        for listener in self.listeners:
            if listener.dsn not in self.connections:
                conn = self.make_connection(listener.dsn)
                conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
                self.connections[listener.dsn] = conn

        for listener in self.listeners:
            self.update(listener)

        self.listen()
        self.loop()

def run(listeners):
    daemon = Daemon(listeners)
    daemon.run()