Debian Codegraph @

powa_collector/__init__.py

raw
1 """
2 PowaCollector: powa-collector main application.
3
4 It takes a simple configuration file in json format, where repository.dsn
5 should point to an URI to connect to the repository server. The list of remote
6 servers and their configuration will be retrieved from this repository server.
7
8 It maintains a persistent dedicated connection to the repository server, for
9 monitoring and communication purpose. It also starts one thread per remote
10 server. These threads are kept in the "workers" dict attribute, with the key
11 being the textual identifier (host:port). See powa_worker.py for more details
12 about those threads.
13
14 The main thread will intercept the following signals:
15
16 - SIGHUP: reload configuration and log and changes done
17 - SIGTERM: cleanly terminate all threads and exit
18
19 A minimal communication protocol is implemented, using the LISTEN/NOTIFY
20 facility provided by postgres. The dedicated main thread repository connection
21 listens on the "powa_collector" channel. A client, such as powa-web, can send
22 requests on this channel and the main thread will act and respond accordingly.
23
24 The requests are of the following form:
25
26 COMMAND RESPONSE_CHANNEL OPTIONAL_ARGUMENTS
27
28 See the README.md file for the full protocol documentation.
29 """
30
31 from powa_collector.options import (parse_options, get_full_config,
32 add_servers_config)
33 from powa_collector.powa_worker import PowaThread
34 from powa_collector.customconn import get_connection
35 from powa_collector.notify import (notify_parse_force_snapshot,
36 notify_parse_refresh_db_cat,
37 notify_allowed)
38 from powa_collector.utils import conf_are_equal
39 import psycopg2
40 import select
41 import logging
42 import json
43 import signal
44 import time
45
46 __VERSION__ = '1.3.2'
47 __VERSION_NUM__ = [int(part) for part in __VERSION__.split('.')]
48
49
50 def getVersion():
51 """Return powa_collector's version as a string"""
52 return __VERSION__
53
54
55 class PowaCollector():
56 """Main powa collector's class. This manages all collection tasks
57 Declare all attributes here, we don't want dynamic attributes
58 """
59 def __init__(self):
60 """Instance creator. Sets logging, signal handlers, and basic structure"""
61 self.workers = {}
62 self.logger = logging.getLogger("powa-collector")
63 self.stopping = False
64
65 raw_options = parse_options()
66 loglevel = logging.INFO
67 if (raw_options["debug"]):
68 loglevel = logging.DEBUG
69
70 extra = {'threadname': '-'}
71 logging.basicConfig(
72 format='%(asctime)s %(threadname)s %(levelname)-6s: %(message)s ',
73 level=loglevel)
74 self.logger = logging.LoggerAdapter(self.logger, extra)
75 signal.signal(signal.SIGHUP, self.sighandler)
76 signal.signal(signal.SIGTERM, self.sighandler)
77
78
79 def __get_worker_by_srvid(self, srvid):
80 """Get the worker thread for the given srvid, if any"""
81 for k, worker in self.workers.items():
82 worker_srvid = self.config["servers"][k]["srvid"]
83
84 if (srvid != worker_srvid):
85 continue
86
87 return worker
88 return None
89
90 def connect(self, options):
91 """Connect to the repository
92 Used for communication with powa-web and users of the communication repository
93 Persistent
94 Threads will use distinct connections
95 """
96 try:
97 self.logger.debug("Connecting on repository...")
98 self.__repo_conn = get_connection(self.logger,
99 options["debug"],
100 options["repository"]['dsn'])
101 self.__repo_conn.autocommit = True
102 self.logger.debug("Connected.")
103 cur = self.__repo_conn.cursor()
104
105 # Setup a 2s lock_timeout if there's no inherited lock_timeout
106 cur.execute("""SELECT
107 pg_catalog.set_config(name, '2000', false)
108 FROM pg_catalog.pg_settings
109 WHERE name = 'lock_timeout'
110 AND setting = '0'""")
111 cur.execute("SET application_name = %s",
112 ('PoWA collector - main thread'
113 + ' (' + __VERSION__ + ')', ))
114
115 # Listen on our dedicated powa_collector notify channel
116 cur.execute("LISTEN powa_collector")
117
118 # Check if powa-archivist is installed on the repository server
119 cur.execute("""SELECT
120 regexp_split_to_array(extversion, E'\\\\.'),
121 extversion
122 FROM pg_catalog.pg_extension
123 WHERE extname = 'powa'""")
124 ver = cur.fetchone()
125 cur.close()
126
127 if ver is None:
128 self.__repo_conn.close()
129 self.__repo_conn = None
130 self.logger.error("PoWA extension not found on repository "
131 "server")
132 return False
133 elif (int(ver[0][0]) < 4):
134 self.__repo_conn.close()
135 self.__repo_conn = None
136 self.logger.error("Incompatible PoWA version, found %s,"
137 " requires at least 4.0.0" % ver[1])
138 return False
139
140 except psycopg2.Error as e:
141 self.__repo_conn = None
142 self.logger.error("Error connecting:\n%s", e)
143 return False
144
145 return True
146
147 def process_notifications(self):
148 """Process PostgreSQL NOTIFY messages.
149 These come mainly from the UI, to ask us to reload our configuration,
150 or to display the workers status.
151 """
152 if (not self.__repo_conn):
153 return
154
155 self.__repo_conn.poll()
156 cur = self.__repo_conn.cursor()
157
158 while (self.__repo_conn.notifies):
159 notify = self.__repo_conn.notifies.pop(0)
160 pid = notify.pid
161 payload = notify.payload.split(' ')
162 status = ''
163 cmd = payload.pop(0)
164 channel = "-"
165 status = "OK"
166 data = None
167
168 # the channel is mandatory, but if the message can be processed
169 # without answering, we'll try to
170 if (len(payload) > 0):
171 channel = payload.pop(0)
172
173 self.logger.debug("Received async command: %s %s %r" %
174 (cmd, channel, payload))
175
176 if (not notify_allowed(pid, self.__repo_conn)):
177 status = 'ERROR'
178 data = 'Permission denied'
179 else:
180 try:
181 (status, data) = self.__process_one_notification(cmd,
182 channel,
183 payload)
184 except Exception as e:
185 status = 'ERROR'
186 data = str(e)
187
188 # if there was a response channel, reply back
189 if (channel != '-'):
190 # We need an extra {} around the data as the custom connection
191 # will call format() on the overall string, which would fail
192 # with a json dump as-is. We therefore also need to make sure
193 # that any non-empty data looks like a json.
194
195 payload = ("%(cmd)s %(status)s %(data)s" %
196 {'cmd': cmd, 'status': status, 'data': data})
197
198 # with default configuration, postgres only accept up to 8k
199 # bytes payload. If the payload is longer, just warn the
200 # caller that it didn't fit.
201 # XXX we could implement multi-part answer, but if we ever
202 # reach that point, we should consider moving to a table
203 if (len(payload.encode('utf-8')) >= 8000):
204 payload = ("%(cmd)s %(status)s %(data)s" %
205 {'cmd': cmd,
206 'status': "KO",
207 'data': "{ANSWER TOO LONG}"})
208
209 cur.execute('NOTIFY "' + channel + '", %(payload)s',
210 {'payload': payload})
211
212 cur.close()
213
214 def __process_one_notification(self, cmd, channel, notif):
215 """
216 Process a single notification, called by process_notifications.
217 """
218 status = "OK"
219 data = ''
220
221 if (cmd == "RELOAD"):
222 self.reload_conf()
223 data = 'OK'
224 elif (cmd == "WORKERS_STATUS"):
225 # ignore the message if no channel was received
226 if (channel != '-'):
227 # did the caller request a single server only? We ignore
228 # anything but the first parameter passed
229 if (len(notif) > 0 and notif[0].isdigit()):
230 w_id = int(notif[0])
231 data = json.dumps(self.list_workers(w_id, False))
232 else:
233 data = json.dumps(self.list_workers(None, False))
234 elif (cmd == "FORCE_SNAPSHOT"):
235 r_srvid = notify_parse_force_snapshot(notif)
236 worker = self.__get_worker_by_srvid(r_srvid)
237
238 if (worker is None):
239 raise Exception("Server id %d not found" % r_srvid)
240
241 request_time = time.time()
242 (status, data) = worker.request_forced_snapshot()
243
244 # If a snapshot could be scheduled, wait just a bit and see if we
245 # can report that the snapshot has already begun or will be started
246 # shortly. It's possible, although unlikely, that the snapshot was
247 # started and finished during that time. We don't try to properly
248 # detect that case, as it should only happen in toy setups. We
249 # might want to change that later if we want to provide a way to
250 # inform callers of the completion of the snapshot they requested.
251 if (status == 'OK'):
252 time.sleep(0.1)
253 if worker.is_snapshot_in_progress():
254 data = 'Snapshot in progress'
255 else:
256 data = 'Snapshot wil begin shortly'
257 elif (cmd == "REFRESH_DB_CAT"):
258 (r_srvid, r_dbnames) = notify_parse_refresh_db_cat(notif)
259 worker = self.__get_worker_by_srvid(r_srvid)
260
261 if (worker is None):
262 raise Exception("Server id %d not found" % r_srvid)
263
264 (status, data) = worker.register_cat_refresh(r_dbnames)
265
266 # everything else is unhandled
267 else:
268 status = 'UNKNOWN'
269 data = 'Message "%s" invalid, command ignored' % cmd
270
271 return (status, data)
272
273 def main(self):
274 """Start the active loop.
275 Connect or reconnect to the repository and starts threads to manage the
276 monitored servers
277 """
278 raw_options = parse_options()
279 self.logger.info("Starting powa-collector...")
280
281 if (not self.connect(raw_options)):
282 exit(1)
283
284 try:
285 self.config = add_servers_config(self.__repo_conn, raw_options)
286 except psycopg2.Error as e:
287 self.__repo_conn.close()
288 self.__repo_conn = None
289 self.logger.error("Error retrieving the list of remote servers:"
290 "\n%s",
291 e)
292 exit(1)
293
294 for k, conf in self.config["servers"].items():
295 self.register_worker(k, self.config["repository"], conf,
296 raw_options['debug'])
297
298 self.list_workers()
299
300 try:
301 while (not self.stopping):
302 if (self.__repo_conn is not None):
303 try:
304 cur = self.__repo_conn.cursor()
305 cur.execute("SELECT 1")
306 cur.close()
307 except Exception:
308 self.__repo_conn = None
309 self.logger.warning("Connection was dropped!")
310
311 if (not self.__repo_conn):
312 self.connect(raw_options)
313
314 select.select([self.__repo_conn], [], [], 10)
315
316 self.process_notifications()
317 except KeyboardInterrupt:
318 self.logger.debug("KeyboardInterrupt caught")
319 self.logger.info("Stopping all workers and exiting...")
320 self.stop_all_workers()
321
322 def register_worker(self, name, repository, config, debug):
323 """Add a worker thread to a server"""
324 self.workers[name] = PowaThread(name, repository, config, debug)
325 self.workers[name].start()
326
327 def stop_all_workers(self):
328 """Ask all worker threads to stop
329 This is asynchronous, no guarantee
330 """
331 for k, worker in self.workers.items():
332 worker.ask_to_stop()
333
334 def sighandler(self, signum, frame):
335 """Manage signal handlers: reload conf on SIGHUB, shutdown on SIGTERM"""
336 if (signum == signal.SIGHUP):
337 self.logger.debug("SIGHUP caught")
338 self.reload_conf()
339 elif (signum == signal.SIGTERM):
340 self.logger.debug("SIGTERM caught")
341 self.stop_all_workers()
342 self.stopping = True
343 else:
344 self.logger.error("Unhandled signal %d" % signum)
345
346 def list_workers(self, wanted_srvid=None, tostdout=True):
347 """List all workers and their status"""
348 res = {}
349
350 if (tostdout):
351 self.logger.info('List of workers:')
352
353 if (tostdout and len(self.workers.items()) == 0):
354 self.logger.info('No worker')
355
356 for k, worker in self.workers.items():
357 # self.logger.info(" %s%s" % (k, "" if (worker.is_alive()) else
358 # " (stopped)"))
359 worker_srvid = self.config["servers"][k]["srvid"]
360
361 # ignore this entry if caller want information for only one server
362 if (wanted_srvid is not None and wanted_srvid != worker_srvid):
363 continue
364
365 status = "Unknown"
366 if (worker.is_stopping()):
367 status = "stopping"
368 elif (worker.is_alive()):
369 status = worker.get_status()
370 else:
371 status = "stopped"
372
373 if (tostdout):
374 self.logger.info("%r (%s)" % (worker, status))
375 else:
376 res[worker_srvid] = status
377
378 return res
379
380 def reload_conf(self):
381 """Reload configuration:
382 - reparse the configuration
383 - stop and start workers if necessary
384 - for those whose configuration has changed, ask them to reload
385 - update dep versions: recompute powa version's and its dependencies
386 """
387 self.list_workers()
388
389 self.logger.info('Reloading...')
390 config_new = get_full_config(self.__repo_conn)
391
392 # check for removed servers
393 for k, worker in self.workers.items():
394 if (worker.is_alive()):
395 continue
396
397 if (worker.is_stopping()):
398 self.logger.warning("The worker %s is stoping" % k)
399
400 if (k not in config_new["servers"]):
401 self.logger.info("%s has been removed, stopping it..." % k)
402 worker.ask_to_stop()
403
404 # check for added servers
405 for k in config_new["servers"]:
406 if (k not in self.workers or not self.workers[k].is_alive()):
407 self.logger.info("%s has been added, registering it..." % k)
408 self.register_worker(k, config_new["repository"],
409 config_new["servers"][k],
410 config_new['debug'])
411
412 # check for updated configuration
413 for k in config_new["servers"]:
414 cur = config_new["servers"][k]
415 if (not conf_are_equal(cur, self.workers[k].get_config())):
416 self.workers[k].ask_reload(cur)
417 # also try to reconnect if the worker experienced connection issue
418 elif(self.workers[k].get_status() != "running"):
419 self.workers[k].ask_reload(cur)
420
421 # update stored versions
422 for k in config_new["servers"]:
423 self.workers[k].ask_update_dep_versions()
424
425 self.config = config_new
426 self.logger.info('Reload done')