Beispiel #1
0
def livepdf():

    import inotifyx, sys, os, time, subprocess
    sys.path.insert(0, sourcedir)
    from conf import basic_filename

    subprocess.call(
        ['xdg-open', builddir + 'latex/' + basic_filename + '.pdf'])

    fd = inotifyx.init()

    try:
        wd = inotifyx.add_watch(fd, sourcedir, inotifyx.IN_CLOSE_WRITE)
        try:
            while True:

                events = []
                events += inotifyx.get_events(fd, 0)
                time.sleep(1)
                events += inotifyx.get_events(fd, 0)

                names = set()
                for event in events:
                    if event.name and event.name[-3:-1] != 'sw' and event.name[
                            -1] != '!':
                        names.add(sourcedir + event.name)
                if len(names) > 0:
                    print('%s modified' % ','.join(names))
                    subprocess.call(['make', 'latexpdf'])

        except KeyboardInterrupt:
            pass

    finally:
        os.close(fd)
Beispiel #2
0
  def waitDeletion(self):
    inotify_fd = inotifyx.init()
    try:
      inotifyx.add_watch(inotify_fd, self.filename, inotifyx.IN_DELETE)
      inotifyx.get_events(inotify_fd)
    except IOError: # add_watch failed
      pass
    finally:
      os.close(inotify_fd)

    self.__enter__()
Beispiel #3
0
 def ivisit(self):
     try:
         fd = inotifyx.init()
         wd = inotifyx.add_watch(fd, self.items[0], inotifyx.IN_CLOSE)
         self.urlvisit()
         inotifyx.get_events(fd, self.keep)
         inotifyx.rm_watch(fd, wd)
         os.close(fd)
     except IOError:
         hint = "consider increasing " "/proc/sys/fs/inotify/max_user_watches"
         raise util.DeadMan("failed to enable inotify", hint=hint)
    def waitDeletion(self):
        inotify_fd = inotifyx.init()
        try:
            inotifyx.add_watch(inotify_fd, self.filename, inotifyx.IN_DELETE)
            inotifyx.get_events(inotify_fd)
        except IOError:  # add_watch failed
            pass
        finally:
            os.close(inotify_fd)

        self.__enter__()
Beispiel #5
0
 def run(self):
     logging.debug('starting watcher thread')
     mask = inotifyx.IN_MODIFY | inotifyx.IN_CLOSE_WRITE
     in_fd = inotifyx.init()
     for f in self.watch_files:
         inotifyx.add_watch(in_fd, f, mask)
         logging.debug('watching ' + f)
     while True:
         logging.debug('watcher waiting for events')
         inotifyx.get_events(in_fd)
         logging.debug('watcher got change event')
         self.mapfuse.read_list()
Beispiel #6
0
 def ivisit(self):
     try:
         fd = inotifyx.init()
         wd = inotifyx.add_watch(fd, self.items[0], inotifyx.IN_CLOSE)
         self.urlvisit()
         inotifyx.get_events(fd, self.keep)
         inotifyx.rm_watch(fd, wd)
         os.close(fd)
     except IOError:
         hint = ('consider increasing '
                 '/proc/sys/fs/inotify/max_user_watches')
         raise util.DeadMan('failed to enable inotify', hint=hint)
Beispiel #7
0
 def inotifywait(self):
     """
     Blocks until file change event happens and
     self.last_update is not recent
     """
     while True:
         events = inotifyx.get_events(self.fd)
         if (now() - self.last_update).total_seconds() < 1.0:
             continue
         for e in events:
             sys.stdout.flush()
             if e.name == FILE_NAME and e.mask & self.NOTABLE:
                 while inotifyx.get_events(self.fd, 0.5):
                     pass
                 return True
Beispiel #8
0
 def get_events(self):
     new_events = []
     for path in self._watched:
         ievents = inotifyx.get_events(self._ifd, 0)
         for event in ievents:
             # if `name` is empty, it's the same directory
             abspath = os.path.join(path, event.name)
             url = Url(abspath) if event.name else self.url
             new_events.append((url, event.mask))
             if (self._recurse and event.mask & inotifyx.IN_ISDIR
                     and event.mask & inotifyx.IN_CREATE):
                 # A new directory has been created. Add a watch
                 # for it too and for all its subdirectories. Also,
                 # we need to trigger new events for any file
                 # created in it.
                 for (rootdir, dirnames, filenames) in os.walk(abspath):
                     for dirname in dirnames:
                         self.watch(os.path.join(rootdir, dirname))
                     for filename in filenames:
                         # Trigger a fake event
                         new_events.append(
                             (Url(os.path.join(rootdir, filename)),
                              events['IN_CLOSE_WRITE']
                              | events['IN_CREATE']))
     return new_events
Beispiel #9
0
 def run ( self ):
   path = self._conf['dev_path']
   exp  = re.compile(self._conf['dev_regex'])
   pd   = select.poll()
   pd.register(self._id, select.POLLIN)
   
   # Run an initial scan
   self.scan(path, exp)
   
   # Wait for events
   while self._run:
     rs = pd.poll(1000)
     if not rs: continue
     for (fd,ev) in rs:
       if fd == self._id and ev & select.POLLIN: 
         try:
           es = inotifyx.get_events(self._id)
           for e in es:
             if not (e.mask & inotifyx.IN_CREATE | inotifyx.IN_DELETE):
               continue
             p = os.path.join(path, e.name)
             if not exp.search(p): continue
             if e.mask & inotifyx.IN_CREATE:
               self.added(p)
             else:
               self.removed(p)
         except: break
Beispiel #10
0
  def run ( self ):
    scan = False
    tdir = os.path.expanduser(self._conf['track_dir'])

    # Set up poll
    pd   = select.poll()
    pd.register(self._id, select.POLLIN)

    # Scan existing files
    scan = not self.scan(tdir)

    # Wait for events
    while self._run:
      rs = pd.poll(3600000)

      # Force scan
      if scan:
        scan = not self.scan(tdir)
        continue

      # Check for events
      if not rs: continue
      for (fd,ev) in rs:
        if fd == self._id and ev & select.POLLIN:
          es = inotifyx.get_events(self._id)
          for e in es:
            if not (e.mask & inotifyx.IN_CREATE): continue
            p = os.path.join(tdir, e.name)
            if not self.added(p):
              scan = True
Beispiel #11
0
    def _observe_inotify(self, watch_dir):
        self.msg.info(self.name, 'Using inotify.')

        timeout = -1
        fd = inotifyx.init()
        try:
            self._inotify_watch_recursive(fd, watch_dir)
            while True:
                events = inotifyx.get_events(fd, timeout)
                if events:
                    for event in events:
                        if not event.mask & inotifyx.IN_ISDIR:
                            filename = self._get_playing_file_lsof(self.process_name)
                            (state, show_tuple) = self._get_playing_show(filename)
                            self.update_show_if_needed(state, show_tuple)

                            if self.last_state == STATE_NOVIDEO:
                                # Make get_events block indifinitely
                                timeout = -1
                            else:
                                timeout = 1
                else:
                    self.update_show_if_needed(self.last_state, self.last_show_tuple)
        except IOError:
            self.msg.warn(self.name, 'Watch directory not found! Tracker will stop.')
        finally:
            os.close(fd)
Beispiel #12
0
    def get_events(self):
        newevents = []
        for path, ifd in self._ifds.items():
            ievents = inotifyx.get_events(ifd, 0)
            for event in ievents:
                # if `name` is empty, it's the same directory
                abspath = os.path.join(path, event.name)
                url = Url(abspath) if event.name else self.url
                newevents.append((url, event.mask))
                if self._recurse and \
                   event.mask & inotifyx.IN_ISDIR and \
                   event.mask & inotifyx.IN_CREATE:
                    # New directory has been created. We need to add a
                    # watch for this directory too and for all its
                    # subdirectories. Also, we need to trigger new
                    # events for any other file created in it

                    for (rootdir, dirnames, filenames) in os.walk(abspath):
                        for dirname in dirnames:
                            self._add_watch(os.path.join(rootdir, dirname))
                        for filename in filenames:
                            # Trigger a fake event
                            newevents.append((Url(os.path.join(rootdir, filename)),
                                              events['IN_CLOSE_WRITE']|events['IN_ALL_EVENTS']))
        return newevents
Beispiel #13
0
	def processEvents(self, events):
		i = 0
		l = len(events)
		while i < l:
			e = events[i]
			i += 1
			if e.mask & inotifyx.IN_MOVED_FROM:
				if i < l and (events[i].cookie == e.cookie):
					e2 = events[i]
					assert e2.mask == (inotifyx.IN_MOVED_TO | e.mask & inotifyx.IN_ISDIR)
					i += 1
					self._move(e.wd, e2.wd, e.mask, e.name, e2.name)
				else:
					self._move(e.wd, None, e.mask, e.name, e.name)
			elif e.mask & inotifyx.IN_MOVED_TO:
				self._move(None, e.wd, e.mask, e.name, e.name)
			elif e.mask & inotifyx.IN_MOVE_SELF:
				self._move_self(e.wd, e.mask, e.name)
			elif e.mask & inotifyx.IN_DELETE_SELF:
				self._delete_self(e.wd, e.mask, e.name)
			elif e.mask & inotifyx.IN_CREATE:
				self._create(e.wd, e.mask, e.name)
			elif e.mask & inotifyx.IN_ATTRIB:
				self._attrib(e.wd, e.mask, e.name)
			elif e.mask & inotifyx.IN_CLOSE_WRITE:
				self._close_write(e.wd, e.mask, e.name)
			elif e.mask & inotifyx.IN_DELETE:
				self._delete(e.wd, e.mask, e.name)
			elif e.mask & inotifyx.IN_IGNORED:
				pass
			else:
				print "???", e
		events = inotifyx.get_events(self.fd, 0)
		if events:
			self.enqueue(ProcessEvents(events))
Beispiel #14
0
    def run(self):
        """Run the event detection.
        """

        if self.create_job is not None:
            self.create_job.start()

        n_events = 0
        run_loop = True
        t_start = 0
        while run_loop:
            events = inotifyx.get_events(self.inotify_binding, self.timeout)

            if t_start and not events:
                run_loop = False

            for event in events:
                if not t_start:
                    t_start = time.time()

                if event.wd < 0:
                    continue

                event_type = event.get_mask_description()
                event_type_array = event_type.split("|")

                if "IN_OPEN" in event_type_array:
                    n_events += 1

        t_needed = time.time() - t_start
        print("n_events {} in {} s, ({} Hz)".format(n_events, t_needed,
                                                    n_events / t_needed))

        if self.create_job is not None:
            self.create_job.join()
Beispiel #15
0
	def run(self):
		# watch intel vbtn for event to know when to parse dmesg for what it was
		self.log.info("StanceWatcher started")
		vbtnWatchFd = inotifyx.init()
		try:
			self.log.debug("Add Watch for Intel Virtual Button input...")
			vbtnWatch = inotifyx.add_watch(vbtnWatchFd, Config['intelVbtnInput'], inotifyx.IN_ACCESS)
			
			lastEventTime = 0.0
			while not self.stopEv.is_set():
				vbtnEvent = inotifyx.get_events(vbtnWatchFd,0.8)
				if len(vbtnEvent) > 0:
					now = time.time();
					# vbtn event file is modified multiple times on a lid rotation, a quick solution to fire stance change only once
					# assuming the user won't rotate the lid very frequently (like under a second...)
					if now - lastEventTime > 0.8:
						self.log.debug("lid rotate event occurred, parse syslog...")
						time.sleep(0.2) #give time for event to appear in syslog
						readStance = self.parseStanceFromSyslog()
						if readStance:
							self.stance = readStance
							self.log.debug("Stance updated to %s", self.stance)
							self.changeEvent.set()
						else:
							self.log.warning("Got None, stance NOT updated.")
					else:
						self.log.debug("event discarded, too soon")
					lastEventTime = now
			inotifyx.rm_watch(vbtnWatchFd, vbtnWatch)
			self.log.debug("Removed watch for Intel Virtual Button input")
		finally:
			os.close(vbtnWatchFd)
Beispiel #16
0
    def run(self):
        path = self._conf['dev_path']
        exp = re.compile(self._conf['dev_regex'])
        pd = select.poll()
        pd.register(self._id, select.POLLIN)

        # Run an initial scan
        self.scan(path, exp)

        # Wait for events
        while self._run:
            rs = pd.poll(1000)
            if not rs: continue
            for (fd, ev) in rs:
                if fd == self._id and ev & select.POLLIN:
                    try:
                        es = inotifyx.get_events(self._id)
                        for e in es:
                            if not (e.mask & inotifyx.IN_CREATE
                                    | inotifyx.IN_DELETE):
                                continue
                            p = os.path.join(path, e.name)
                            if not exp.search(p): continue
                            if e.mask & inotifyx.IN_CREATE:
                                self.added(p)
                            else:
                                self.removed(p)
                    except:
                        break
Beispiel #17
0
    def get_events(self):
        newevents = []
        for path, ifd in self._ifds.items():
            ievents = inotifyx.get_events(ifd, 0)
            for event in ievents:
                # if `name` is empty, it's the same directory
                abspath = os.path.join(path, event.name)
                url = Url(abspath) if event.name else self.url
                newevents.append((url, event.mask))
                if self._recurse and \
                   event.mask & inotifyx.IN_ISDIR and \
                   event.mask & inotifyx.IN_CREATE:
                    # New directory has been created. We need to add a
                    # watch for this directory too and for all its
                    # subdirectories. Also, we need to trigger new
                    # events for any other file created in it

                    for (rootdir, dirnames, filenames) in os.walk(abspath):
                        for dirname in dirnames:
                            self._add_watch(os.path.join(rootdir, dirname))
                        for filename in filenames:
                            # Trigger a fake event
                            newevents.append(
                                (Url(os.path.join(rootdir, filename)),
                                 events['IN_CLOSE_WRITE']
                                 | events['IN_ALL_EVENTS']))
        return newevents
Beispiel #18
0
    def _observe_inotify(self, watch_dir):
        self.msg.info(self.name, 'Using inotify.')

        timeout = -1
        fd = inotifyx.init()
        try:
            self._inotify_watch_recursive(fd, watch_dir)
            while True:
                events = inotifyx.get_events(fd, timeout)
                if events:
                    for event in events:
                        if not event.mask & inotifyx.IN_ISDIR:
                            (state, show_tuple) = self._get_playing_show()
                            self.update_show_if_needed(state, show_tuple)

                            if self.last_state == STATE_NOVIDEO:
                                # Make get_events block indifinitely
                                timeout = -1
                            else:
                                timeout = 1
                else:
                    self.update_show_if_needed(self.last_state,
                                               self.last_show_tuple)
        except IOError:
            self.msg.warn(self.name,
                          'Watch directory not found! Tracker will stop.')
        finally:
            os.close(fd)
Beispiel #19
0
 def every_main_loop(self):
     # Check if any new file has been created. The 5 seconds
     # timeout allows us to continue the execution if no new file
     # is created.
     events = inotifyx.get_events(self.ifd, 5)
     for event in events:
         fname = event.name
         self.add_new_application(fname)
Beispiel #20
0
    def clear(self):
        """Clears and returns any changed files that are waiting in the queue."""

        events = inotifyx.get_events(self.fd, 0)
        change_set = set(
            os.path.join(self.watches.get(event.wd, ''), event.name or '')
            for event in events if self.is_white_listed(event.name))
        return change_set
    def clear(self):
        """Clears and returns any changed files that are waiting in the
        queue."""

        events = inotifyx.get_events(self.fd, 0)
        change_set = set(os.path.join(self.watches.get(event.wd, ''),
                                      event.name or '')
                         for event in events if self.is_white_listed(event.name))
        return change_set
Beispiel #22
0
 def test_file_create(self):
     inotifyx.add_watch(self.fd, self.testdir, inotifyx.IN_CREATE)
     self._create_file('foo')
     try:
         events = inotifyx.get_events(self.fd)
         self.assertEqual(len(events), 1)
         self.assertEqual(events[0].mask, inotifyx.IN_CREATE)
         self.assertEqual(events[0].name, 'foo')
     finally:
         os.unlink('foo')
Beispiel #23
0
	def run(self):
		while True:
			timeout = ()

			if self.queue:
				heapq.heappop(self.queue).run(self)
				timeout = (0,)
			events = inotifyx.get_events(self.fd, *timeout)
			if events:
				self.enqueue(ProcessEvents(events))
Beispiel #24
0
    def __iter__(self):
        """Iterating a monitor returns the next set of changed files.

        When requesting the next item from a monitor it will block
        until file changes are detected and then return the set of
        changed files.
        """

        while True:
            # Block until events arrive.
            events = inotifyx.get_events(self.fd)

            # Collect any events that occur within the delay period.
            # This allows events that occur close to the trigger event
            # to be collected now rather than causing another run
            # immediately after this run.
            if self.delay:
                time.sleep(self.delay)
                events.extend(inotifyx.get_events(self.fd, 0))

            # Filter to events that are white listed.
            events = [
                event for event in events if self.is_white_listed(event.name)
            ]

            if events:
                # Track watched dirs.
                for event in events:
                    if event.mask & inotifyx.IN_ISDIR and event.mask & inotifyx.IN_CREATE:
                        self.watches[inotifyx.add_watch(
                            self.fd,
                            os.path.join(self.watches.get(event.wd),
                                         event.name),
                            self.WATCH_EVENTS)] = os.path.join(
                                self.watches.get(event.wd), event.name)
                    elif event.mask & inotifyx.IN_DELETE_SELF:
                        self.watches.pop(event.wd, None)

                # Supply this set of changes to the caller.
                change_set = set(
                    os.path.join(self.watches.get(event.wd, ''), event.name
                                 or '') for event in events)
                yield change_set
Beispiel #25
0
 def test_file_create(self):
     inotifyx.add_watch(self.fd, self.test_dir, inotifyx.IN_CREATE)
     self._create_file('foo')
     try:
         events = inotifyx.get_events(self.fd)
         self.assertEqual(len(events), 1)
         self.assertEqual(events[0].mask, inotifyx.IN_CREATE)
         self.assertEqual(events[0].name, 'foo')
     finally:
         os.unlink('foo')
Beispiel #26
0
def watchFiles(queue):
    mediaFound = False
    fd = inotifyx.init()
    wd = inotifyx.add_watch(fd, watchPath, inotifyx.IN_CLOSE)

    while (1):
	# Wait for an event with timeout.
	event = inotifyx.get_events(fd, eventTimeout)
	print("Event caught, or timed-out.")

	# Wait before reading files
	time.sleep(readDelay)

	for fname in os.listdir(watchPath):
	    fpath = os.path.join(watchPath, fname)
	    if (os.path.isfile(fpath) and fname.startswith(watchFilePrefix)
			and fname.endswith(watchFileSuffix)):
		mediaFound = False
		print ("Processing file: " + fpath)
		f = open(fpath, "r")

		for line in f:
		    pieces = shlex.split(line.strip())
		    for p in pieces:
			queue.put(p)
			print ("Found: " + p)
			mediaFound = True
		f.close()

		# Only remove the file if we found something in it
		if(mediaFound):
		    os.remove(fpath)
		    print("Deleting file.")

	# Drain events from file operations.
	e = inotifyx.get_events(fd, 0)
	while e:
	    e = inotifyx.get_events(fd, 0)

    inotifyx.rm_watch(fd, wd)
    os.close(fd)
Beispiel #27
0
def subfiles(directory):
  """Return the list of subfiles of a directory, and wait for the newly created
  ones.

  CAUTION : *DONT TRY TO CONVERT THE RESULT OF THIS FUNCTION INTO A LIST !
  ALWAYS ITERATE OVER IT !!!*"""
  watchfd = inotifyx.init()
  inotifyx.add_watch(watchfd, directory, inotifyx.IN_CREATE)
  try:

    subfiles = set(os.listdir(directory))
    subfiles |= set([file_.name for file_ in inotifyx.get_events(watchfd, 0)])

    while True:
      for file_ in subfiles:
        yield os.path.join(directory, file_)

      subfiles = [file_.name for file_ in inotifyx.get_events(watchfd)]

  finally:
    os.close(watchfd)
Beispiel #28
0
 def test_file_remove(self):
     self._create_file('foo')
     try:
         inotifyx.add_watch(self.fd, self.testdir, inotifyx.IN_DELETE)
     except:
         os.unlink('foo')
         raise
     os.unlink('foo')
     events = inotifyx.get_events(self.fd)
     self.assertEqual(len(events), 1)
     self.assertEqual(events[0].mask, inotifyx.IN_DELETE)
     self.assertEqual(events[0].name, 'foo')
Beispiel #29
0
 def test_file_remove(self):
     self._create_file('foo')
     try:
         inotifyx.add_watch(self.fd, self.test_dir, inotifyx.IN_DELETE)
     except:
         os.unlink('foo')
         raise
     os.unlink('foo')
     events = inotifyx.get_events(self.fd)
     self.assertEqual(len(events), 1)
     self.assertEqual(events[0].mask, inotifyx.IN_DELETE)
     self.assertEqual(events[0].name, 'foo')
def subfiles(directory):
    """Return the list of subfiles of a directory, and wait for the newly created
  ones.

  CAUTION : *DONT TRY TO CONVERT THE RESULT OF THIS FUNCTION INTO A LIST !
  ALWAYS ITERATE OVER IT !!!*"""
    watchfd = inotifyx.init()
    inotifyx.add_watch(watchfd, directory, inotifyx.IN_CREATE)
    try:

        subfiles = set(os.listdir(directory))
        subfiles |= set(
            [file_.name for file_ in inotifyx.get_events(watchfd, 0)])

        while True:
            for file_ in subfiles:
                yield os.path.join(directory, file_)

            subfiles = [file_.name for file_ in inotifyx.get_events(watchfd)]

    finally:
        os.close(watchfd)
    def __iter__(self):
        """Iterating a monitor returns the next set of changed files.

        When requesting the next item from a monitor it will block
        until file changes are detected and then return the set of
        changed files.
        """

        while True:
            # Block until events arrive.
            events = inotifyx.get_events(self.fd)

            # Collect any events that occur within the delay period.
            # This allows events that occur close to the trigger event
            # to be collected now rather than causing another run
            # immediately after this run.
            if self.delay:
                time.sleep(self.delay)
                events.extend(inotifyx.get_events(self.fd, 0))

            # Filter to events that are white listed.
            events = [event for event in events if self.is_white_listed(event.name)]

            if events:
                # Track watched dirs.
                for event in events:
                    if event.mask & inotifyx.IN_ISDIR and event.mask & inotifyx.IN_CREATE:
                        self.watches[inotifyx.add_watch(self.fd, os.path.join(self.watches.get(event.wd), event.name), self.WATCH_EVENTS)] = os.path.join(self.watches.get(event.wd), event.name)
                    elif event.mask & inotifyx.IN_DELETE_SELF:
                        self.watches.pop(event.wd, None)

                # Supply this set of changes to the caller.
                change_set = set(os.path.join(self.watches.get(event.wd, ''),
                                              event.name or '')
                                 for event in events)
                yield change_set
Beispiel #32
0
def _main():
    watch_dir = "/tmp/watch_tree"
    create_thread = threading.Thread(target=create_test_files,
                                     args=(watch_dir, ))

    try:
        os.mkdir(watch_dir)
    except OSError:
        pass

    fd = inotifyx.init()

    wd_to_path = {}

    try:
        wd = inotifyx.add_watch(fd, watch_dir)
        wd_to_path[wd] = watch_dir

        print("wd_to_path: ", wd_to_path)
    except Exception:
        print("stopped")
        os.close(fd)
        sys.exit(1)

    create_thread.start()

    try:
        while True:
            events = inotifyx.get_events(fd)

            for event in events:
                path = wd_to_path[event.wd]
                event_type = event.get_mask_description()
                event_type_array = event_type.split("|")

                # remember dir name
                if "IN_ISDIR" in event_type_array and "IN_CREATE" in event_type:
                    new_dir = os.path.join(path, event.name)
                    wd = inotifyx.add_watch(fd, new_dir)
                    wd_to_path[wd] = new_dir

                print("PATH=[{}] FILENAME=[{}] EVENT_TYPES={}".format(
                    path, event.name, event_type_array))

    except KeyboardInterrupt:
        pass
    finally:
        os.close(fd)
Beispiel #33
0
    def tail(self):
        fd = inotifyx.init()
        try:
            wd = inotifyx.add_watch(fd, '/var/log/emerge.log', inotifyx.IN_MODIFY)

            self.log_currentcompile(1) # only wait for a second for the sandbox

            while True:
		self.log_heartbeat()
                events = inotifyx.get_events(fd, float(self.nap))
                if len(events) != 0: # not timeout
                    self.log_currentcompile(self.sandboxwait)

            inotifyx.rm_watch(fd, wd)
        finally:
            os.close(fd)
Beispiel #34
0
def main_linux(data_dir):
    """Notify about events triggered base on inotify.

    Args:
        data_dir: The directory to watch.
    """
    from inotifyx import init, add_watch, get_events

    inotify_fd = init()
    wd_to_path = {}

    try:
        # get all subdirs
        # do not register right away because it will trigger events
        dirs = []
        for root, _, _ in os.walk(data_dir):
            dirs.append(root)

        for i in dirs:
            wd_to_path[add_watch(inotify_fd, i)] = i

        try:
            while True:
                events = get_events(inotify_fd)
                for event in events:
                    path = wd_to_path[event.wd]
                    parts = event.get_mask_description()

                    logging.info("%s: %s/%s", parts, path, event.name)

                    #                    is_created = ("IN_CREATE" in parts)
                    #                    is_dir = ("IN_ISDIR" in parts)
                    #                    is_closed = ("IN_CLOSE" in a_array
                    #                                 or "IN_CLOSE_WRITE" in a_array)

                    # if a new directory is created inside the monitored one,
                    # this one has to be monitored as well
                    #                    if is_created and is_dir and event.name:
                    if ("IN_CREATE" in parts and "IN_ISDIR" in parts
                            and event.name):
                        dirname = path + os.sep + event.name
                        wd_to_path[add_watch(inotify_fd, dirname)] = dirname

        except KeyboardInterrupt:
            pass
    finally:
        os.close(inotify_fd)
Beispiel #35
0
    def do_watch(self):
        events = inotifyx.get_events(self.watch_fd, 0)
        if events != None:
            filt = [e for e in events if (not e.name.startswith('.') and
                                          e.name.endswith('.cnote-theme'))]
            for e in filt:
                path = os.path.join(self.watches[e.wd], e.name)
                logging.info('reloading: {0}: {1}'.format(
                        path, e.get_mask_description()))
                t = Theme(path)
                if not t.success:
                    continue
                tname = t['metadata']['name']
                self.themes[tname] = t
                self.resolve_bases()

        return 1
Beispiel #36
0
def currentFile(inputFile, watchDescriptor):
    # Checks whether inputFile is the current log file.
    # watchDescriptor should be the file descriptor returned by inotifyx.init()
    # Returns True/False

    events = inotifyx.get_events(watchDescriptor, 1)
    logger.debug("IN events: %s" % (len(events)))
    for e in events:
        logger.debug("Event: %s" % e.mask)

    if len(events) >= 1:
        # There were writes, assume current
        logger.debug("currentFile True")
        return True
    else:
        logger.debug("currentFile False")
        return False
Beispiel #37
0
 def run(self):
     while 1:
         try:
             events = inotifyx.get_events(self._fd)
         except KeyboardInterrupt:
             break
         for event in events:
             if event.mask & inotifyx.IN_CREATE:
                 self._starts[event.wd] = event.name
             elif event.mask & inotifyx.IN_CLOSE_WRITE:
                 name = self._starts.pop(event.wd, None)
                 if name is not None:
                     thedir = self._watches[event.wd]
                     syslog.syslog(
                         "created {!r}".format(name).encode("ascii"))
                     InotifyWatcher.created.send(self,
                                                 path=os.path.join(
                                                     thedir, name))
Beispiel #38
0
    def watch(self):

        fd = inotifyx.init()
        wd = inotifyx.add_watch(fd, self.pickup_dir, inotifyx.constants["IN_CLOSE_WRITE"])

        keep_running = True

        while keep_running:
            try:
                events = inotifyx.get_events(fd, 1.0)
                for event in events:
                    self.pickup_event_processor.process(event)

                sleep(0.1)
            except KeyboardInterrupt:
                keep_running = False

        os.close(fd)
def _main():
    watch_dir = "/tmp/watch_tree"

    try:
        for path in watch_dir:
            os.mkdir(path)
    except OSError:
        pass

    fd = inotifyx.init()

    wd_to_path = {}

    try:
        wd = inotifyx.add_watch(fd, watch_dir)
        wd_to_path[wd] = watch_dir
        print("wd_to_path: ", wd_to_path)
    except Exception as excp:
        print("stopped")
        print("Exception was", excp)
        os.close(fd)
        sys.exit(1)

    with open(os.path.join(watch_dir, "test_file"), "w"):
        pass

    try:
        while True:
            events = inotifyx.get_events(fd)

            for event in events:
                path = wd_to_path[event.wd]
                event_type = event.get_mask_description()
                event_type_array = event_type.split("|")

                print("PATH=[{}] FILENAME=[{}] EVENT_TYPES={}".format(
                    path, event.name, event_type_array))

    except KeyboardInterrupt:
        pass
    finally:
        os.close(fd)
    def ssh(self, cmd, output_catcher=ForwardToStd(),
            remotes_stdin=None):
        if not cmd:
            # XXX: Where do these empty commands come from?
            return
        def assert_master_openssh_running():
            if self.master_openssh.poll() == 255:
                raise Offline(self)

        ssh_master_socket = self.ssh_master_socket
        if not ssh_master_socket:
            ssh_master_socket_dir = on_exit_vanishing_dtemp()
            ssh_master_socket = join(ssh_master_socket_dir, 'socket')
            self.ssh_master_socket = ssh_master_socket
            fd = inotifyx.init()
            try:
                inotifyx.add_watch(fd, ssh_master_socket_dir)
                self.master_openssh = master_openssh = self.openssh(
                        ['-M', '-N']
                        + remote_authorized_key_env(),
                        [], stderr=PIPE)
                filter_masters_stderr_thread = threading.Thread(
                        target=self.filter_masters_stderr,
                        args=(master_openssh.stderr,)
                        )
                filter_masters_stderr_thread.daemon = True
                filter_masters_stderr_thread.start()
                # Wait for termination in the case the target is
                # not available:
                while True:
                    if inotifyx.get_events(fd, 0.1):
                        register(master_openssh.kill)
                        break
                    assert_master_openssh_running()
            finally:
                os.close(fd)
        cmd_openssh = self.openssh(output_catcher.allocate_tty, [cmd],
                remotes_stdin, output_catcher.remotes_stdout,
                output_catcher.remotes_stdout)
        communicate_with_child(cmd_openssh, output_catcher,
                assert_master_openssh_running, cmd)
Beispiel #41
0
def scan(topdir):
    '''
    print filesystem events for tree of files
    '''
    fd = inotifyx.init()

    mask = inotifyx.IN_MODIFY | inotifyx.IN_CLOSE_WRITE
    if 0:
        mask = inotifyx.IN_ALL_EVENTS

    wd_to_path = add_watch_dirs(
        topdir=topdir,
        fd=fd,
        mask=mask,
        )

    try:
        oldpath = None
        while True:
            for event in inotifyx.get_events(fd):
                path = os.path.join(
                    wd_to_path[event.wd],
                    event.name if event.name else '',
                    )

                parts = [ event.get_mask_description() ]
                parts = [ word.replace('IN_ALL_EVENTS|', '')
                          for word in parts
                          ]

                if path != oldpath:
                    print path
                oldpath = path
                print '\t', ' '.join(parts)

    except KeyboardInterrupt:
        pass
    finally:
        os.close(fd)
Beispiel #42
0
def ino_watch(file_to_watch, action, *action_args):
    ''' ``inotify``-based watcher, applying function upon
        *write-and-close* events '''
    watcher = inotifyx.init()
    #TODO: implement check like "it's a directory and you don't run a cmd!"
    if not os.path.isdir(file_to_watch):
        dirname = os.path.dirname(file_to_watch) or '.'
        basename = os.path.basename(file_to_watch)
    else:
        dirname = file_to_watch
        basename = None
    # we watch for CLOSE_WRITE events in directory and filter them by file name
    # because editors like vim do save&rename instead of simple modification
    inotifyx.add_watch(watcher, dirname, inotifyx.IN_CLOSE_WRITE)
    # wrap action to avoid code duplication
    action_lambda = lambda: action(file_to_watch, *action_args)
    # run the first time
    action_lambda()
    while True:
        events = inotifyx.get_events(watcher)
        if (basename is None) or (basename in (ev.name for ev in events)):
            action_lambda()
Beispiel #43
0
def _wait_files_creation(file_list):
  # Etablish a list of directory and subfiles
  directories = dict()
  for dirname, filename in [os.path.split(f) for f in file_list]:
    directories.setdefault(dirname, dict())
    directories[dirname][filename] = False

  def all_files_exists():
    return all([all(files.values()) for files in directories.values()])

  fd = inotifyx.init()
  try:
    # Watch every directories where the file are
    watchdescriptors = dict()
    for dirname in directories.keys():
      wd = inotifyx.add_watch(fd,
                              dirname,
                              inotifyx.IN_CREATE | inotifyx.IN_DELETE)
      watchdescriptors[wd] = dirname

    # Set to True the file wich exists
    for dirname, filename in [os.path.split(f) for f in file_list]:
      directories[dirname][filename] = os.path.exists(os.path.join(dirname,
                                                                   filename))
    # Let's wait for every file creation
    while not all_files_exists():
      events_list = inotifyx.get_events(fd)
      for event in events_list:
        dirname = watchdescriptors[event.wd]
        if event.name in directories[dirname]:
          # One of watched file was created or deleted
          if event.mask & inotifyx.IN_DELETE:
            directories[dirname][event.name] = False
          else:
            directories[dirname][event.name] = True

  finally:
    os.close(fd)
def _wait_files_creation(file_list):
    # Etablish a list of directory and subfiles
    directories = dict()
    for dirname, filename in [os.path.split(f) for f in file_list]:
        directories.setdefault(dirname, dict())
        directories[dirname][filename] = False

    def all_files_exists():
        return all([all(files.values()) for files in directories.values()])

    fd = inotifyx.init()
    try:
        # Watch every directories where the file are
        watchdescriptors = dict()
        for dirname in directories.keys():
            wd = inotifyx.add_watch(fd, dirname,
                                    inotifyx.IN_CREATE | inotifyx.IN_DELETE)
            watchdescriptors[wd] = dirname

        # Set to True the file wich exists
        for dirname, filename in [os.path.split(f) for f in file_list]:
            directories[dirname][filename] = os.path.exists(
                os.path.join(dirname, filename))
        # Let's wait for every file creation
        while not all_files_exists():
            events_list = inotifyx.get_events(fd)
            for event in events_list:
                dirname = watchdescriptors[event.wd]
                if event.name in directories[dirname]:
                    # One of watched file was created or deleted
                    if event.mask & inotifyx.IN_DELETE:
                        directories[dirname][event.name] = False
                    else:
                        directories[dirname][event.name] = True

    finally:
        os.close(fd)
Beispiel #45
0
    def get_new_event(self):
        """Implementation of the abstract method get_new_event.

        Returns:
            A list of event messages generated from inotify events.
        """

        remaining_events = self.get_remaining_events()

        # only take the events which are not handles yet
        event_message_list = [
            event for event in remaining_events if [
                os.path.join(event["source_path"], event["relative_path"]),
                event["filename"]
            ] not in self.history
        ]
        self.history += [[
            os.path.join(event["source_path"], event["relative_path"]),
            event["filename"]
        ] for event in remaining_events]

        # event_message_list = self.get_remaining_events()
        event_message = {}

        events = inotifyx.get_events(self.file_descriptor, self.timeout)
        removed_wd = None

        for event in events:

            if not event.name:
                continue

            try:
                path = self.wd_to_path[event.wd]
            except Exception:
                path = removed_wd
            parts = event.get_mask_description()
            parts_array = parts.split("|")

            is_dir = ("IN_ISDIR" in parts_array)
            is_created = ("IN_CREATE" in parts_array)
            is_moved_from = ("IN_MOVED_FROM" in parts_array)
            is_moved_to = ("IN_MOVED_TO" in parts_array)

            current_mon_event = None
            current_mon_regex = None
            for key, value in iteritems(self.mon_regex_per_event):
                if key in parts_array:
                    current_mon_event = key
                    current_mon_regex = value
#                    current_mon_regex = self.mon_regex_per_event[key]

#            if not is_dir:
#                self.log.debug("{} {} {}".format(path, event.name, parts))
#                self.log.debug("current_mon_event: {}"
#                               .format(current_mon_event))
#            self.log.debug(event.name)
#            self.log.debug("is_dir: {}".format(is_dir))
#            self.log.debug("is_created: {}".format(is_created))
#            self.log.debug("is_moved_from: {}".format(is_moved_from))
#            self.log.debug("is_moved_to: {}".format(is_moved_to))

# if a new directory is created or a directory is renamed inside
# the monitored one, this one has to be monitored as well
            if is_dir and (is_created or is_moved_to):

                # self.log.debug("is_dir and is_created: {} or is_moved_to: "
                #                "{}".format(is_created, is_moved_to))
                # self.log.debug("{} {} {}".format(path, event.name, parts)
                # self.log.debug(event.name)

                dirname = os.path.join(path, event.name)
                self.log.info("Directory event detected: %s, %s", dirname,
                              parts)
                if dirname in self.paths:
                    self.log.debug(
                        "Directory already contained in path list:"
                        " %s", dirname)
                else:
                    watch_descriptor = inotifyx.add_watch(  # noqa E501
                        self.file_descriptor, dirname)
                    self.wd_to_path[watch_descriptor] = dirname
                    self.log.info("Added new directory to watch: %s", dirname)

                    # because inotify misses subdirectory creations if they
                    # happen to fast, the newly created directory has to be
                    # walked to get catch this misses
                    # http://stackoverflow.com/questions/15806488/
                    #        inotify-missing-events
                    for dirpath, directories, files in os.walk(dirname):
                        # Add the found dirs to the list for the inotify-watch
                        for dname in directories:
                            subdir = os.path.join(dirpath, dname)
                            watch_descriptor = inotifyx.add_watch(
                                self.file_descriptor, subdir)
                            self.wd_to_path[watch_descriptor] = subdir
                            self.log.info(
                                "Added new subdirectory to watch: "
                                "%s", subdir)
                        self.log.debug("files: %s", files)

                        for filename in files:
                            # self.log.debug("filename: {}".format(filename))
                            # pylint: disable=no-member
                            if self.mon_regex.match(filename) is None:
                                self.log.debug(
                                    "File does not match monitored "
                                    "regex: %s", filename)
                                self.log.debug("detected events were: %s",
                                               parts)
                                continue

                            event_message = get_event_message(
                                dirpath, filename, self.paths)
                            self.log.debug("event_message: %s", event_message)
                            event_message_list.append(event_message)
#                            self.log.debug("event_message_list: {}"
#                                           .format(event_message_list))
                continue

            # if a directory is renamed the old watch has to be removed
            if is_dir and is_moved_from:

                # self.log.debug("is_dir and is_moved_from")
                # self.log.debug("{} {} {}".format(path, event.name, parts)
                # self.log.debug(event.name)

                dirname = os.path.join(path, event.name)
                found_watch = None
                for watch, watch_path in iteritems(self.wd_to_path):
                    if watch_path == dirname:
                        found_watch = watch
                        break
                inotifyx.rm_watch(self.file_descriptor, found_watch)
                self.log.info("Removed directory from watch: %s", dirname)
                # the IN_MOVE_FROM event always apears before the IN_MOVE_TO
                # (+ additional) events and thus has to be stored till loop
                # is finished
                removed_wd = self.wd_to_path[found_watch]
                # removing the watch out of the dictionary cannot be done
                # inside the loop (would throw error: dictionary changed size
                # during iteration)
                del self.wd_to_path[found_watch]
                continue

            # only files of the configured event type are send
            if (not is_dir and current_mon_event
                    and [path, event.name] not in self.history):

                # only files matching the regex specified with the current
                # event are monitored
                if current_mon_regex.match(event.name) is None:
                    # self.log.debug("File ending not in monitored Suffixes: "
                    #                "%s", event.name)
                    # self.log.debug("detected events were: %s", parts)
                    continue

                event_message = get_event_message(path, event.name, self.paths)
                self.log.debug("event_message %s", event_message)
                event_message_list.append(event_message)

                self.history.append([path, event.name])

        return event_message_list
Beispiel #46
0
if __name__ == '__main__':
	dub = DUB()

	if not dub.build():
		sys.exit(1)

	try:
		dub.start()
		fd = inotifyx.init()
		inotifyx.add_watch(fd, SOURCE_PATH, binding.IN_MODIFY)
		inotifyx.add_watch(fd, TEMPLATE_PATH, binding.IN_MODIFY)

		start_time = datetime.now()
		while True:
			events = inotifyx.get_events(fd)
			end_time = datetime.now()
			isrestart = False
			if (end_time - start_time) > TIME_INTERVAL:
				for event in events:
					if event.name and event.name.split(".")[-1] in EXTENSIONS:
						isrestart = True
			start_time = end_time
			if isrestart:
				dub.restart(True)

	except KeyboardInterrupt:
		dub.stop()
	finally:
		dub.stop()
Beispiel #47
0
def main(charnames):
    pygame.init()
    window_size = (200*len(charnames), 400)
    screen = pygame.display.set_mode(window_size)
    skins, wds = load_entities(charnames)

    anim = 0
    display_hardshape = True
    speed = 1.0
    font = pygame.font.Font(pygame.font.get_default_font(), 12)
    pause = False
    shield = False
    frame = 0
    mouse_click = False
    mouse_xy = [0, 0]

    bottom_center_hardshape = [window_size[0]/2, window_size[1]*2/3]
    last_time = time.time()
    while True:
        # frame limiter
        while time.time() < last_time + 0.05:
            time.sleep(0.05)

        last_time = time.time()

        # get key events
        pygame.event.pump()
        if inotifyx:
            for i, w in enumerate(wds):
                if inotifyx.get_events(fd, 0):
                    print "events"
                    for i in range(3):
                        try:
                            skins = load_entities(charnames)[0]
                            break
                        except:
                            time.sleep(0.5)
                    else:
                        print "doh!"

        if mouse_click and not pygame.mouse.get_pressed()[0]:
            print "click released"
            print """
            <agressiv-point
            coords="%s,%s"
            vector="%s,%s"
            ></agressiv-point>
            """ % (
                (mouse_xy[0] - image_position[0]) % 200,
                mouse_xy[1] - image_position[1],
                2 * (pygame.mouse.get_pos()[0] - mouse_xy[0]),
                2 * (pygame.mouse.get_pos()[1] - mouse_xy[1])
                )

            print """
            <vector
            time="%s"
            vector="%s,%s"
            ></agressiv-point>
            """ % (
                img.time,
                2 * (pygame.mouse.get_pos()[0] - mouse_xy[0]),
                2 * (pygame.mouse.get_pos()[1] - mouse_xy[1])
                )
            mouse_click = False

        if not mouse_click and pygame.mouse.get_pressed()[0]:
            print "click pressed"
            mouse_xy = pygame.mouse.get_pos()
            mouse_click = True

        for event in pygame.event.get(
            [KEYDOWN, KEYUP]
            ):
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    return
                elif event.key == K_F5:
                    entity_skins = load_entities(charnames)[0]
                    print "reloaded"
                elif event.key == K_s:
                    shield = not shield
                elif event.key == K_p:
                    if pause:
                        print "normal mode"
                    else:
                        print "pause: frame mode, chose frame with ← and →"
                    pause = not pause
                elif event.key == K_RIGHT:
                    frame +=1
                elif event.key == K_LEFT:
                    frame -=1
                elif event.key == K_UP:
                    anim +=1
                elif event.key == K_DOWN:
                    anim -=1
                elif event.key == K_SPACE:
                    display_hardshape = not display_hardshape
                elif event.key == K_PLUS or event.key == K_KP_PLUS:
                    speed *= 2
                elif event.key == K_MINUS or event.key == K_KP_MINUS:
                    speed /= 2

        pygame.event.clear( [MOUSEMOTION, MOUSEBUTTONUP, MOUSEBUTTONDOWN] )
        screen.fill(pygame.Color('green'))
        for i, skin in enumerate(skins):
            animation = animations[anim % len(animations)]
            # update screen
            if animation in skin.animations:
                if not pause:
                    try:
                        img = filter(
                                    lambda f : f.time <= (
                                        (time.time()*1000.0*speed) %
                                        skin.animations[animation].duration
                                        ),
                                    skin.animations[animation].frames
                                    )[-1]
                    except ZeroDivisionError:
                        print "error: duration of 0 in", charnames[i], "in animation", animation
                        continue

                    bottom_center_hardshape[0] = (window_size[0]/(len(charnames)
                            * 2)) + (int(time.time() * CONFIG.general.WALKSPEED) % 200 if
                                    "walk" in animation else 0)

                    #if "walk" in animation:
                        #bottom_center_hardshape[0] = int(
                            #time.time() * CONFIG.general.WALKSPEED']
                            #) % window_size[0]
                    #else:
                        #bottom_center_hardshape[0] = window_size[0]/(len(charnames) * 2)
                else:
                    img = skin.animations[animation].frames[frame % len(skin.animations[animation].frames)]
            else:
                img = Placeholder()

            # update the image_position of the up-left corner of image, so that the
            # bottom-middle of the hardhape never moves (as in the game)
            image_position = (
                (bottom_center_hardshape[0] - img.hardshape[0] -
                img.hardshape[2]/2 + 200 * i) % window_size[0],
                bottom_center_hardshape[1] - img.hardshape[1] - img.hardshape[3]
            )

            if display_hardshape:
                screen.fill(
                    pygame.Color('grey'),
                    pygame.Rect((
                        image_position[0],
                        image_position[1],
                        image(img.image)[1][2],
                        image(img.image)[1][3]
                    ))
                    )

                screen.fill(
                    pygame.Color('blue'),
                    pygame.Rect((
                        image_position[0] + img.hardshape[0],
                        image_position[1] + img.hardshape[1],
                        img.hardshape[2],
                        img.hardshape[3]
                    ))
                    )

            screen.blit(image(img.image)[0], image_position)
            screen.blit(
                font.render( charnames[i], True, pygame.Color('red')),
                (10 + 200 * i,10))

            screen.blit(
                font.render(str(anim)+': '+animation, True, pygame.Color('red')),
                (10 + 200 * i,20))

            screen.blit(
                font.render(str(img.time), True, pygame.Color('red')),
                (10 + 200 * i,30))

            if shield:
                pygame.draw.circle(
                    screen,
                    pygame.Color('red'),
                    (
                        image_position[0] + img.hardshape[0] +
                        skin.shield_center[0] - 100 + 200 * i,
                        image_position[1] + img.hardshape[1] + skin.shield_center[1]
                    ),
                    10
                )

                image_shield = image(
                        os.path.sep.join(('..','data','misc','shield.png')),
                        zoom=3
                        )

                screen.blit(
                    image_shield[0],
                    (
                        image_position[0]
                        + skin.shield_center[0]
                        - .5 * image_shield[1][2]
                        ,
                        image_position[1]
                        + skin.shield_center[1]
                        - .5 * image_shield[1][3]
                        )
                    )

            for i in img.agressivpoints:
                pygame.draw.ellipse(
                    screen,
                    pygame.Color('red'),
                    pygame.Rect(
                        image_position[0]+i[0][0]-1, image_position[1]+i[0][1]-1, 2, 2
                        )
                    )
                pygame.draw.line(
                    screen,
                    pygame.Color('red'),
                        (
                        image_position[0]+i[0][0],
                        image_position[1]+i[0][1],
                        ),
                        (
                        image_position[0]+i[0][0]+i[1][0]/2,
                        image_position[1]+i[0][1]+i[1][1]/2,
                        ),
                    1
                )

        if mouse_click:
            pygame.draw.line(
                screen,
                pygame.color.Color("red"),
                mouse_xy,
                pygame.mouse.get_pos(),
                1
                )

        pygame.display.flip()
    for wd in wds:
        inotifyx.rm_watch(wd)
Beispiel #48
0
nom_fichero = "registro_drive"

if not os.path.exists(ruta):
    print("La ruta expecificada en el fichero de configuracion no existe.")
    exit()

#Guarda los datos de GDrive en el fichero local al principio del programa
lista_archivos = miCliente.getListaArchivos()
guardarEnFichero(lista_archivos, nom_fichero)

#Ciclo principal
fd = inotifyx.init()
while True:
    try:
        wd = inotifyx.add_watch(fd, ruta, inotifyx.IN_CREATE)
        events = inotifyx.get_events(fd)
        archivos_a_subir = comprobarCambios(ruta, nom_fichero)
        if archivos_a_subir:
            print("Se subiran estos archivos: ")
            print(archivos_a_subir)
            #Sube cada archivo de la lista a Drive
            for i in archivos_a_subir:
                ruta_archivo = os.path.join(ruta, i)
                miCliente.subirArchivo(i, ruta_archivo, tipoArchivo(i))
                print(
                    str(archivos_a_subir.index(i) + 1) + ") " + i +
                    ": subido.")
            #Registra los cambios en el fichero
            lista_archivos += archivos_a_subir
            guardarEnFichero(lista_archivos, nom_fichero)
            print("Archivos registrados con exito")
Beispiel #49
0
def watch_dhcp_leases(path):
    """
    This is a generator for events that happen to the file at the
    given path. It assumes ISC DHCPD -like behavior; that is, ISC
    dhcpd man page dhcpd.leases(5) promises that the leases file is
    only updated in exactly two ways:

    1. new entries are appended

    2. a new (pruned) lease file is renamed to the monitored filename
       (the old file is first moved out of the way, but that's not
       relevant here)

    So we trigger events on appends and lease file replacement, and
    start monitoring the new file on the latter.

    Example::

        for _ in watch('/var/lib/dhcp/dhcpd.leases'):
            print "Stuff happened!"

    """
    fd = inotifyx.init()
    parent = os.path.dirname(path)
    if parent == '':
        # this happens if path had no slashes in it; mostly when
        # testing manually
        parent = '.'

    try:
        wd_new = inotifyx.add_watch(
            fd,
            parent,
            inotifyx.IN_MOVED_TO | inotifyx.IN_ONLYDIR,
        )

        while True:
            # the only real reason for `path` not to exist here is on
            # first loop (assuming dhcpd behavior); `replaced` only
            # becomes True after a file is renamed to this name, so
            # there's no race there (barring un-dhcpd like behavior
            # like deleting the file)
            wd_journal = inotifyx.add_watch(
                fd,
                path,
                inotifyx.IN_MODIFY,
            )

            # yield once in order to 1) make caller read the existing
            # content of the file and 2) make writing unit tests
            # easier; now we already have an open inotify fd with the
            # right watches
            yield None

            replaced = False
            while not replaced:
                for e in inotifyx.get_events(fd):
                    if e.mask & inotifyx.IN_Q_OVERFLOW:
                        yield e
                        # we could have lost an IN_MOVED_TO event,
                        # do this just in case
                        replaced = True
                    elif e.wd == wd_journal:
                        yield e
                    elif (e.wd == wd_new and e.mask & inotifyx.IN_MOVED_TO
                          and e.name == os.path.basename(path)):
                        # the old watch is implicitly removed as the
                        # file is deleted, no need to clean that up;
                        # not 100% sure if this will leak wds or not
                        replaced = True
    finally:
        os.close(fd)
Beispiel #50
0
 def check (self):
     events = inotifyx.get_events (self.fd, 0)  # 0 => don't block
     for event in events:
         self.process (event)
Beispiel #51
0
r.start()
g.start()
b.start()

# Create a list to hold the objects that respond to file events
evList = []
evList.append(None)
evList += [b1, b2, b3, b4, b5]
evList.append(vol)

# All activity is event driven, watch for file
# system changes
lastch = None
try:
    while True:
        events = inotifyx.get_events(fd, 0.1)
        for event in events:
            ev = str(event)
            ch = ev[0]
            if lastch:
                if ch != lastch:
                    evList[int(lastch)].fileEvent()
                    lastch = ch
            else:
                lastch = ch
        if not events:
            if lastch:
                evList[int(lastch)].fileEvent()
                lastch = None

Beispiel #52
0
 import inotifyx
 dirname, filename = os.path.split(watch_symlink)
 fd = inotifyx.init()
 try:
     # Watch the directory, if it changes then we need to see if the
     # change was in the file we specifically care about. While we
     # have the watch in place we compare the symlink to what was last
     # deployed, if it is different then we don't bother waiting, we
     # just set start_deploy and then loop.
     wd = inotifyx.add_watch(fd, dirname, inotifyx.IN_DELETE)
     if deployed_symlink_value != read_symlink():
         log.info('Symlink changed from "%s" to "%s", deploying.',
                  deployed_symlink_value, read_symlink())
         start_deploy = True
     else:
         events = inotifyx.get_events(fd, 24 * 60 * 60)
         if deployed_symlink_value != read_symlink():
             log.info('Symlink changed from "%s" to "%s", deploying.',
                      deployed_symlink_value, read_symlink())
             start_deploy = True
     inotifyx.rm_watch(fd, wd)
 except IOError as e:
     if e.errno == 2:
         # Errno2 is thrown when the file we are attempting to watch
         # does not exist. If this happens then we fall back to a
         # simple sleep loop. Sleep will be interrupted by a signal.
         time.sleep(1)
     elif e.errno == 4:
         # Errno 4 is used when a syscall gets interrupted. This will
         # most likely be due to a signal so we repeat our loop to check
         # the various conditions.
Beispiel #53
0
    def check (self):
	events = inotifyx.get_events (self.fd)
	for event in events:
	    self.process (event)
Beispiel #54
0
"""
LOG = "/var/log/auth.log"
ifd = inotifyx.init()
log = inotifyx.add_watch(
    ifd, LOG, inotifyx.IN_MODIFY | inotifyx.IN_ATTRIB | inotifyx.IN_DELETE_SELF
    | inotifyx.IN_MOVE_SELF)
f = open(LOG)
sessions = set()
while True:
    line = f.readline()
    if line == '':
        # we've reached end of log, inotify avoids polling for growth
        # suspend if after 60seconds after activity in auth log stopped, there are still 0 ssh sessions
        ls = []
        while len(ls) == 0:
            ls = inotifyx.get_events(ifd, 60)
            # sometimes the log is missing an entry
            # make sure that we only wait for live processes
            for pid in list(sessions):
                if not os.path.exists("/proc/%s" % pid):
                    print "Removing stale pid %s" % pid
                    sessions.remove(pid)
            if len(ls) + len(sessions) == 0:
                syslog.syslog("No more ssh sessions, going to sleep")
                os.system("/home/taras/work/sleepyscripts/suspend.sh")
        for e in ls:
            print e.get_mask_description()
        continue
    m = re.search('sshd\[([0-9]+)\]:.*session (opened|closed)', line)
    if m != None:
        [pid, reason] = m.groups()
Beispiel #55
0
	def on_inotifyx(self, source, condition, fd):
		events = inotifyx.get_events(fd)
		names = set(x.name for x in events if x.name)
		for name in names:
			self.on_file_changed(self.directory.get_child(name))
		return True
Beispiel #56
0
 def check(self):
     for event in inotifyx.get_events(self._fd):
         self.log.debug('%s %r [%s]', event, event.name, event.cookie)
         if event.wd in self._wd:
             self._wd[event.wd].dispatch()
Beispiel #57
0
	def get(self, **params):
		"""
		Return a list of watched paths that where affected by recent
		changes, following a successful poll() return for the controlling
		file descriptor.

		If param "timeout" is greater than 0, the event queue will be read
		multiple times and reads continue until a timeout occurs.

		With a timeout active, if param "limit" is greater than 0,
		event reads will stop when the number of changes exceeds the
		limit.  This guarantees that the time the method will block
		will never be greater than timeout*limit seconds.

		Note that with a timeout active, multiple changes to a
		single path will only be reported once.
	"""
		log = self._getparam('log', self._discard, **params)

		self.last_changes = {}

		timeout = self._getparam('timeout', 0, **params)
		if not timeout or timeout < 0:
			timeout = 0
		limit = self._getparam('limit', None, **params)
		if not limit or limit < 0:
			limit = None

		max_events = limit if limit else 10000
		if self.unprocessed_event:
			log.debug("Will handle unprocessed event")

		if self._mode == WF_KQUEUE:
			evagg = {}
			while True:
				try:
					evlist = self._kq.control(None, max_events, timeout)
				except OSError as e:
					if e.errno == errno.EINTR:
						break
					raise e
				if not evlist:
					break

				log.debug("kq.control() returned %d event%s", len(evlist), ses(len(evlist)))
				for ev in evlist:
					if ev.ident in self.fds_open:
						path = self.fds_open[ev.ident]
						if path in evagg:
							evagg[path].fflags |= ev.fflags
						else:
							evagg[path] = ev
				if limit and len(evagg) >= limit:
					break
			for path, ev in evagg.items():
				if ev.fflags & (select.KQ_NOTE_DELETE | select.KQ_NOTE_RENAME):
					self._disappeared(ev.ident, path, **params)
				self.last_changes[path] = time.time()
				log.debug("Change on '%s'", path)

		elif self._mode == WF_INOTIFYX:
			evagg = {}
			while True:
				try:
					evlist = inotifyx.get_events(self._inx_fd, timeout)
				except IOError as e:
					if e.errno == errno.EINTR:
						break
					raise e
				if not evlist:
					break

				log.debug("inotifyx.get_events() returned %d event%s", len(evlist), ses(len(evlist)))

				for ev in evlist:
					if ev.wd in self.fds_open:
						path = self.fds_open[ev.wd]
						if path in evagg:
							evagg[path].mask |= ev.mask
						else:
							evagg[path] = ev
					elif ev.mask & inotifyx.IN_IGNORED:
						log.debug("skipping IN_IGNORED event on unknown wd %d", ev.wd)
					else:
						log.warning("attempt to handle unknown inotify event wd %d", ev.wd)
				if limit and len(evagg) >= limit:
					break
			for path, ev in evagg.items():
				log.debug("Change on '%s' -- %s", path, ev.get_mask_description())
				if ev.mask & (inotifyx.IN_DELETE_SELF | inotifyx.IN_MOVE_SELF):
					self._disappeared(ev.wd, path, **params)
				elif ev.mask & inotifyx.IN_ATTRIB:
					file_move_del = False
					try:
						s = os.stat(path)
						if s.st_ino != self._inx_inode[path]:
							file_move_del = True
							log.info("'simfs' (used with containers) bug detected -- '%s' moved", path)
					except Exception as e:
						file_move_del = True
						log.info("'simfs' (used with containers) bug detected -- '%s' removed", path)
					if file_move_del:
						self._disappeared(ev.wd, path, **params)
				self.last_changes[path] = time.time()

		elif self._mode == WF_POLLING:
			#  Consume any pending data from the self-pipe.  Read
			#  until EOF.  The fd is already non-blocking so this
			#  terminates on zero read or any error.
			#
			cnt = 0
			while True:
				try:
					data = os.read(self._poll_fd, 1024)
					if data == '':
						break
					cnt += len(data)
				except OSError as e:
					if e.errno != errno.EAGAIN:
						log.warning("Ignoring self-pipe read failure -- %s", str(e))
					break
				except Exception as e:
					log.warning("Ignoring self-pipe read failure -- %s", str(e))
					break
			log.debug("Self-pipe read consumed %d byte%s", cnt, ses(cnt))
			now = time.time()
			for path in self._poll_pending:
				self.last_changes[path] = self._poll_pending[path]
			self._poll_pending = {}
			for fd in list(self._poll_stat):
				path = self.fds_open[fd]
				fstate = self._poll_get_stat(fd, path)
				if fstate is None:
					self.last_changes[path] = now
				elif self._poll_stat[fd] != fstate:
					self._poll_stat[fd] = fstate
					self.last_changes[path] = now
					log.debug("Change on '%s'", path)
		else:
			raise Exception("Unsupported polling mode " + self.get_mode_name())
		paths = list(self.last_changes)
		paths.sort()
		log.debug("Change was to %d path%s", len(paths), ses(len(paths)))
		return paths
def main():
    '''
    The main function
    '''    
    try:
        if len(sys.argv) < 2: 
            print_help()
        else:
            command = sys.argv[1]
            # Start the system
            if command == "start":
                # Set keyboard to use
                steelsquid_utils.execute_system_command_blind(["/usr/bin/termfix", steelsquid_utils.get_parameter("keyboard")], wait_for_finish=True)
                # Redirect sys.stdout to shout
                sys.stdout = Logger()
                # Create the task event dir 
                steelsquid_utils.make_dirs(system_event_dir)
                # Print welcome message
                steelsquid_utils.shout("Steelsquid Kiss OS "+steelsquid_utils.steelsquid_kiss_os_version()[1], to_lcd=False, wait_for_finish=False)
                # Use locking on the I2C bus
                if steelsquid_utils.get_flag("i2c_lock"):
                    steelsquid_i2c.enable_locking(True)
                else:
                    steelsquid_i2c.enable_locking(False)
                # Disable the monitor
                if steelsquid_utils.get_flag("disable_monitor"):
                    steelsquid_utils.execute_system_command_blind(["/opt/vc/bin/tvservice", "-o"], wait_for_finish=False)
                # Listen for shutdown on GPIO
                if steelsquid_utils.has_parameter("power_gpio"):
                    gpio = steelsquid_utils.get_parameter("power_gpio")
                    steelsquid_utils.shout("Listen for clean shutdown on GPIO " + gpio)
                    steelsquid_pi.gpio_click(gpio, poweroff, steelsquid_pi.PULL_DOWN)
                # Load all modules
                pkgpath = os.path.dirname(modules.__file__)
                for name in pkgutil.iter_modules([pkgpath]):
                    if steelsquid_utils.get_flag("module_"+name[1]):
                        steelsquid_utils.shout("Load module: " +name[1], debug=True)    
                        n = name[1]
                        steelsquid_kiss_global.loaded_modules[n]=import_module('modules.'+n)
                # Enable the download manager
                if steelsquid_utils.get_flag("download"):
                    if steelsquid_utils.get_parameter("download_dir") == "":
                        steelsquid_utils.set_parameter("download_dir", "/root")
                    steelsquid_utils.execute_system_command_blind(['steelsquid', 'download-on'], wait_for_finish=False)
                # Enable NRF24L01+ as server
                if steelsquid_utils.get_flag("nrf24_server"):
                    steelsquid_utils.shout("Enable NRF24L01+ server")
                    steelsquid_nrf24.server()
                    thread.start_new_thread(nrf24_server_thread, ())
                # Enable NRF24L01+ as client
                elif steelsquid_utils.get_flag("nrf24_client"):
                    steelsquid_utils.shout("Enable NRF24L01+ client")
                    steelsquid_nrf24.client()
                # Enable NRF24L01+ as master
                if steelsquid_utils.get_flag("nrf24_master"):
                    steelsquid_utils.shout("Enable NRF24L01+ master")
                    steelsquid_nrf24.master(nrf24_callback)
                # Enable NRF24L01+ as slave
                elif steelsquid_utils.get_flag("nrf24_slave"):
                    steelsquid_utils.shout("Enable NRF24L01+ slave")
                    steelsquid_nrf24.slave()
                    thread.start_new_thread(nrf24_slave_thread, ())
                # Enable HM-TRLR-S as server
                if steelsquid_utils.get_flag("hmtrlrs_server"):
                    config_gpio = int(steelsquid_utils.get_parameter("hmtrlrs_config_gpio", "25"))
                    reset_gpio = int(steelsquid_utils.get_parameter("hmtrlrs_reset_gpio", "23"))
                    steelsquid_utils.shout("Enable HM-TRLR-S server")
                    steelsquid_hmtrlrs.setup(config_gpio=config_gpio, reset_gpio=reset_gpio)
                    thread.start_new_thread(hmtrlrs_server_thread, ())
                # Enable HM-TRLR-S as client
                elif steelsquid_utils.get_flag("hmtrlrs_client"):
                    config_gpio = int(steelsquid_utils.get_parameter("hmtrlrs_config_gpio", "25"))
                    reset_gpio = int(steelsquid_utils.get_parameter("hmtrlrs_reset_gpio", "23"))
                    steelsquid_utils.shout("Enable HM-TRLR-S client")
                    steelsquid_hmtrlrs.setup(config_gpio=config_gpio, reset_gpio=reset_gpio)
                    thread.start_new_thread(hmtrlrs_client_thread, ())
                # Start the modules
                for obj in steelsquid_kiss_global.loaded_modules.itervalues():
                    thread.start_new_thread(import_file_dyn, (obj,)) 
                # Enable the webserver
                if steelsquid_utils.get_flag("web"):
                    port = None
                    if steelsquid_utils.has_parameter("web_port"):
                        port = steelsquid_utils.get_parameter("web_port")
                    steelsquid_kiss_global.http_server = steelsquid_kiss_http_server.SteelsquidKissHttpServer(port, steelsquid_utils.STEELSQUID_FOLDER+"/web/", steelsquid_utils.get_flag("web_authentication"), steelsquid_utils.get_flag("web_local"), steelsquid_utils.get_flag("web_authentication"), steelsquid_utils.get_flag("web_https"))
                    for obj in steelsquid_kiss_global.loaded_modules.itervalues():
                        if hasattr(obj, "WEB"):
                            steelsquid_kiss_global.http_server.external_objects.append(getattr(obj, "WEB"))
                    steelsquid_kiss_global.http_server.start_server()
                # Enable the socket server as server
                if steelsquid_utils.get_flag("socket_server"):
                    steelsquid_kiss_global.socket_connection = steelsquid_kiss_socket_connection.SteelsquidKissSocketConnection(True)
                    for obj in steelsquid_kiss_global.loaded_modules.itervalues():
                        if hasattr(obj, "SOCKET"):
                            steelsquid_kiss_global.socket_connection.external_objects.append(getattr(obj, "SOCKET"))
                    steelsquid_kiss_global.socket_connection.start()
                # Enable the socket server as client
                elif steelsquid_utils.has_parameter("socket_client"):
                    steelsquid_kiss_global.socket_connection = steelsquid_kiss_socket_connection.SteelsquidKissSocketConnection(False, steelsquid_utils.get_parameter("socket_client"))
                    for obj in steelsquid_kiss_global.loaded_modules.itervalues():
                        if hasattr(obj, "SOCKET"):
                            steelsquid_kiss_global.socket_connection.external_objects.append(getattr(obj, "SOCKET"))
                    steelsquid_kiss_global.socket_connection.start()
                # Enable the bluetooth
                if steelsquid_utils.get_flag("bluetooth_pairing"):
                    if not steelsquid_utils.has_parameter("bluetooth_pin"):
                        steelsquid_utils.set_parameter("bluetooth_pin", "1234")
                    thread.start_new_thread(bluetooth_agent, ()) 
                fd = inotifyx.init()
                inotifyx.add_watch(fd, system_event_dir, inotifyx.IN_CLOSE_WRITE)
                # Execute a network event so the IP is shown
                execute_task_event("network")
                # Delete old stop eventa and execute others...
                for f in os.listdir(system_event_dir):
                    if f=="stop" or f=="shutdown":
                        steelsquid_utils.deleteFileOrFolder(system_event_dir+"/"+f)
                    else:
                        read_task_event(f)
                # Listen for events
                try:
                    while running:
                        events = inotifyx.get_events(fd)
                        for event in events:
                            read_task_event(event.name)
                except KeyboardInterrupt:
                    pass
                os.close(fd)
                _cleanup()
                # Delete old eventa
                for f in os.listdir(system_event_dir):
                    steelsquid_utils.deleteFileOrFolder(system_event_dir+"/"+f)
            # Broadcast the event
            else:
                if len(sys.argv)>2:
                    broadcast_task_event(command, sys.argv[2:])
                else:
                    broadcast_task_event(command)
    except:
        steelsquid_utils.shout("Fatal error when on boot steelsquid service", is_error=True)
        os._exit(0)