|
| 1 | +import os |
| 2 | +import logging |
| 3 | + |
| 4 | +# Skip bson in requirements , pymongo provides |
| 5 | +# noinspection PyPackageRequirements |
| 6 | +from multiprocessing import Process, Event |
| 7 | +from pymongo import CursorType |
| 8 | +from pymongo.errors import AutoReconnect |
| 9 | +from signal import signal, SIGINT, SIGTERM |
| 10 | +from time import sleep, time |
| 11 | + |
| 12 | +from mongodb_consistent_backup.Common import DB, LocalCommand |
| 13 | +from mongodb_consistent_backup.Oplog import Oplog |
| 14 | + |
| 15 | + |
| 16 | +class TailThread(Process): |
| 17 | + def __init__(self, state, backup_name, base_dir, host, port, dump_gzip=False, user=None, |
| 18 | + password=None, authdb='admin', update_secs=10): |
| 19 | + Process.__init__(self) |
| 20 | + self.state = state |
| 21 | + self.backup_name = backup_name |
| 22 | + self.base_dir = base_dir |
| 23 | + self.host = host |
| 24 | + self.port = int(port) |
| 25 | + self.dump_gzip = dump_gzip |
| 26 | + self.user = user |
| 27 | + self.password = password |
| 28 | + self.authdb = authdb |
| 29 | + self.update_secs = update_secs |
| 30 | + |
| 31 | + self.last_update = time() |
| 32 | + self.last_update_str = "" |
| 33 | + self._connection = None |
| 34 | + self._oplog = None |
| 35 | + self._stop = Event() |
| 36 | + self.stop_ts = None |
| 37 | + |
| 38 | + self.out_dir = "%s/%s" % (self.base_dir, self.backup_name) |
| 39 | + self.oplog_file = "%s/oplog-tailed.bson" % self.out_dir |
| 40 | + if not os.path.isdir(self.out_dir): |
| 41 | + try: |
| 42 | + LocalCommand("mkdir", ["-p", self.out_dir]).run() |
| 43 | + except Exception, e: |
| 44 | + logging.error("Cannot make directory %s! Error: %s" % (self.out_dir, e)) |
| 45 | + raise e |
| 46 | + |
| 47 | + # init thread state |
| 48 | + self.state['host'] = self.host |
| 49 | + self.state['port'] = self.port |
| 50 | + self.state['file'] = self.oplog_file |
| 51 | + self.state['count'] = 0 |
| 52 | + self.state['first_ts'] = None |
| 53 | + self.state['last_ts'] = None |
| 54 | + self.state['stop_ts'] = self.stop_ts |
| 55 | + |
| 56 | + signal(SIGINT, self.close) |
| 57 | + signal(SIGTERM, self.close) |
| 58 | + |
| 59 | + # the DB connection has to be made outside of __init__ due to threading: |
| 60 | + def connection(self): |
| 61 | + try: |
| 62 | + self._connection = DB(self.host, self.port, self.user, self.password, self.authdb).connection() |
| 63 | + except Exception, e: |
| 64 | + logging.fatal("Cannot get connection - %s" % e) |
| 65 | + raise e |
| 66 | + return self._connection |
| 67 | + |
| 68 | + def oplog(self): |
| 69 | + if not self._oplog: |
| 70 | + try: |
| 71 | + self._oplog = Oplog(self.oplog_file, self.dump_gzip) |
| 72 | + except Exception, e: |
| 73 | + logging.fatal("Could not open oplog tailing file %s! Error: %s" % (self.oplog_file, e)) |
| 74 | + raise e |
| 75 | + return self._oplog |
| 76 | + |
| 77 | + def stop(self, timestamp=None): |
| 78 | + if timestamp: |
| 79 | + try: |
| 80 | + self.state['stop_ts'] = timestamp |
| 81 | + logging.info("Set oplog tail thread stop position to timestamp: %s" % timestamp) |
| 82 | + except Exception, e: |
| 83 | + logging.fatal("Cannot create bson.timestamp.Timestamp object! Error: %s" % e) |
| 84 | + raise e |
| 85 | + else: |
| 86 | + self._stop.set() |
| 87 | + |
| 88 | + def close(self, exit_code=None, frame=None): |
| 89 | + del exit_code |
| 90 | + del frame |
| 91 | + self.stop() |
| 92 | + if self._oplog: |
| 93 | + self._oplog.flush() |
| 94 | + self._oplog.close() |
| 95 | + |
| 96 | + def do_stop(self): |
| 97 | + if self.state['stop_ts'] and self.state['last_ts'] and self.state['last_ts'] >= self.state['stop_ts']: |
| 98 | + return True |
| 99 | + elif self._stop.is_set(): |
| 100 | + logging.warn("Oplog tail thread killed at timestamp: %s" % self.state['last_ts']) |
| 101 | + return True |
| 102 | + return False |
| 103 | + |
| 104 | + def status(self): |
| 105 | + update_str = "Oplog tailing of %s:%i current position: %s" % (self.host, self.port, self.state['last_ts']) |
| 106 | + if update_str != self.last_update_str: |
| 107 | + logging.info(update_str) |
| 108 | + self.last_update = time() |
| 109 | + self.last_update_str = update_str |
| 110 | + |
| 111 | + def do_status(self): |
| 112 | + return (time() - self.last_update) >= self.update_secs |
| 113 | + |
| 114 | + def run(self): |
| 115 | + conn = self.connection() |
| 116 | + db = conn['local'] |
| 117 | + |
| 118 | + logging.info("Tailing oplog on %s:%i for changes (options: gzip=%s)" % (self.host, self.port, self.dump_gzip)) |
| 119 | + |
| 120 | + oplog = self.oplog() |
| 121 | + tail_start_ts = db.oplog.rs.find().sort('$natural', -1)[0]['ts'] |
| 122 | + while not self.do_stop(): |
| 123 | + query = {'ts': {'$gt': tail_start_ts}} |
| 124 | + oplog = self.oplog() |
| 125 | + cursor = db.oplog.rs.find(query, cursor_type=CursorType.TAILABLE_AWAIT) |
| 126 | + try: |
| 127 | + while not self.do_stop(): |
| 128 | + try: |
| 129 | + # get the next oplog doc and write it |
| 130 | + doc = cursor.next() |
| 131 | + if doc: |
| 132 | + oplog.write(doc) |
| 133 | + self.state['count'] = oplog.count() |
| 134 | + self.state['first_ts'] = oplog.first_ts() |
| 135 | + self.state['last_ts'] = oplog.last_ts() |
| 136 | + self.state['stop_ts'] = self.stop_ts |
| 137 | + if self.do_status(): |
| 138 | + self.status() |
| 139 | + except (AutoReconnect, StopIteration): |
| 140 | + if self.do_stop(): |
| 141 | + break |
| 142 | + sleep(1) |
| 143 | + finally: |
| 144 | + logging.debug("Stopping oplog cursor on %s:%i" % (self.host, self.port)) |
| 145 | + cursor.close() |
| 146 | + oplog.flush() |
| 147 | + oplog.close() |
| 148 | + |
| 149 | + logging.info("Done tailing oplog on %s:%i, %i changes captured to: %s" % (self.host, self.port, self.state['count'], self.state['last_ts'])) |
0 commit comments