|
| 1 | +import logging |
| 2 | +import multiprocessing |
| 3 | +import os |
| 4 | +import pyinotify |
| 5 | +import sys |
| 6 | +import threading |
| 7 | +import time |
| 8 | + |
| 9 | +from django.db.utils import OperationalError |
| 10 | + |
| 11 | + |
| 12 | +logging.basicConfig( |
| 13 | + level=logging.WARNING, |
| 14 | + format='%(asctime)s -> %(levelname)s: %(message)s', |
| 15 | + datefmt='%Y-%m-%d %H:%M:%S', |
| 16 | + stream=sys.stderr) |
| 17 | +logger = logging.getLogger() |
| 18 | + |
| 19 | + |
| 20 | +class Database(object): |
| 21 | + '''A object representing a pacman database on the filesystem. It stores |
| 22 | + various bits of metadata and state representing the file path, when we last |
| 23 | + updated, how long our delay is before performing the update, whether we are |
| 24 | + updating now, etc.''' |
| 25 | + def __init__(self, arch, path, callback_func, delay=60.0, nice=3, retry_limit=5): |
| 26 | + self.arch = arch |
| 27 | + self.path = path |
| 28 | + self.delay = delay |
| 29 | + self.nice = nice |
| 30 | + self.retry_limit = retry_limit |
| 31 | + self.mtime = None |
| 32 | + self.last_import = None |
| 33 | + self.update_thread = None |
| 34 | + self.updating = False |
| 35 | + self.run_again = False |
| 36 | + self.lock = threading.Lock() |
| 37 | + self.callback_func = callback_func |
| 38 | + |
| 39 | + def _start_update_countdown(self): |
| 40 | + self.update_thread = threading.Timer(self.delay, self.update) |
| 41 | + logger.info('Starting %.1f second countdown to update %s', |
| 42 | + self.delay, self.path) |
| 43 | + self.update_thread.start() |
| 44 | + |
| 45 | + def queue_for_update(self, mtime): |
| 46 | + logger.debug('Queueing database %s...', self.path) |
| 47 | + with self.lock: |
| 48 | + self.mtime = mtime |
| 49 | + if self.updating: |
| 50 | + # store the fact that we will need to run it again |
| 51 | + self.run_again = True |
| 52 | + return |
| 53 | + if self.update_thread: |
| 54 | + self.update_thread.cancel() |
| 55 | + self.update_thread = None |
| 56 | + self._start_update_countdown() |
| 57 | + |
| 58 | + def update(self): |
| 59 | + logger.debug('Updating database %s...', self.path) |
| 60 | + with self.lock: |
| 61 | + self.last_import = time.time() |
| 62 | + self.updating = True |
| 63 | + |
| 64 | + try: |
| 65 | + # invoke reporead's primary method. we do this in a separate |
| 66 | + # process for memory conservation purposes; these processes grow |
| 67 | + # rather large so it is best to free up the memory ASAP. |
| 68 | + # A retry mechanism exists for when reporead_inotify runs on a different machine. |
| 69 | + def run(): |
| 70 | + retry = True |
| 71 | + retry_count = 0 |
| 72 | + if self.nice != 0: |
| 73 | + os.nice(self.nice) |
| 74 | + while retry and retry_count < self.retry_limit: |
| 75 | + try: |
| 76 | + self.callback_func(self.arch, self.path, {}) |
| 77 | + retry = False |
| 78 | + except OperationalError as exc: |
| 79 | + retry_count += 1 |
| 80 | + logger.error('Unable to update database \'%s\', retrying=%d', self.path, retry_count, exc_info=exc) |
| 81 | + time.sleep(5) |
| 82 | + |
| 83 | + if retry_count == self.retry_limit: |
| 84 | + logger.error('Unable to update database, exceeded maximum retries') |
| 85 | + |
| 86 | + process = multiprocessing.Process(target=run) |
| 87 | + process.start() |
| 88 | + process.join() |
| 89 | + finally: |
| 90 | + logger.debug('Done updating database %s.', self.path) |
| 91 | + with self.lock: |
| 92 | + self.update_thread = None |
| 93 | + self.updating = False |
| 94 | + if self.run_again: |
| 95 | + self.run_again = False |
| 96 | + self._start_update_countdown() |
| 97 | + |
| 98 | + |
| 99 | +class EventHandler(pyinotify.ProcessEvent): |
| 100 | + '''Our main event handler which listens for database change events. Because |
| 101 | + we are watching the whole directory, we filter down and only look at those |
| 102 | + events dealing with files databases.''' |
| 103 | + |
| 104 | + def my_init(self, filename_suffix, callback_func, **kwargs): |
| 105 | + self.databases = {} |
| 106 | + self.arch_lookup = {} |
| 107 | + |
| 108 | + self.filename_suffix = filename_suffix |
| 109 | + self.callback_func = callback_func |
| 110 | + |
| 111 | + # we really want a single path to arch mapping, so massage the data |
| 112 | + arch_paths = kwargs['arch_paths'] |
| 113 | + for arch, paths in arch_paths.items(): |
| 114 | + self.arch_lookup.update((path.rstrip('/'), arch) for path in paths) |
| 115 | + |
| 116 | + def process_default(self, event): |
| 117 | + '''Primary event processing function which kicks off reporead timer |
| 118 | + threads if a files database was updated.''' |
| 119 | + name = event.name |
| 120 | + if not name: |
| 121 | + return |
| 122 | + # screen to only the files we care about, skipping temp files |
| 123 | + if name.endswith(self.filename_suffix) and not name.startswith('.'): |
| 124 | + path = event.pathname |
| 125 | + stat = os.stat(path) |
| 126 | + database = self.databases.get(path, None) |
| 127 | + if database is None: |
| 128 | + arch = self.arch_lookup.get(event.path, None) |
| 129 | + if arch is None: |
| 130 | + logger.warning( |
| 131 | + 'Could not determine arch for %s, skipping update', |
| 132 | + path) |
| 133 | + return |
| 134 | + database = Database(arch, path, self.callback_func) |
| 135 | + self.databases[path] = database |
| 136 | + database.queue_for_update(stat.st_mtime) |
| 137 | + |
| 138 | + |
| 139 | +# vim: set ts=4 sw=4 et: |
0 commit comments