Example #1
0
def setup_server(args, config, key):
    clients = []
    state_manager = StateManager(config['app_id'],
                                 Database(get_data_dir(), get_lock_file()),
                                 CommandCipher(key))

    ensure_lock_file()
    ensure_data_dir()
    wm = pyinotify.WatchManager()
    notifier = pyinotify.TornadoAsyncNotifier(wm, ioloop.IOLoop.current(),
                                              change_callback,
                                              pyinotify.ProcessEvent())
    notifier.clients = clients
    notifier.state_manager = state_manager
    wm.add_watch(get_lock_file(), pyinotify.IN_CLOSE_WRITE)

    # make sure initial state is prepared
    fresh = not state_manager.notify()
    auth_bucket = LeakyBucket(timedelta(seconds=3), 3)

    app = web.Application([
        (r'/gtd', GTDSocketHandler, {
            'config': config,
            'auth_bucket': auth_bucket,
            'clients': clients,
            'state_manager': state_manager
        }),
    ])
    app.listen(args.port, address='127.0.0.1')

    schedule_midnight(ioloop.IOLoop.current(), clients)

    return fresh
Example #2
0
    def run(self):
        prcevent = pyinotify.ProcessEvent()
        prcevent.process_default = self.__process_default
        self.__notifier = pyinotify.Notifier(self.__monitor,
                                             prcevent,
                                             timeout=self.__notify_maxtout)
        logSys.debug("[%s] filter started (pyinotifier)", self.jailName)
        while self.active:
            try:

                # slow check events while idle:
                if self.idle:
                    if Utils.wait_for(
                            lambda: not self.active or not self.idle,
                            min(self.sleeptime * 10, self.__pendingMinTime),
                            min(self.sleeptime, self.__pendingMinTime)):
                        if not self.active: break

                # default pyinotify handling using Notifier:
                self.__notifier.process_events()

                # wait for events / timeout:
                def __check_events():
                    return (not self.active or bool(
                        self.__notifier.check_events(
                            timeout=self.__notify_maxtout))
                            or (self.__pendingMinTime and self.__pending))

                wres = Utils.wait_for(
                    __check_events, min(self.sleeptime, self.__pendingMinTime))
                if wres:
                    if not self.active: break
                    if not isinstance(wres, dict):
                        self.__notifier.read_events()

                self.ticks += 1

                # check pending files/dirs (logrotate ready):
                if self.idle:
                    continue
                self._checkPending()
                if self.ticks % 10 == 0:
                    self.performSvc()

            except Exception as e:  # pragma: no cover
                if not self.active:  # if not active - error by stop...
                    break
                logSys.error(
                    "Caught unhandled exception in main cycle: %r",
                    e,
                    exc_info=logSys.getEffectiveLevel() <= logging.DEBUG)
                # incr common error counter:
                self.commonError("unhandled", e)

        logSys.debug("[%s] filter exited (pyinotifier)", self.jailName)
        self.__notifier = None

        return True
Example #3
0
 def __init__(self, files, query):
     log.debug('Watching for %s' % files)
     inotify = pyinotify.WatchManager()
     self.files = files
     self.query = query
     self.notifier = pyinotify.TornadoAsyncNotifier(
         inotify, ioloop, self.notified, pyinotify.ProcessEvent())
     inotify.add_watch(
         files, pyinotify.EventsCodes.ALL_FLAGS['IN_CLOSE_WRITE'],
         rec=True)
Example #4
0
        def __init__(self):
            inotify = pyinotify.WatchManager()
            self.files = glob('/usr/lib/libpython*')
            if not self.files:
                self.files = glob('/lib/libpython*')

            log.debug('Watching for %s' % self.files)
            self.notifier = pyinotify.TornadoAsyncNotifier(
                inotify, ioloop, self.notified, pyinotify.ProcessEvent())
            inotify.add_watch(
                self.files, pyinotify.EventsCodes.ALL_FLAGS['IN_OPEN']
                | pyinotify.EventsCodes.ALL_FLAGS['IN_CLOSE_NOWRITE'])
Example #5
0
def follow(file):
    wm = pyinotify.WatchManager()
    notifier = pyinotify.Notifier(wm, pyinotify.ProcessEvent())
    wm.add_watch(file.name, pyinotify.IN_MODIFY)

    file.seek(0, os.SEEK_END)
    while True:
        line = file.readline()
        if not line:
            notifier.check_events()
            continue
        yield line
Example #6
0
        def __init__(self, extra_search_path=None):
            inotify = pyinotify.WatchManager()
            self.files = glob('/usr/lib/libpython*')
            if not self.files:
                self.files = glob('/lib/libpython*')

            if extra_search_path is not None:
                # Handle custom installation paths
                for root, dirnames, filenames in os.walk(extra_search_path):
                    for filename in fnmatch.filter(filenames, 'libpython*'):
                        self.files.append(os.path.join(root, filename))

            log.debug('Watching for %s' % self.files)
            self.notifier = pyinotify.TornadoAsyncNotifier(
                inotify, ioloop, self.notified, pyinotify.ProcessEvent())
            inotify.add_watch(
                self.files, pyinotify.EventsCodes.ALL_FLAGS['IN_OPEN']
                | pyinotify.EventsCodes.ALL_FLAGS['IN_CLOSE_NOWRITE'])
Example #7
0
    def __start(self):
        self.__running_event.set()
        self.__events = []
        self.__timer = 0
        self.__wm = pi.WatchManager()
        handler = pi.ProcessEvent(self._on_event)
        self.__notifier = pi.Notifier(self.__wm, handler)
        while self.__running_event.is_set():
            self.__wdd = self.__wm.add_watch(self.__path,
                                             mask,
                                             rec=True,
                                             auto_add=True)
            self.__starting_event.set()
            if len(self.__wdd) > 0:
                try:
                    while self.__running_event.is_set():
                        #print 'Process events'
                        self.__notifier.process_events()
                        #print 'Check events'
                        if self.__notifier.check_events(10):
                            #print 'Read events'
                            self.__notifier.read_events()
                        #print time.time()
                        if self.__timer != 0 and time.time() > self.__timer:
                            self._on_events(self.__events)
                            self.__events = []
                            self.__timer = 0

                    pass
                    #print 'Sleep 1'
                    time.sleep(0.1)
                except KeyboardInterrupt:
                    break
            time.sleep(0.1)
        print 'Inotify stopping'
        self.__events = []
        self.__notifier.stop()
        #self.__wm.stop()
        self.__running_event.clear()
        print 'Inotify stopped'
Example #8
0
        def __init__(self, extra_search_path: Optional[str] = None) -> None:
            inotify = pyinotify.WatchManager()
            self.files = glob("/usr/lib/libpython*")
            if not self.files:
                self.files = glob("/lib/libpython*")

            if extra_search_path is not None:
                # Handle custom installation paths
                for file in Path(extra_search_path).rglob("libpython*"):
                    self.files.append(str(file.resolve()))

            log.debug("Watching for %s", self.files)
            self.notifier = pyinotify.AsyncioNotifier(
                inotify,
                asyncio.get_event_loop(),
                self.notified,
                pyinotify.ProcessEvent(),
            )
            inotify.add_watch(
                self.files,
                pyinotify.EventsCodes.ALL_FLAGS["IN_OPEN"]
                | pyinotify.EventsCodes.ALL_FLAGS["IN_CLOSE_NOWRITE"],
            )