You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
#!/usr/bin/env python3# Copyright (c) 2010 Greggory Hernandez# Permission is hereby granted, free of charge, to any person obtaining a copy# of this software and associated documentation files (the "Software"), to deal# in the Software without restriction, including without limitation the rights# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell# copies of the Software, and to permit persons to whom the Software is# furnished to do so, subject to the following conditions:# The above copyright notice and this permission notice shall be included in# all copies or substantial portions of the Software.# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN# THE SOFTWARE.### BEGIN INIT INFO# Provides: watcher.py# Required-Start: $remote_fs $syslog# Required-Stop: $remote_fs $syslog# Default-Start: 2 3 4 5# Default-Stop: 0 1 6# Short-Description: Monitor directories for file changes# Description: Monitor directories specified in /etc/watcher.ini for# changes using the Kernel's inotify mechanism and run# jobs when files or directories change### END INIT INFOimportsys, os, time, atexitfromsignalimportSIGTERMimportpyinotifyimportsys, osimportdatetimeimportsubprocessfromtypesimport*fromstringimportTemplateimportconfigparserimportargparseclassDaemon:
""" A generic daemon class Usage: subclass the Daemon class and override the run method """def__init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
self.stdin=stdinself.stdout=stdoutself.stderr=stderrself.pidfile=pidfiledefdaemonize(self):
""" do the UNIX double-fork magic, see Stevens' "Advanced Programming in the UNIX Environment" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 """try:
pid=os.fork()
ifpid>0:
#exit first parentsys.exit(0)
exceptOSErrorase:
sys.stderr.write("fork #1 failed: %d (%s)\n"% (e.errno, e.strerror))
sys.exit(1)
# decouple from parent environmentos.chdir("/")
os.setsid()
os.umask(0)
# do second forktry:
pid=os.fork()
ifpid>0:
# exit from second parentsys.exit(0)
exceptOSErrorase:
sys.stderr.write("fork #2 failed: %d (%s)\n"% (e.errno, e.strerror))
sys.exit(1)
#redirect standard file descriptorssys.stdout.flush()
sys.stderr.flush()
si=open(self.stdin, 'r')
so=open(self.stdout, 'wb')
se=open(self.stderr, 'wb', 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
#write pid fileatexit.register(self.delpid)
pid=str(os.getpid())
open(self.pidfile, 'w+').write("%s\n"%pid)
defdelpid(self):
os.remove(self.pidfile)
defstart(self):
""" Start the daemon """# Check for a pidfile to see if the daemon already runstry:
pf=open(self.pidfile, 'r')
pid=int(pf.read().strip())
pf.close()
exceptIOError:
pid=Noneifpid:
message="pidfile %s already exists. Daemon already running?\n"sys.stderr.write(message%self.pidfile)
sys.exit(1)
# Start the Daemonself.daemonize()
self.run()
defstop(self):
""" Stop the daemon """# get the pid from the pidfiletry:
pf=open(self.pidfile, 'r')
pid=int(pf.read().strip())
pf.close()
exceptIOError:
pid=Noneifnotpid:
message="pidfile %s does not exist. Daemon not running?\n"sys.stderr.write(message%self.pidfile)
return# not an error in a restart# Try killing the daemon processtry:
while1:
os.kill(pid, SIGTERM)
time.sleep(0.1)
exceptOSErroraserr:
err=str(err)
iferr.find("No such process") >0:
ifos.path.exists(self.pidfile):
os.remove(self.pidfile)
else:
print(str(err))
sys.exit(1)
defrestart(self):
""" Restart the daemon """self.stop()
self.start()
defstatus(self):
try:
pf=open(self.pidfile, 'r')
pid=int(pf.read().strip())
pf.close()
exceptIOError:
pid=Noneifpid:
print("service running")
sys.exit(0)
ifnotpid:
print("service not running")
sys.exit(3)
defrun(self):
""" You should override this method when you subclass Daemon. It will be called after the process has been daemonized by start() or restart(). """classEventHandler(pyinotify.ProcessEvent):
def__init__(self, command):
pyinotify.ProcessEvent.__init__(self)
self.command=command# from http://stackoverflow.com/questions/35817/how-to-escape-os-system-calls-in-pythondefshellquote(self,s):
s=str(s)
return"'"+s.replace("'", "'\\''") +"'"defrunCommand(self, event):
t=Template(self.command)
command=t.substitute(watched=self.shellquote(event.path),
filename=self.shellquote(event.pathname),
tflags=self.shellquote(event.maskname),
nflags=self.shellquote(event.mask),
cookie=self.shellquote(event.cookieifhasattr(event, "cookie") else0))
try:
os.system(command)
exceptOSErroraserr:
print("Failed to run command '%s' %s"% (command, str(err)))
defprocess_IN_ACCESS(self, event):
print("Access: ", event.pathname)
self.runCommand(event)
defprocess_IN_ATTRIB(self, event):
print("Attrib: ", event.pathname)
self.runCommand(event)
defprocess_IN_CLOSE_WRITE(self, event):
print("Close write: ", event.pathname)
self.runCommand(event)
defprocess_IN_CLOSE_NOWRITE(self, event):
print("Close nowrite: ", event.pathname)
self.runCommand(event)
defprocess_IN_CREATE(self, event):
print("Creating: ", event.pathname)
self.runCommand(event)
defprocess_IN_DELETE(self, event):
print("Deleteing: ", event.pathname)
self.runCommand(event)
defprocess_IN_MODIFY(self, event):
print("Modify: ", event.pathname)
self.runCommand(event)
defprocess_IN_MOVE_SELF(self, event):
print("Move self: ", event.pathname)
self.runCommand(event)
defprocess_IN_MOVED_FROM(self, event):
print("Moved from: ", event.pathname)
self.runCommand(event)
defprocess_IN_MOVED_TO(self, event):
print("Moved to: ", event.pathname)
self.runCommand(event)
defprocess_IN_OPEN(self, event):
print("Opened: ", event.pathname)
self.runCommand(event)
classWatcherDaemon(Daemon):
def__init__(self, config):
self.stdin='/dev/null'self.stdout=config.get('DEFAULT','logfile')
self.stderr=config.get('DEFAULT','logfile')
self.pidfile=config.get('DEFAULT','pidfile')
self.config=configdefrun(self):
log('Daemon started')
wdds= []
notifiers= []
# read jobs from config fileforsectioninself.config.sections():
log(section+": "+self.config.get(section,'watch'))
# get the basic config infomask=self._parseMask(self.config.get(section,'events').split(','))
folder=self.config.get(section,'watch')
recursive=self.config.getboolean(section,'recursive')
autoadd=self.config.getboolean(section,'autoadd')
excluded=self.config.get(section,'excluded')
command=self.config.get(section,'command')
# Exclude directories right away if 'excluded' regexp is set# Example https://github.com/seb-m/pyinotify/blob/master/python2/examples/exclude.pyifexcluded.strip() =='': # if 'excluded' is empty or whitespaces onlyexcl=Noneelse:
excl=pyinotify.ExcludeFilter(excluded.split(','))
wm=pyinotify.WatchManager()
handler=EventHandler(command)
wdds.append(wm.add_watch(folder, mask, rec=recursive, auto_add=autoadd, exclude_filter=excl))
# BUT we need a new ThreadNotifier so I can specify a different# EventHandler instance for each job# this means that each job has its own thread as well (I think)notifiers.append(pyinotify.ThreadedNotifier(wm, handler))
# now we need to start ALL the notifiers.# TODO: load test this ... is having a thread for each a problem?fornotifierinnotifiers:
notifier.start()
def_parseMask(self, masks):
ret=False;
formaskinmasks:
mask=mask.strip()
if'access'==mask:
ret=self._addMask(pyinotify.IN_ACCESS, ret)
elif'attribute_change'==mask:
ret=self._addMask(pyinotify.IN_ATTRIB, ret)
elif'write_close'==mask:
ret=self._addMask(pyinotify.IN_CLOSE_WRITE, ret)
elif'nowrite_close'==mask:
ret=self._addMask(pyinotify.IN_CLOSE_NOWRITE, ret)
elif'create'==mask:
ret=self._addMask(pyinotify.IN_CREATE, ret)
elif'delete'==mask:
ret=self._addMask(pyinotify.IN_DELETE, ret)
elif'self_delete'==mask:
ret=self._addMask(pyinotify.IN_DELETE_SELF, ret)
elif'modify'==mask:
ret=self._addMask(pyinotify.IN_MODIFY, ret)
elif'self_move'==mask:
ret=self._addMask(pyinotify.IN_MOVE_SELF, ret)
elif'move_from'==mask:
ret=self._addMask(pyinotify.IN_MOVED_FROM, ret)
elif'move_to'==mask:
ret=self._addMask(pyinotify.IN_MOVED_TO, ret)
elif'open'==mask:
ret=self._addMask(pyinotify.IN_OPEN, ret)
elif'all'==mask:
m=pyinotify.IN_ACCESS|pyinotify.IN_ATTRIB|pyinotify.IN_CLOSE_WRITE| \
pyinotify.IN_CLOSE_NOWRITE|pyinotify.IN_CREATE|pyinotify.IN_DELETE| \
pyinotify.IN_DELETE_SELF|pyinotify.IN_MODIFY|pyinotify.IN_MOVE_SELF| \
pyinotify.IN_MOVED_FROM|pyinotify.IN_MOVED_TO|pyinotify.IN_OPENret=self._addMask(m, ret)
elif'move'==mask:
ret=self._addMask(pyinotify.IN_MOVED_FROM|pyinotify.IN_MOVED_TO, ret)
elif'close'==mask:
ret=self._addMask(pyinotify.IN_CLOSE_WRITE|pyinotify.IN_CLOSE_NOWRITE, ret)
returnretdef_addMask(self, new_option, current_options):
ifnotcurrent_options:
returnnew_optionelse:
returncurrent_options|new_optiondeflog(msg):
sys.stdout.write("%s %s\n"% ( str(datetime.datetime.now()), msg ))
if__name__=="__main__":
# Parse commandline argumentsparser=argparse.ArgumentParser(
description='A daemon to monitor changes within specified directories and run commands on these changes.',
)
parser.add_argument('-c','--config',
action='store',
help='Path to the config file (default: %(default)s)')
parser.add_argument('command',
action='store',
choices=['start','stop','restart','status','debug'],
help='What to do. Use debug to start in the foreground')
args=parser.parse_args()
# Parse the config fileconfig=configparser.ConfigParser()
if(args.config):
confok=config.read(args.config)
else:
confok=config.read(['/etc/watcher.ini', os.path.expanduser('~/.watcher.ini')]);
if(notconfok):
sys.stderr.write("Failed to read config file. Try -c parameter\n")
sys.exit(4);
# Initialize the daemondaemon=WatcherDaemon(config)
# Execute the commandif'start'==args.command:
daemon.start()
elif'stop'==args.command:
daemon.stop()
elif'restart'==args.command:
daemon.restart()
elif'status'==args.command:
daemon.status()
elif'debug'==args.command:
daemon.run()
else:
print("Unkown Command")
sys.exit(2)
sys.exit(0)
The text was updated successfully, but these errors were encountered:
jrubenc
changed the title
Python3 version
Working Python3 version :)
Nov 9, 2023
The text was updated successfully, but these errors were encountered: