def startService(self): in_watch_mask = self.SUBFOLDER_CREATE notifier = inotify.INotify() notifier.startReading() notifier.watch(filepath.FilePath(self.path), mask=in_watch_mask, callbacks=[self.onChange])
def run(): if not watch: exit(1) if before_command: click.echo('==> reloopd, INFO : running RELOOP_BEFORE_CMD') subprocess.call(shlex.split(before_command)) if not command: click.echo( 'ERROR: environment variable RELOOP_CMD is not set! Exiting.') exit(1) global proc proc = subprocess.Popen(shlex.split(command)) click.echo('==> reloopd, INFO : watching {0} {1})'.format( ('directory' if os.path.isdir(watch) else 'file'), os.path.abspath(watch))) notifier = inotify.INotify() notifier.startReading() # recursive=True causes this whole thing to barely work... no FS changes will be detected. notifier.watch(filepath.FilePath(str(os.path.abspath(watch))), autoAdd=True, callbacks=[on_change], recursive=True) reactor.run()
def start(self): """ Register the file with iNotify and prep the file handle to the end to avoid reading the existing contents. """ # Starting listening self.notifier = inotify.INotify() self.notifier.startReading() # Note: we watch the parent directory for changes to cover log rotate # cases. If we only monitor the individual file then there is a chance # that we will not see any other changes after the file is moved # and recreated (this is a race condition if there is a 'create' # clause in the logrotate config and the producing application # does not open the file for writing again). parentDir = os.path.dirname(self.watchPath) # The original watch mask covers the following cases: # IN_MODIFY File was modified # IN_ATTRIB Metadata changed # IN_MOVED_FROM File was moved from X # IN_MOVED_TO File was moved to Y # IN_CREATE Subfile was created # IN_DELETE Subfile was delete # IN_DELETE_SELF Self was deleted # IN_MOVE_SELF Self was moved # IN_UNMOUNT Backing fs was unmounted self.notifier.watch(filepath.FilePath(str.encode(parentDir)), callbacks=[self.eventReceived]) # Seek the the end of the file before processing any new information self.openNewFile()
def setupAutoReloading(self): notifier = inotify.INotify() notifier.startReading() notifier.watch(filepath.FilePath(self.plugins_dir), callbacks=[self.reloadPluginModule]) notifier.watch(filepath.FilePath(self.plugins_config), callbacks=[self.reloadPluginModule])
def __init__(self, client, upload_dircap, local_dir_utf8, inotify=None): service.MultiService.__init__(self) try: local_dir_u = abspath_expanduser_unicode( local_dir_utf8.decode('utf-8')) if sys.platform == "win32": local_dir = local_dir_u else: local_dir = local_dir_u.encode(get_filesystem_encoding()) except (UnicodeEncodeError, UnicodeDecodeError): raise AssertionError( "The '[drop_upload] local.directory' parameter %s was not valid UTF-8 or " "could not be represented in the filesystem encoding." % quote_output(local_dir_utf8)) self._client = client self._stats_provider = client.stats_provider self._convergence = client.convergence self._local_path = FilePath(local_dir) self.is_upload_ready = False if inotify is None: from twisted.internet import inotify self._inotify = inotify if not self._local_path.exists(): raise AssertionError( "The '[drop_upload] local.directory' parameter was %s but there is no directory at that location." % quote_output(local_dir_u)) if not self._local_path.isdir(): raise AssertionError( "The '[drop_upload] local.directory' parameter was %s but the thing at that location is not a directory." % quote_output(local_dir_u)) # TODO: allow a path rather than a cap URI. self._parent = self._client.create_node_from_uri(upload_dircap) if not IDirectoryNode.providedBy(self._parent): raise AssertionError( "The URI in 'private/drop_upload_dircap' does not refer to a directory." ) if self._parent.is_unknown() or self._parent.is_readonly(): raise AssertionError( "The URI in 'private/drop_upload_dircap' is not a writecap to a directory." ) self._uploaded_callback = lambda ign: None self._notifier = inotify.INotify() # We don't watch for IN_CREATE, because that would cause us to read and upload a # possibly-incomplete file before the application has closed it. There should always # be an IN_CLOSE_WRITE after an IN_CREATE (I think). # TODO: what about IN_MOVE_SELF or IN_UNMOUNT? mask = inotify.IN_CLOSE_WRITE | inotify.IN_MOVED_TO | inotify.IN_ONLYDIR self._notifier.watch(self._local_path, mask=mask, callbacks=[self._notify])
def __init__(self, fp, toNotify): notifier = inotify.INotify() notifier.startReading() notifier.watch(filepath.FilePath(fp), callbacks=[self.eventReceived]) self.fp = fp self.f = open(fp, "r") self.f.seek(0, 2) self.toNotify = toNotify
def watch(self): """ Watch the file and set a callback """ notifier = inotify.INotify() notifier.startReading() notifier.watch(self.WATCHED_FILENAME_OBJECT, callbacks=[self._invoke_callback]) self._notifier = notifier
def test_connectionLostError(self): """ L{inotify.INotify.connectionLost} if there's a problem while closing the fd shouldn't raise the exception but should log the error """ import os in_ = inotify.INotify() os.close(in_._fd) in_.loseConnection() self.flushLoggedErrors()
def set_watch(self): self.notifier = inotify.INotify() self.notifier.startReading() try: self.notifier.watch(filepath.FilePath(self.path), mask=inotify.IN_WATCH_MASK | inotify.IN_ACCESS, callbacks=[self.inotify_twisted]) except inotify.INotifyError, e: error_message = simplejson.dumps(str(e)) self.recipent.sendLine(error_message)
def setup_notify(self): def notify(_ignored, updated_file, _mask): # Make sure it's actually the config file that was updated. if updated_file == filepath.FilePath(self.filename): self.update_config_file() logging.info('Watching for changes: %s', self.filename) self.notifier = inotify.INotify() self.notifier.startReading() self.notifier.watch(path=filepath.FilePath( os.path.dirname(self.filename)), callbacks=[notify])
def __init__(self, session): watchPath = resolveFilename(SCOPE_CURRENT_SKIN, "") print("[SkinAutoReloader] Starting watching for skin changes in %s" % watchPath) self.session = session self.bounceTimer = None self.notifier = inotify.INotify() self.notifier.startReading() self.notifier.watch(filepath.FilePath(watchPath), mask=inotify.IN_MODIFY, callbacks=[self.__notify], recursive=True)
def setup(self): logger.info('Setting up Sauron') if self.override_state: # Override previous state of conf self.eye.set_state_conf(self.conf) else: # Merge provided conf with state conf self.eye.set_base_conf(self.conf) # Register File Watcher notifier = inotify.INotify() notifier.startReading() notifier.watch(filepath.FilePath(self.conf_path), callbacks=[self.on_conf_change]) self.notifer = notifier
def __init__(self, imagePath, frameOut): self.imagePath, self.frameOut = imagePath, frameOut self.setRate(30) # not working self.inotify = inotify.INotify() self.inotify.watch(filepath.FilePath(self.imagePath).parent(), inotify.IN_WATCH_MASK, callbacks=[self.reloadImage]) # fallback from inotify task.LoopingCall(self.checkMtime).start(.2) self.reloadImage()
def __init__(self, watch_dir, shared_dict): if not os.path.exists(watch_dir): logger.error('Directory not found %s' % (watch_dir, )) raise IOError(watch_dir) self._shared_dict = shared_dict notifier = inotify.INotify() mask = inotify.IN_CREATE | inotify.IN_DELETE notifier.startReading() notifier.watch(filepath.FilePath(watch_dir), mask=mask, callbacks=[self.notify]) logger.info('watch dir %s' % (watch_dir, )) self.timers = {}
def _startNotifier(self): def notify(ignored, fp, mask): if self.transport is None: if fp.isfile(): if not self.processRunning(): self.spawnViewer(fp) self._stopNotifier() elif not fp.isfile(): self.termViewer() self._startNotifier() if self.notifier is None: self.notifier = inotify.INotify() self.notifier.startReading() self.notifier.watch(self.filePath, callbacks=[notify])
def on_conf_change(self, ignore, fp, mask): """Callback to be invoked when the file at config path changes.""" if mask == inotify.IN_DELETE_SELF: logger.info('Handling conf path change') self.notifer.stopReading() notifier = inotify.INotify() notifier.startReading() notifier.watch(filepath.FilePath(fp.path), callbacks=[self.on_conf_change]) self.notifer = notifier with fp.open() as conf: self.eye.set_base_conf(conf.read()) elif mask == inotify.IN_MODIFY: with fp.open() as conf: self.eye.set_base_conf(conf.read())
def __init__(self): # Initialize the ExtensionLoader parent object super(ModuleManager, self).__init__() self._modules = OrderedDict() self._extension = '.py' if GNU_LINUX: # Create and setup the Linux iNotify mechanism self.notifier = inotify.INotify() self.notifier.startReading() try: self.notifier.watch(filepath.FilePath(self._module_store), callbacks=[self._notify]) self._watching = True except INotifyError: self._watching = False # Start the loading process self.setup()
def load_config(self, *args): if args: masks = inotify.humanReadableMask(args[2]) #print masks if not set(masks).intersection(set(('delete_self', ))): return self.config = ConfigParser() self.config.read(CONFIG) self.commands = self.config.items('commands') if args: print "config reloaded" notifier = inotify.INotify() notifier.startReading() #print "adding watcher" notifier.watch(filepath.FilePath(CONFIG), callbacks=[self.load_config]) print "config watcher started" reactor.callLater(.5, self.send, commands=self.commands)
def Start(self): """Start watching the path.""" if platform.system() == 'Linux': # # On linux it is possible to use the inotify api. # from twisted.internet import inotify notifier = inotify.INotify() notifier.startReading() notifier.watch(filepath.FilePath(self.path_to_watch), mask=inotify.IN_CREATE, callbacks=[self._inotifyCB]) else: # # On windows we use a method from: # http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html # d = threads.deferToThread(self._watchThread)
def __init__(self): super(System, self).__init__() self.load() # These might be updated from ltsp_shared_folders, if they're used self.teachers = 'teachers' self.share_groups = [self.teachers] # INotifier for /etc/group and /etc/shadow self.system_event = Event() self.libuser_event = Event() self.system_event.connect(self.on_system_changed) self.mask = inotify.IN_MODIFY self.group_fp = filepath.FilePath( os.path.join(paths.sysconfdir, 'group')) self.shadow_fp = filepath.FilePath( os.path.join(paths.sysconfdir, 'shadow')) self.notifier = inotify.INotify() self.notifier.startReading() self.notifier._addWatch(self.group_fp, self.mask, False, [self.on_fd_changed]) self.notifier._addWatch(self.shadow_fp, self.mask, False, [self.on_fd_changed])
def startService(self): """ Starts the MailReceiver service """ Service.startService(self) self.wm = inotify.INotify() self.wm.startReading() # watch mail directories for new files to trigger processing of # incoming mail for directory, recursive in self._directories: self._start_watching_dir(directory, recursive) # schedule a periodic task to process skipped mail, and also run it # immediatelly self._lcall = task.LoopingCall(self._process_skipped) self._lcall.start(interval=self.PROCESS_SKIPPED_INTERVAL, now=True) # catch SIGUSR1 to trigger processing of skipped mail signal.signal( signal.SIGUSR1, lambda *_: self._process_skipped())
def __init__(self, operatingsystem: str, datapath: str, *args, **kwargs) -> None: super(Endpoint, self).__init__(*args, **kwargs) # initialize in memory database self.operatingsystem = operatingsystem self.datapath = datapath self.data = None self.releases: Set = set() self.components: Set = set() self.architectures: Set = set() self.release_aliases: Dict = dict() self.data_lock = asyncio.Lock() self.data_semaphore = asyncio.Semaphore(2) self.etag = None # set up data directory notifier self.notifier = inotify.INotify() self.notifier.startReading() self.notifier.watch(filepath.FilePath(datapath), callbacks=[self.notify]) # read initial data self.read_task = asyncio.ensure_future(self.read_data())
from opennode.oms.core import IApplicationInitializedEvent from opennode.oms.config import get_config from opennode.oms.endpoint.ssh.pubkey import InMemoryPublicKeyCheckerDontUse from opennode.oms.security import acl, checker from opennode.oms.security.interaction import new_interaction from opennode.oms.security.permissions import Role from opennode.oms.security.principals import User, Group log = logging.getLogger(__name__) _checkers = None if _platform == "linux" or _platform == "linux2": from twisted.internet import inotify conf_reload_notifier = inotify.INotify() conf_reload_notifier.startReading() def get_linux_groups_for_user(user): groups = [g.gr_name for g in grp.getgrall() if user in g.gr_mem] gid = pwd.getpwnam(user).pw_gid groups.append(grp.getgrgid(gid).gr_name) return groups class PamAuthChecker(object): """ Check user credentials using PAM infrastructure """ credentialInterfaces = IUsernamePassword implements(ICredentialsChecker)
def setUp(self): self.dirname = filepath.FilePath(self.mktemp()) self.dirname.createDirectory() self.inotify = inotify.INotify() self.inotify.startReading() self.addCleanup(self.inotify.loseConnection)
def __init__(self, path_to_watch, cmd): self.path = path_to_watch self.notifier = inotify.INotify() self.exploit = cmd
def __init__(self, to_watch, callback): notifier = inotify.INotify() notifier.startReading() notifier.watch(filepath.FilePath(to_watch), callbacks=[callback])
def start(self): self.notifier = inotify.INotify() self.reopenFiles()
def main(): epilog = "Copyright 2012 The LEAP Encryption Access Project" parser = argparse.ArgumentParser(description="""LEAP MX Mail receiver""", epilog=epilog) parser.add_argument('-d', '--debug', action="store_true", help="Launches the LEAP MX mail receiver with debug output") parser.add_argument('-l', '--logfile', metavar="LOG FILE", nargs='?', action="store", dest="log_file", help="Writes the logs to the specified file") parser.add_argument('-c', '--config', metavar="CONFIG FILE", nargs='?', action="store", dest="config", help="Where to look for the configuration file. " \ "Default: mail_receiver.cfg") opts, _ = parser.parse_known_args() debug = opts.debug config_file = opts.config if debug: level = logging.DEBUG else: level = logging.WARNING if config_file is None: config_file = "leap_mx.cfg" logger.setLevel(level) console = logging.StreamHandler() console.setLevel(level) formatter = logging.Formatter( '%(asctime)s ' '- %(name)s - %(levelname)s - %(message)s') console.setFormatter(formatter) logger.addHandler(console) logger.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") logger.info(" LEAP MX Mail receiver") logger.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") logger.info("Reading configuration from %s" % (config_file,)) config = ConfigParser.ConfigParser() config.read(config_file) users_user = config.get("couchdb", "users_user") users_password = config.get("couchdb", "users_password") mail_user = config.get("couchdb", "mail_user") mail_password = config.get("couchdb", "mail_password") server = config.get("couchdb", "server") port = config.get("couchdb", "port") wm = inotify.INotify(reactor) wm.startReading() mask = inotify.IN_CREATE users_db = couchdbhelper.ConnectedCouchDB(server, port=port, dbName="users", username=users_user, password=users_password) mail_couch_url_prefix = "http://%s:%s@localhost:%s" % (mail_user, mail_password, port) incoming_partial = partial(_process_incoming_email, users_db, mail_couch_url_prefix) for section in config.sections(): if section in ("couchdb"): continue to_watch = config.get(section, "path") recursive = config.getboolean(section, "recursive") logger.debug("Watching %s --- Recursive: %s" % (to_watch, recursive)) wm.watch(filepath.FilePath(to_watch), mask, callbacks=[incoming_partial], recursive=recursive) reactor.run()
def start(self): self.notifier = inotify.INotify(reactor=reactor) self.reopenFiles()
config.read(config_file) user = config.get("couchdb", "user") password = config.get("couchdb", "password") server = config.get("couchdb", "server") port = config.get("couchdb", "port") cdb = couchdbhelper.ConnectedCouchDB(server, port=port, dbName="users", username=user, password=password) # Mail receiver wm = inotify.INotify(reactor) wm.startReading() mask = inotify.IN_CREATE mail_couch_url_prefix = "http://%s:%s@%s:%s" % (user, password, server, port) incoming_partial = partial(mail_receiver._process_incoming_email, cdb, mail_couch_url_prefix) for section in config.sections(): if section in ("couchdb"): continue to_watch = config.get(section, "path") recursive = config.getboolean(section, "recursive") logger.debug("Watching %s --- Recursive: %s" % (to_watch, recursive))