Debian Codegraph @

powa_collector/powa_worker.py

raw
1 """
2 PowaThread: powa-collector dedicated remote server thread.
3
4 One of such thread is started per remote server by the main thred. Each
5 threads will use 2 connections:
6
7 - a persistent dedicated connection to the remote server, where it'll get
8 the source data
9 - a connection to the repository server, to write the source data and
10 perform the snapshot. This connection is created and dropped at each
11 checkpoint
12 """
13 from collections import defaultdict
14 from decimal import Decimal
15 import threading
16 import time
17 import psycopg2
18 from psycopg2.extras import DictCursor
19 import logging
20 import random
21 from powa_collector.customconn import get_connection
22 from powa_collector.snapshot import (get_global_snapfuncs_sql, get_src_query,
23 get_db_mod_snapfuncs_sql,
24 get_db_cat_snapfuncs_sql,
25 get_global_tmp_name,
26 get_nsp, copy_remote_data_to_repo)
27 from powa_collector.utils import get_powa_version
28
29
30 class PowaThread (threading.Thread):
31 """A Powa collector thread. Derives from threading.Thread
32 Manages a monitored remote server.
33 """
34 def __init__(self, name, repository, config, debug):
35 """Instance creator. Starts threading and logger"""
36 threading.Thread.__init__(self)
37 # we use this event to sleep on the worker main loop. It'll be set by
38 # the main thread through one of the public functions, when a SIGHUP
39 # was received to notify us to reload our config, or if we should
40 # terminate. All public functions will first set the required event
41 # before setting this one, to avoid missing an event in case of the
42 # sleep ends at exactly the same time
43 self.__stop_sleep = threading.Event()
44 # this event is set when we should terminate the thread
45 self.__stopping = threading.Event()
46 # this event is set when we should reload the configuration
47 self.__got_sighup = threading.Event()
48 # this event is set when we should force an immediate snapshot
49 self.__force_snapshot = threading.Event()
50 # this event is set internally while a snapshot is being performed
51 self.__snapshot_in_progress = threading.Event()
52 # protects __register_cat_refresh_dbnames only
53 self.__register_cat_refresh_lock = threading.Lock()
54 # Info for registering catalog refresh. None means no refresh asked,
55 # empty array means all db, otherwise a list of dbnames. There's no
56 # associated Event as this won't change the normal snapshot scheduling.
57 self.__register_cat_refresh_dbnames = None
58 self.__connected = threading.Event()
59 # the alias can be the dsn is use_server_alias is false or there's no
60 # alias defined for that remote server.
61 self.name = config["alias"]
62 self.__repository = repository
63 self.__config = config
64 self.__pending_config = None
65 self.__update_dep_versions = False
66 self.__remote_conn = None
67 self.__repo_conn = None
68 self.__last_repo_conn_errored = False
69 self.logger = logging.getLogger("powa-collector")
70 # last snapshot time, None if unknown
71 self.__last_snap_time = None
72 self.__debug = debug
73
74 extra = {'threadname': self.name}
75 self.logger = logging.LoggerAdapter(self.logger, extra)
76
77 self.logger.debug("Creating worker %s: %r" % (name, config))
78
79 def _safe_dsn(self):
80 """
81 Returns a safe dsn, ie the dsn with a redacted password if any.
82 """
83 dsn = self.__config["dsn"].copy()
84 if ("password" in dsn):
85 dsn["password"] = "<REDACTED>"
86
87 return dsn
88
89 def __repr__(self):
90 return ("%s: %s" % (self.name, self._safe_dsn()))
91
92 def __maybe_load_powa(self, conn):
93 """Loads Powa if it's not already and it's needed.
94 Only supports 4.0+ extension, and this version can be loaded on the fly
95 """
96
97 ver = get_powa_version(conn)
98
99 if (not ver):
100 self.logger.error("PoWA extension not found")
101 self.__disconnect_all()
102 self.__stopping.set()
103 return
104 elif (int(ver[0][0]) < 4):
105 self.logger.error("Incompatible PoWA version, found %s,"
106 " requires at least 4.0.0" % ver[1])
107 self.__disconnect_all()
108 self.__stopping.set()
109 return
110
111 # make sure the GUC are present in case powa isn't in
112 # shared_preload_librairies. This is only required for powa
113 # 4.0.x.
114 if (int(ver[0][0]) == 4 and int(ver[0][1]) == 0):
115 try:
116 cur = conn.cursor()
117 cur.execute("LOAD 'powa'")
118 cur.close()
119 conn.commit()
120 except psycopg2.Error as e:
121 self.logger.error("Could not load extension powa:\n%s" % e)
122 self.__disconnect_all()
123 self.__stopping.set()
124
125 def __save_versions(self):
126 """Save the versions we collect on the remote server in the repository"""
127 srvid = self.__config["srvid"]
128
129 if (self.__repo_conn is None):
130 self.__connect()
131
132 ver = get_powa_version(self.__repo_conn)
133
134 # Check and update PG and dependencies versions, for powa 4.1+
135 if (not ver or (int(ver[0][0]) == 4 and int(ver[0][1]) == 0)):
136 self.__disconnect_repo()
137 return
138
139 self.logger.debug("Checking postgres and dependencies versions")
140
141 if (self.__remote_conn is None or self.__repo_conn is None):
142 self.logger.error("Could not check PoWA")
143 return
144
145 cur = self.__remote_conn.cursor()
146 repo_cur = self.__repo_conn.cursor()
147
148 cur.execute("""
149 SELECT setting
150 FROM pg_settings
151 WHERE name = 'server_version'
152 --WHERE name = 'server_version_num'
153 """)
154 server_num = cur.fetchone()
155 repo_cur.execute("""
156 SELECT version
157 FROM {powa}.powa_servers
158 WHERE id = %(srvid)s
159 """, {'srvid': srvid})
160 repo_num = cur.fetchone()
161
162 if (repo_num is None or repo_num[0] != server_num[0]):
163 try:
164 repo_cur.execute("""
165 UPDATE {powa}.powa_servers
166 SET version = %(version)s
167 WHERE id = %(srvid)s
168 """, {'srvid': srvid, 'version': server_num[0]})
169 self.__repo_conn.commit()
170 except Exception as e:
171 self.logger.warning("Could not save server version"
172 + ": %s" % (e))
173 self.__repo_conn.rollback()
174
175 tbl_config = "powa_extension_config"
176 if ((int(ver[0][0]) <= 4)):
177 tbl_config = "powa_extensions"
178
179 hypo_ver = None
180 repo_cur.execute("""
181 SELECT extname, version
182 FROM {powa}.""" + tbl_config + """
183 WHERE srvid = %(srvid)s
184 """ % {'srvid': srvid})
185 exts = repo_cur.fetchall()
186
187 for ext in exts:
188 if (ext[0] == 'hypopg'):
189 hypo_ver = ext[1]
190
191 cur.execute("""
192 SELECT extversion
193 FROM pg_extension
194 WHERE extname = %(extname)s
195 """, {'extname': ext[0]})
196 remote_ver = cur.fetchone()
197
198 if (not remote_ver):
199 self.logger.debug("No version found for extension "
200 + "%s on server %d" % (ext[0], srvid))
201 continue
202
203 if (ext[1] is None or ext[1] != remote_ver[0]):
204 try:
205 repo_cur.execute("""
206 UPDATE {powa}.""" + tbl_config + """
207 SET version = %(version)s
208 WHERE srvid = %(srvid)s
209 AND extname = %(extname)s
210 """, {'version': remote_ver, 'srvid': srvid,
211 'extname': ext[0]})
212 self.__repo_conn.commit()
213 except Exception as e:
214 self.logger.warning("Could not save version for extension "
215 + "%s: %s" % (ext[0], e))
216 self.__repo_conn.rollback()
217
218 # Special handling of hypopg, which isn't required to be installed in
219 # the powa dedicated database.
220 cur.execute("""
221 SELECT default_version
222 FROM pg_available_extensions
223 WHERE name = 'hypopg'
224 """)
225 remote_ver = cur.fetchone()
226
227 if (remote_ver is None):
228 try:
229 repo_cur.execute("""
230 DELETE FROM {powa}.""" + tbl_config + """
231 WHERE srvid = %(srvid)s
232 AND extname = 'hypopg'
233 """, {'srvid': srvid, 'hypo_ver': remote_ver})
234 self.__repo_conn.commit()
235 except Exception as e:
236 self.logger.warning("Could not save version for extension "
237 + "hypopg: %s" % (e))
238 self.__repo_conn.rollback()
239 elif (remote_ver != hypo_ver):
240 try:
241 if (hypo_ver is None):
242 repo_cur.execute("""
243 INSERT INTO {powa}.""" + tbl_config + """
244 (srvid, extname, version)
245 VALUES (%(srvid)s, 'hypopg', %(hypo_ver)s)
246 """, {'srvid': srvid, 'hypo_ver': remote_ver})
247 else:
248 repo_cur.execute("""
249 UPDATE {powa}.""" + tbl_config + """
250 SET version = %(hypo_ver)s
251 WHERE srvid = %(srvid)s
252 AND extname = 'hypopg'
253 """, {'srvid': srvid, 'hypo_ver': remote_ver})
254
255 self.__repo_conn.commit()
256 except Exception as e:
257 self.logger.warning("Could not save version for extension "
258 + "hypopg: %s" % (e))
259 self.__repo_conn.rollback()
260
261 cur.close()
262 self.__remote_conn.commit()
263 repo_cur.close()
264 self.__disconnect_repo()
265
266 def __check_powa(self):
267 """Check that Powa is ready on the remote server."""
268 if (self.__remote_conn is None):
269 self.__connect()
270
271 if (self.is_stopping()):
272 return
273
274 # make sure the GUC are present in case powa isn't in
275 # shared_preload_librairies. This is only required for powa
276 # 4.0.x.
277 if (self.__remote_conn is not None):
278 self.__maybe_load_powa(self.__remote_conn)
279
280 if (self.is_stopping()):
281 return
282
283 # Check and update PG and dependencies versions if possible
284 self.__save_versions()
285
286 def __reload(self):
287 """Reload configuration
288 Disconnect from everything, read new configuration, reconnect, update
289 dependencies, check Powa is still available The new session could be
290 totally different
291 """
292 self.logger.info("Reloading configuration")
293 if (self.__pending_config is not None):
294 self.__config = self.__pending_config
295 self.__pending_config = None
296 self.__disconnect_all()
297 self.__connect()
298 if (self.__update_dep_versions):
299 self.__update_dep_versions = False
300 self.__check_powa()
301 self.__got_sighup.clear()
302
303 def __report_error(self, msg, replace=True):
304 """Store errors in the repository database.
305 replace means we overwrite current stored errors in the database for
306 this server. Else we append"""
307 if (self.__repo_conn is not None):
308 if (type(msg).__name__ == 'list'):
309 error = msg
310 else:
311 error = [msg]
312 srvid = self.__config["srvid"]
313 cur = self.__repo_conn.cursor()
314 cur.execute("SAVEPOINT metas")
315 try:
316 if (replace):
317 cur.execute("""UPDATE {powa}.powa_snapshot_metas
318 SET errors = %s
319 WHERE srvid = %s
320 """, (error, srvid))
321 else:
322 cur.execute("""UPDATE {powa}.powa_snapshot_metas
323 SET errors = pg_catalog.array_cat(errors, %s)
324 WHERE srvid = %s
325 """, (error, srvid))
326 cur.execute("RELEASE metas")
327 except psycopg2.Error as e:
328 err = "Could not report error for server %d:\n%s" % (srvid, e)
329 self.logger.warning(err)
330 cur.execute("ROLLBACK TO metas")
331 self.__repo_conn.commit()
332
333 def __connect(self):
334 """Connect to a remote server
335 Override lock_timeout, application name"""
336 if ('dsn' not in self.__repository or 'dsn' not in self.__config):
337 self.logger.error("Missing connection info")
338 self.__stopping.set()
339 return
340
341 try:
342 if (self.__repo_conn is None):
343 self.logger.debug("Connecting on repository...")
344 self.__repo_conn = get_connection(self.logger,
345 self.__debug,
346 self.__repository['dsn'])
347 self.logger.debug("Connected.")
348 # make sure the GUC are present in case powa isn't in
349 # shared_preload_librairies. This is only required for powa
350 # 4.0.x.
351 self.__maybe_load_powa(self.__repo_conn)
352
353 # Return now if __maybe_load_powa asked to stop
354 if (self.is_stopping()):
355 return
356
357 cur = self.__repo_conn.cursor()
358 cur.execute("""SELECT
359 pg_catalog.set_config(name, '2000', false)
360 FROM pg_catalog.pg_settings
361 WHERE name = 'lock_timeout'
362 AND setting = '0'""")
363
364 cur.execute("SET application_name = %s",
365 ('PoWA collector - repo_conn for worker ' + self.name,))
366 cur.close()
367 self.__repo_conn.commit()
368 self.__last_repo_conn_errored = False
369
370 if (self.__remote_conn is None):
371 self.logger.debug("Connecting on remote database...")
372 self.__remote_conn = get_connection(self.logger,
373 self.__debug,
374 **self.__config['dsn'])
375 self.logger.debug("Connected.")
376
377 # make sure the GUC are present in case powa isn't in
378 # shared_preload_librairies. This is only required for powa
379 # 4.0.x.
380 if (self.__remote_conn is not None):
381 self.__maybe_load_powa(self.__remote_conn)
382
383 # Return now if __maybe_load_powa asked to stop
384 if (self.is_stopping()):
385 return
386
387 cur = self.__remote_conn.cursor()
388 cur.execute("""SELECT
389 pg_catalog.set_config(name, '2000', false)
390 FROM pg_catalog.pg_settings
391 WHERE name = 'lock_timeout'
392 AND setting = '0'""")
393 cur.execute("SET application_name = %s",
394 ('PoWA collector - worker ' + self.name,))
395 cur.close()
396 self.__remote_conn.commit()
397
398 self.__connected.set()
399 except psycopg2.Error as e:
400 self.logger.error("Error connecting on %s:\n%s" %
401 (self._safe_dsn(), e))
402
403 if (self.__repo_conn is not None):
404 self.__report_error("%s" % (e))
405 else:
406 self.__last_repo_conn_errored = True
407
408 def __disconnect_all(self):
409 """Disconnect from remote server and repository server"""
410 if (self.__remote_conn is not None):
411 self.logger.info("Disconnecting from remote server")
412 self.__remote_conn.close()
413 self.__remote_conn = None
414 if (self.__repo_conn is not None):
415 self.logger.info("Disconnecting from repository")
416 self.__disconnect_repo()
417 self.__connected.clear()
418
419 def __disconnect_repo(self):
420 """Disconnect from repo"""
421 if (self.__repo_conn is not None):
422 self.__repo_conn.close()
423 self.__repo_conn = None
424
425 def __disconnect_all_and_exit(self):
426 """Disconnect all and stop the thread"""
427 # this is the exit point
428 self.__disconnect_all()
429 self.logger.info("stopped")
430 self.__stopping.clear()
431
432 def __worker_main(self):
433 """The thread's main loop
434 Get latest snapshot timestamp for the remote server and determine how
435 long to sleep before performing the next snapshot.
436 Add a random seed to avoid doing all remote servers simultaneously"""
437 self.__last_snap_time = None
438 self.__check_powa()
439
440 # __check_powa() is only responsible for making sure that the remote
441 # connection is opened.
442 if (self.__repo_conn is None):
443 self.__connect()
444
445 # if this worker has been restarted, restore the previous snapshot
446 # time to try to keep up on the same frequency
447 if (not self.is_stopping() and self.__repo_conn is not None):
448 cur = None
449 try:
450 cur = self.__repo_conn.cursor()
451 cur.execute("""SELECT EXTRACT(EPOCH FROM snapts)
452 FROM {powa}.powa_snapshot_metas
453 WHERE srvid = %d
454 """ % self.__config["srvid"])
455 row = cur.fetchone()
456 if not row:
457 self.logger.error("Server %d was not correctly registered"
458 " (no powa_snapshot_metas record)"
459 % self.__config["srvid"])
460 self.logger.debug("Server configuration details:\n%r"
461 % self.__config)
462 self.logger.error("Stopping worker for server %d"
463 % self.__config["srvid"])
464 self.__stopping.set()
465 if row:
466 self.__last_snap_time = float(row[0])
467 self.logger.debug("Retrieved last snapshot time:"
468 + " %r" % self.__last_snap_time)
469 cur.close()
470 self.__repo_conn.commit()
471 except Exception as e:
472 self.logger.warning("Could not retrieve last snapshot"
473 + " time: %s" % (e))
474 if (cur is not None):
475 cur.close()
476 self.__repo_conn.rollback()
477
478 # Normalize unknkown last snapshot time
479 if (self.__last_snap_time == Decimal('-Infinity')):
480 self.__last_snap_time = None
481
482 # if this worker was stopped longer than the configured frequency,
483 # assign last snapshot time to a random time between now and now minus
484 # duration. This will help to spread the snapshots and avoid activity
485 # spikes if the collector itself was stopped for a long time, or if a
486 # lot of new servers were added
487 freq = self.__config["frequency"]
488 if (not self.is_stopping()
489 and (
490 self.__last_snap_time is None
491 or
492 ((time.time() - self.__last_snap_time) > freq)
493 )):
494 random.seed()
495 r = random.randint(0, self.__config["frequency"] - 1)
496 self.logger.debug("Spreading snapshot: setting last snapshot to"
497 + " %d seconds ago (frequency: %d)" %
498 (r, freq))
499 self.__last_snap_time = time.time() - r
500
501 while (not self.is_stopping()):
502 if (self.__got_sighup.isSet()):
503 self.__reload()
504
505 if ((self.__last_snap_time is None) or
506 ((time.time() - self.__last_snap_time) >= freq) or
507 (self.__force_snapshot.isSet())):
508 try:
509 self.__snapshot_in_progress.set()
510 if (self.__force_snapshot.isSet()):
511 self.__force_snapshot.clear()
512
513 self.__last_snap_time = time.time()
514
515 self.__take_snapshot()
516 self.__snapshot_in_progress.clear()
517 except psycopg2.Error as e:
518 self.logger.error("Error during snapshot: %s" % e)
519 # It will reconnect automatically at next snapshot
520 self.__disconnect_all()
521
522 time_to_sleep = max(self.__config["frequency"] - \
523 (time.time() - self.__last_snap_time), 0)
524
525 # sleep until the scheduled processing time, or if the main thread
526 # asked us to perform an action or if we were asked to stop.
527 if (time_to_sleep > 0 and not self.is_stopping()):
528 self.__stop_sleep.wait(time_to_sleep)
529
530 # clear the event if it has been set. We'll process all possible
531 # event triggered by it within the next iteration
532 if (self.__stop_sleep.isSet()):
533 self.__stop_sleep.clear()
534
535 # main loop is over, disconnect and quit
536 self.__disconnect_all_and_exit()
537
538 def __get_global_snapfuncs(self, powa_ver):
539 """
540 Get the list of global snapshot functions (in the dedicated powa
541 database), and their associated query_src
542 """
543 srvid = self.__config["srvid"]
544
545 cur = self.__repo_conn.cursor(cursor_factory=DictCursor)
546 cur.execute("SAVEPOINT snapshots")
547 try:
548 cur.execute(get_global_snapfuncs_sql(powa_ver), (srvid,))
549 snapfuncs = cur.fetchall()
550 cur.execute("RELEASE snapshots")
551 except psycopg2.Error as e:
552 cur.execute("ROLLBACK TO snapshots")
553 err = "Error while getting snapshot functions:\n%s" % (e)
554 self.logger.error(err)
555 self.logger.error("Exiting worker for server %s..." % srvid)
556 self.__stopping.set()
557 return None
558 cur.close()
559
560 if (not snapfuncs):
561 self.logger.info("No datasource configured for server %d" % srvid)
562 self.logger.debug("Committing transaction")
563 self.__repo_conn.commit()
564 self.__disconnect_repo()
565 return None
566
567 return snapfuncs
568
569 def __get_global_src_data(self, powa_ver, ins):
570 """
571 Retrieve the source global data (in the powa database) from the foreign
572 server, and insert them in the *_src_tmp tables on the repository
573 server.
574 """
575 srvid = self.__config["srvid"]
576 errors = []
577
578 snapfuncs = self.__get_global_snapfuncs(powa_ver)
579 if not snapfuncs:
580 # __get_global_snapfuncs already took care of reporting errors
581 return errors
582
583 data_src = self.__remote_conn.cursor()
584
585 for snapfunc in snapfuncs:
586 if (self.is_stopping()):
587 return errors
588
589 kind_name = snapfunc["name"]
590 query_source = snapfunc["query_source"]
591 cleanup_sql = snapfunc["query_cleanup"]
592 function_name = snapfunc["function_name"]
593 external = snapfunc["external"]
594
595 self.logger.debug("Working on %s", kind_name)
596
597 # get the SQL needed to insert the query_src data on the remote
598 # server into the transient unlogged table on the repository server
599 if (query_source is None):
600 self.logger.warning("No query_source for %s" % function_name)
601 continue
602
603 # get the extension schema on the remote server, or skip this
604 # extension if it's not installed reporting an appropriate error
605 r_nsp = get_nsp(self.__remote_conn, external, kind_name)
606 if r_nsp is None:
607 errors.append("Extension %s is not installed on the the "
608 "remote server %s" % (kind_name, self.name))
609 continue
610
611 # get the extension schema on the repository server, or skip this
612 # extension if it's not installed reporting an appropriate error
613 tbl_nsp = get_nsp(self.__repo_conn, external, kind_name)
614 if tbl_nsp is None:
615 errors.append("Extension %s is not installed on the the "
616 "repository server" % (kind_name, ))
617 continue
618
619 # execute the query_src functions on the remote server to get its
620 # local data (srvid 0)
621 self.logger.debug("Calling %s.%s(0)..." % (r_nsp, query_source))
622 data_src_sql = get_src_query(r_nsp, query_source, srvid)
623
624 target_tbl_name = get_global_tmp_name(tbl_nsp, query_source)
625
626 errors.extend(copy_remote_data_to_repo(self, kind_name, data_src,
627 data_src_sql, ins,
628 target_tbl_name,
629 cleanup_sql))
630
631 data_src.close()
632 return errors
633
634 def __get_db_mod_snapfuncs(self, srvid):
635 """
636 Get the list of per-db module, with their associated query_source and
637 dbnames.
638 """
639 server_version_num = self.__remote_conn.server_version
640
641 db_mod_queries = defaultdict(list)
642
643 cur = self.__repo_conn.cursor(cursor_factory=DictCursor)
644 cur.execute("SAVEPOINT db_snapshots")
645 try:
646 cur.execute(get_db_mod_snapfuncs_sql(srvid, server_version_num))
647 mod_snapfuncs = cur.fetchall()
648 cur.execute("RELEASE db_snapshots")
649 except psycopg2.Error as e:
650 cur.execute("ROLLBACK TO db_snapshots")
651 err = "Error while getting db module snapshot functions:\n%s" % (e)
652 self.logger.error(err)
653 self.logger.error("Exiting worker for server %s..." % srvid)
654 self.__stopping.set()
655 return None
656 cur.close()
657
658 for func in mod_snapfuncs:
659 row = (func['db_module'], func['query_source'], func['tmp_table'])
660
661 if (func['dbnames'] is None):
662 db_mod_queries[None].append(row)
663 else:
664 for dbname in func['dbnames']:
665 db_mod_queries[dbname].append(row)
666
667 return db_mod_queries
668
669 def __get_db_cat_snapfuncs(self, srvid):
670 """
671 Get the list of per-db catalogs, with their associated query_source and
672 dbnames.
673 """
674 server_version_num = self.__remote_conn.server_version
675
676 cat_queries = []
677
678 cur = self.__repo_conn.cursor(cursor_factory=DictCursor)
679 cur.execute("SAVEPOINT db_catalog")
680 forced_dbnames = None
681 try:
682 # Make a copy of the catalog refresh registration if any while
683 # holding a lock, and also clear the registration list at the same
684 # time.
685 # It means that any cat refresh registered after that point won't
686 # be lost and will be treated once during the next snapshot.
687 with self.__register_cat_refresh_lock:
688 if (self.__register_cat_refresh_dbnames is not None):
689 forced_dbnames = self.__register_cat_refresh_dbnames.copy()
690 self.__register_cat_refresh_dbnames = None
691
692 force = True if forced_dbnames is not None else False
693 cur.execute(get_db_cat_snapfuncs_sql(srvid, server_version_num,
694 force))
695 cat_snapfuncs = cur.fetchall()
696 cur.execute("RELEASE db_catalog")
697 except psycopg2.Error as e:
698 cur.execute("ROLLBACK TO db_catalog")
699 err = "Error while getting db catalog snapshot functions:\n%s" % (e)
700 self.logger.error(err)
701 self.logger.error("Exiting worker for server %s..." % srvid)
702 self.__stopping.set()
703 return None
704
705 for func in cat_snapfuncs:
706 row = (func['catname'], func['query_source'], func['tmp_table'],
707 func['excluded_dbnames'])
708 cat_queries.append(row)
709
710 return (cat_queries, forced_dbnames)
711
712 def __get_db_src_data(self, powa_ver, now, ins):
713 """
714 Retrieve the source per-database data from the foreign server, and
715 insert them in the *_src_tmp tables on the repository server.
716 This handles both db_modules and catalog datasources.
717 """
718 srvid = self.__config["srvid"]
719 errors = []
720
721 # This is a powa 5+ feature
722 if (int(powa_ver[0][0]) < 5):
723 return errors
724
725 dbnames = self.__get_remote_dbnames()
726
727 db_mod_queries = self.__get_db_mod_snapfuncs(srvid)
728 (db_cat_queries, forced_cat_dbnames) = self.__get_db_cat_snapfuncs(srvid)
729 for dbname in dbnames:
730 # Skip that database if no module configured for it
731 do_db_module = (None in db_mod_queries or dbname in db_mod_queries)
732 do_db_cat = False
733
734 if (forced_cat_dbnames is not None):
735 if (len(forced_cat_dbnames) == 0):
736 do_db_cat = True
737 else:
738 do_db_cat = (dbname in forced_cat_dbnames)
739
740 if not do_db_cat:
741 for (_, _, _, excluded_dbnames) in db_cat_queries:
742 if (dbname not in excluded_dbnames):
743 do_db_cat = True
744 break
745
746 # Skip this database if there's no db_module or catalog to import
747 if (not do_db_module and not do_db_cat):
748 continue
749
750 self.logger.debug("Working on remote database %s", dbname)
751 errors.extend(self.__get_db_src_data_onedb(now, dbname, ins,
752 db_mod_queries,
753 db_cat_queries,
754 forced_cat_dbnames))
755 if (self.is_stopping()):
756 if (len(errors) > 0):
757 self.__report_error(errors)
758 return []
759
760 return errors
761
762 def __get_db_src_data_onedb(self, now, dbname, ins, db_mod_queries,
763 db_cat_queries, forced_cat_dbnames):
764 """
765 Per-database worker function for __get_db_src_data(), taking care of
766 db modules and catalog import.
767 """
768 srvid = self.__config["srvid"]
769 errors = []
770
771 self.logger.debug("Working on remote database %s", dbname)
772
773 try:
774 dbconn = get_connection(self.logger,
775 self.__debug,
776 override_dbname=dbname,
777 **self.__config['dsn'])
778 except psycopg2.Error as e:
779 err = "Could not connect to remote database %s:\n%s" % (dbname, e)
780 self.logger.warning(err)
781 errors.append(err)
782 return errors
783
784 data_src = dbconn.cursor()
785
786 # first, process the enabled db_modules on that database
787 for row in (db_mod_queries.get(None, []) + \
788 db_mod_queries.get(dbname, [])):
789 if (self.is_stopping()):
790 dbconn.close()
791 return errors
792
793 (db_module, query_source, tmp_table) = row
794
795 data_src_sql = """SELECT %d AS srvid, '%s' AS ts, d.dbid, src.*
796 FROM (%s) src
797 CROSS JOIN (
798 SELECT oid AS dbid
799 FROM pg_catalog.pg_database
800 WHERE datname = current_database()
801 ) d""" % (srvid, now, query_source)
802 self.logger.debug("Db module %s, calling SQL:\n%s" % (db_module,
803 data_src_sql))
804
805 errors.extend(copy_remote_data_to_repo(self, db_module, data_src,
806 data_src_sql, ins,
807 tmp_table))
808
809 # then process the outdated catalogs on that databasr
810 for row in db_cat_queries:
811 (catname, query_source, tmp_table, excluded_dbnames) = row
812
813 # Ignore this catalog if excluded for this database
814 if (forced_cat_dbnames is not None):
815 if (len(forced_cat_dbnames) == 0):
816 # empty means to process all databases
817 pass
818 elif (dbname not in forced_cat_dbnames):
819 continue
820 if (dbname in excluded_dbnames):
821 continue
822
823 data_src_sql = """SELECT %d AS srvid, d.dbid, src.*
824 FROM (%s) src
825 CROSS JOIN (
826 SELECT oid AS dbid
827 FROM pg_catalog.pg_database
828 WHERE datname = current_database()
829 ) d""" % (srvid, query_source)
830 self.logger.debug("Catalog %s, calling SQL:\n:%s" % (catname,
831 data_src_sql))
832
833 errors.extend(copy_remote_data_to_repo(self, catname, data_src,
834 data_src_sql, ins,
835 tmp_table))
836
837 data_src.close()
838 dbconn.close()
839
840 return errors
841
842 def __get_remote_dbnames(self):
843 """
844 Get the list of databases on the remote servers
845 """
846 res = []
847 cur = self.__remote_conn.cursor()
848 cur.execute("""SELECT datname
849 FROM pg_catalog.pg_database
850 WHERE datallowconn""")
851
852 for row in cur.fetchall():
853 res.append(row[0])
854
855 cur.close()
856 return res
857
858 def __take_snapshot(self):
859 """Main part of the worker thread. This function will call all the
860 query_src functions enabled for the target server, and insert all the
861 retrieved rows on the repository server, in unlogged tables, and
862 finally call powa_take_snapshot() on the repository server to finish
863 the distant snapshot. All is done in one transaction, so that there
864 won't be concurrency issues if a snapshot takes longer than the
865 specified interval. This also ensure that all rows will see the same
866 snapshot timestamp.
867 """
868 srvid = self.__config["srvid"]
869
870 if (self.is_stopping()):
871 return
872
873 self.__connect()
874
875 if (self.__remote_conn is None):
876 self.logger.error("No connection to remote server, snapshot skipped")
877 return
878
879 if (self.__repo_conn is None):
880 self.logger.error("No connection to repository server, snapshot skipped")
881 return
882
883 powa_ver = get_powa_version(self.__repo_conn)
884 powa_remote_ver = get_powa_version(self.__remote_conn)
885
886 # We require the same powa major version (X.Y) on the repository and
887 # each remote server.
888 if (powa_ver[0][0] != powa_remote_ver[0][0] or
889 powa_ver[0][1] != powa_remote_ver[0][1]):
890 error = ("Incompatible PoWA version between the repository server"
891 + " (%s.X) and the remote host (%s.X)" % (
892 powa_ver[0][0] + "." + powa_ver[0][1],
893 powa_remote_ver[0][0] + "." + powa_remote_ver[0][1]))
894
895 self.__report_error(error)
896 self.__disconnect_repo()
897 return
898 ins = self.__repo_conn.cursor()
899
900 # Retrieve the global data from the remote server
901 errors = self.__get_global_src_data(powa_ver, ins)
902 if (self.is_stopping()):
903 if (len(errors) > 0):
904 self.__report_error(errors)
905 return
906
907 with self.__remote_conn.cursor() as cur:
908 cur.execute("SELECT now()")
909 now = cur.fetchone()[0]
910
911 # Retrieve the per-db data from the remote server
912 errors.extend(self.__get_db_src_data(powa_ver, now, ins))
913 if (self.is_stopping()):
914 if (len(errors) > 0):
915 self.__report_error(errors)
916 return
917
918 # call powa_take_snapshot() for the given server
919 self.logger.debug("Calling powa_take_snapshot(%d)..." % (srvid))
920 sql = ("SELECT {powa}.powa_take_snapshot(%(srvid)d)" % {'srvid': srvid})
921 try:
922 ins.execute("SAVEPOINT powa_take_snapshot")
923 ins.execute(sql)
924 val = ins.fetchone()[0]
925 if (val != 0):
926 self.logger.warning("Number of errors during snapshot: %d",
927 val)
928 self.logger.warning(" Check the logs on the repository server")
929 ins.execute("RELEASE powa_take_snapshot")
930 except psycopg2.Error as e:
931 err = "Error while taking snapshot for server %d:\n%s" % (srvid, e)
932 self.logger.warning(err)
933 errors.append(err)
934 ins.execute("ROLLBACK TO powa_take_snapshot")
935 # Manually reset existing errors as powa_take_snapshot, which
936 # should be responsible for it, failed
937 ins.execute("""UPDATE {powa}.powa_snapshot_metas
938 SET errors = NULL
939 WHERE srvid = %(srvid)s""", {'srvid': srvid})
940
941 ins.execute("SET application_name = %s",
942 ('PoWA collector - repo_conn for worker ' + self.name,))
943 ins.close()
944
945 # we need to report and append errors after calling powa_take_snapshot,
946 # since this function will first reset errors
947 if (len(errors) > 0):
948 self.__report_error(errors, False)
949
950 # and finally commit the transaction
951 self.logger.debug("Committing transaction")
952 self.__repo_conn.commit()
953 self.__remote_conn.commit()
954
955 self.__disconnect_repo()
956
957 def is_stopping(self):
958 """Is the thread currently stopping"""
959 return self.__stopping.isSet()
960
961 def get_config(self):
962 """Returns the thread's config"""
963 return self.__config
964
965 def ask_to_stop(self):
966 """Ask the thread to stop"""
967 self.__stopping.set()
968 self.logger.info("Asked to stop...")
969 self.__stop_sleep.set()
970
971 def run(self):
972 """Start the main loop of the thread"""
973 if (not self.is_stopping()):
974 self.logger.info("Starting worker")
975 self.__worker_main()
976
977 def ask_reload(self, new_config):
978 """Ask the thread to reload"""
979 self.logger.debug("Reload asked")
980 self.__pending_config = new_config
981 self.__got_sighup.set()
982 self.__stop_sleep.set()
983
984 def ask_update_dep_versions(self):
985 """Ask the thread to recompute its dependencies"""
986 self.logger.debug("Version dependencies reload asked")
987 self.__update_dep_versions = True
988 self.__got_sighup.set()
989 self.__stop_sleep.set()
990
991 def get_status(self):
992 """Get the status: ok, not connected to repo, or not connected to remote"""
993 if (self.__repo_conn is None and self.__last_repo_conn_errored):
994 return "no connection to repository server"
995 if (self.__remote_conn is None):
996 return "no connection to remote server"
997 else:
998 return "running"
999
1000 def is_snapshot_in_progress(self):
1001 """Returns whether the worker is currently performing a snapshot"""
1002 return self.__snapshot_in_progress.isSet()
1003
1004 def request_forced_snapshot(self):
1005 """Ask for an immediate snapshot"""
1006 self.logger.debug('Forced snapshot required')
1007
1008 if (self.__snapshot_in_progress.isSet()):
1009 return ('ERROR', 'A snapshot is already in progress')
1010
1011 if (self.__force_snapshot.isSet()):
1012 return ('ERROR', 'A forced snapshot is already scheduled')
1013
1014 if ((time.time() - self.__last_snap_time ) < 10):
1015 return ('ERROR', 'Last snapshot was less than 10s. ago')
1016
1017 self.__force_snapshot.set()
1018 self.__stop_sleep.set()
1019 return ('OK', '')
1020
1021 def register_cat_refresh(self, dbnames=[]):
1022 """
1023 Register a catalog refresh on the wanted databases (or all) during the
1024 next snapshot.
1025 """
1026 self.logger.debug('Cat refresh required on databases %r', dbnames)
1027
1028 with self.__register_cat_refresh_lock:
1029 if (self.__register_cat_refresh_dbnames is None):
1030 self.__register_cat_refresh_dbnames = dbnames.copy()
1031 elif (len(dbnames) == 0):
1032 # passed empty array means all databases
1033 self.__register_cat_refresh_dbnames = []
1034 # If the stored array is empty, it means someone asked to refresh
1035 # the catalogs on all databases, so nothing to do. Otherwise, just
1036 # add the givend databases
1037 elif (len(self.__register_cat_refresh_dbnames) != 0):
1038 # it's ok to have duplicates, we don't expect too many request,
1039 # and we want to minimize the lock time
1040 self.__register_snapshot.extend(dbnames)
1041
1042 return ('OK', 'Catalogs will be refreshed during the next snapshot')