simplified and finalized background service

This commit is contained in:
Nathaniel Kenschaft 2020-06-14 22:54:11 -04:00
parent a0dff03058
commit db50da3d42
4 changed files with 95 additions and 185 deletions

View File

@ -1,56 +1,102 @@
import os
import sys
import signal
import time import time
import event_processor import sys
import os
import pyinotify
class SkoolOSDaemon: class EventHandler(pyinotify.ProcessEvent):
"""Constructor""" _methods = [
def __init__(self, work_dir='/tmp'): "IN_CREATE",
self.work_dir = work_dir "IN_CLOSE_WRITE",
self.start_time = None "IN_DELETE",
self.end_time = None "IN_MOVED_TO",
self.log_file = None "IN_MOVED_FROM",
def __write_pid_file(self): "IN_OPEN",
try: ]
dirName = "/tmp/skooloslogs"
# Create log Directory def process_IN_CREATE(self, event):
os.mkdir(dirName) description = \
except FileExistsError: "Event: Created file\n" \
pass "Event Path: {}\n" \
pid = str(os.getpid()) "Timestamp: {}\n".format(
file_ = open('/tmp/skoolosdaemonpid', 'w') event.pathname,
file_.write(pid) time.strftime("%A, %B %d, %Y %H:%M:%S", time.localtime())
file_.close() )
def readable_time(self, input_time): print(description)
return time.strftime("%A, %B %d, %Y %H:%M:%S", time.localtime(input_time))
def start(self): def process_IN_CLOSE_WRITE(self, event):
self.__write_pid_file() description = \
self.start_time = time.time() "Event: Wrote to a file\n" \
self.log_file = open('/tmp/skooloslogs/' + str(self.start_time), 'w') "Event Path: {}\n" \
self.log_file.write("Start time: \n" + self.readable_time(self.start_time) + "\n\n") "Timestamp: {}\n".format(
sys.stdout = self.log_file event.pathname,
event_processor.watch_dir(self.work_dir) time.strftime("%A, %B %d, %Y %H:%M:%S", time.localtime())
def stop(self): )
event_processor.stop_watching() print(description)
self.end_time = time.time()
self.log_file.write("Stop time: \n" + self.readable_time(self.end_time)) def process_IN_DELETE(self, event):
self.log_file.write("Total work time: " + description = \
time.strftime("%H:%M:%S", time.gmtime(self.end_time - self.start_time))) "Event: Deleted file\n" \
"Event Path: {}\n" \
"Timestamp: {}\n".format(
event.pathname,
time.strftime("%A, %B %d, %Y %H:%M:%S", time.localtime())
)
print(description)
def process_IN_MOVED_TO(self, event):
description = \
"Event: Moved a file in\n" \
"Event Path: {}\n" \
"Timestamp: {}\n".format(
event.pathname,
time.strftime("%A, %B %d, %Y %H:%M:%S", time.localtime())
)
print(description)
def process_IN_MOVED_FROM(self, event):
description = \
"Event: Moved a file out\n" \
"Event Path: {}\n" \
"Timestamp: {}\n".format(
event.pathname,
time.strftime("%A, %B %d, %Y %H:%M:%S", time.localtime())
)
print(description)
def process_IN_OPEN(self, event):
description = \
"Event: Opened file\n" \
"Event Path: {}\n" \
"Timestamp: {}\n".format(
event.pathname,
time.strftime("%A, %B %d, %Y %H:%M:%S", time.localtime())
)
print(description)
logger = None NOTIFIER = None
def Main():
def signal_handler(signum, frame):
logger.stop()
signal.signal(signal.SIGINT, signal_handler)
# signal.signal(signal.SIGTERM, signal_handler)
global logger
logger = SkoolOSDaemon("/tmp")
logger.start()
if __name__ == "__main__": def watch_dir(watched_dir="/tmp", logdir="/tmp/skooloslogs"):
Main() if not os.path.exists(logdir):
os.makedirs(logdir)
logfile = open(
logdir + "skoolos_" + time.strftime("%m%d%Y-%H%M%S", time.localtime()),
'w')
sys.stdout = logfile
print("Start time: " +
time.strftime("%A, %B %d, %Y %H:%M:%S", time.localtime()) + "\n\n")
global NOTIFIER
wm = pyinotify.WatchManager()
mask = pyinotify.IN_CREATE | pyinotify.IN_CLOSE_WRITE | pyinotify.IN_DELETE | \
pyinotify.IN_MOVED_TO | pyinotify.IN_MOVED_FROM | pyinotify.IN_OPEN
NOTIFIER = pyinotify.ThreadedNotifier(wm, EventHandler())
NOTIFIER.start()
wm.add_watch(watched_dir, mask, rec=True)
def stop_watching():
NOTIFIER.stop()
print("End time: " +
time.strftime("%A, %B %d, %Y %H:%M:%S", time.localtime()) + "\n\n")

View File

@ -1,65 +0,0 @@
import time
import pyinotify
def readable_time(input_time):
return time.strftime("%A, %B %d, %Y %H:%M:%S", time.localtime(input_time))
class EventProcessor(pyinotify.ProcessEvent):
_methods = ["IN_OPEN",
"IN_CREATE",
"IN_CLOSE_WRITE",
"IN_DELETE",
"IN_MOVED_TO",
"IN_MOVED_FROM",
]
def __method_format(method):
return {
"IN_OPEN":"Opened a file",
"IN_CREATE":"Created a file",
"IN_CLOSE_WRITE":"Wrote to a file",
"IN_DELETE":"Deleted a file",
"IN_MOVED_TO":"Moved a file or directory in from elsewhere",
"IN_MOVED_FROM":"Moved a file or directory elsewhere",
}.get(method, "Unknown event")
def __process_generator(cls, method):
def _method_name(self, event):
description = "Event description: {}\n" \
"Path name: {}\n" \
"Event Name: {}\n" \
"Timestamp: {}\n".format(__method_format(method),
event.pathname,
event.maskname,
readable_time(time.time())
)
if "IN_DELETE" in description:
description += "WARNING: Unexpected file deletion\n"
if "IN_MOVED_TO" in description:
description += "WARNING: Unexpected file add to work\n"
if "IN_MOVED_FROM" in description:
description += "WARNING: Unexpected file moved out of directory\n"
print(description)
_method_name.__name__ = "process_{}".format(method)
setattr(cls, _method_name.__name__, _method_name)
EVENT_NOTIFIER = None
def watch_dir(dir_to_watch):
global EVENT_NOTIFIER
for method in EventProcessor._methods:
__process_generator(EventProcessor, method)
watch_manager = pyinotify.WatchManager()
EVENT_NOTIFIER = pyinotify.ThreadedNotifier(watch_manager, EventProcessor())
watch_manager.add_watch(dir_to_watch, pyinotify.ALL_EVENTS, rec=True)
EVENT_NOTIFIER.loop()
def stop_watching():
EVENT_NOTIFIER.stop()

View File

@ -1,52 +0,0 @@
import pyinotify
wm = pyinotify.WatchManager()
mask = pyinotify.IN_CREATE | pyinotify.IN_CLOSE_WRITE | pyinotify.IN_DELETE | \
pyinotify.IN_MOVED_TO | pyinotify.IN_MOVED_FROM | pyinotify.IN_OPEN
class EventHandler(pyinotify.ProcessEvent):
_methods = ["IN_CREATE",
"IN_CLOSE_WRITE",
"IN_DELETE",
"IN_MOVED_TO",
"IN_MOVED_FROM",
"IN_OPEN",
]
def __process_generator(self, event):
description = \
"Event: {}\n" \
"Event Path: {}\n" \
"Timestamp: {}\n".format(
method,
event.pathname,
time.strftime("%A, %B %d, %Y %H:%M:%S", time.localtime())
)
if "IN_DELETE" in description:
description += "WARNING: Unexpected file deletion\n"
if "IN_MOVED_TO" in description:
description += "WARNING: Unexpected file add to work\n"
if "IN_MOVED_FROM" in description:
description += "WARNING: Unexpected file moved out of directory\n"
return description
def process_IN_CREATE(self, event):
self.__process_generator(event)
def process_IN_CLOSE_WRITE(self, event):
self.__process_generator(event)
def process_IN_DELETE(self, event):
self.__process_generator(event)
def process_IN_MOVED_TO(self, event):
self.__process_generator(event)
def process_IN_MOVED_FROM(self, event):
self.__process_generator(event)
def process_IN_OPEN(self, event):
self.__process_generator(event)
notifier = pyinotify.ThreadedNotifier(wm, EventHandler())
notifier.start()
wdd = wm.add_watch('/tmp', mask, rec=True)
input("Press any key to continue...")
notifier.stop()

View File

@ -1,19 +0,0 @@
from bgservice import SkoolOSDaemon as sod
import threading
logger = sod()
if __name__ == "__main__":
line=1
print(line)
line+=1
logger.start()
print(line)
line+=1
input("Enter any key when you are done modifyng the /tmp/ directory")
print(line)
line+=1
logger.stop()
print(line)
line+=1