background service polish

This commit is contained in:
Nathaniel Kenschaft 2020-06-13 22:10:28 -04:00
parent fd31dd3b0e
commit a032cf12ad
2 changed files with 41 additions and 15 deletions

View File

@ -13,6 +13,12 @@ class SkoolOSDaemon:
self.end_time = None
self.log_file = None
def __write_pid_file(self):
try:
dirName = "/tmp/skooloslogs"
# Create log Directory
os.mkdir(dirName)
except FileExistsError:
pass
pid = str(os.getpid())
file_ = open('/tmp/skoolosdaemonpid', 'w')
file_.write(pid)
@ -20,23 +26,29 @@ class SkoolOSDaemon:
def readable_time(self, input_time):
return time.strftime("%A, %B %d, %Y %H:%M:%S", time.localtime(input_time))
def start(self):
__write_pid_file()
self.__write_pid_file()
self.start_time = time.time()
self.log_file = open('/tmp/skooloslogs/' + str(self.start_time), 'w')
self.log_file.write("Started work: \n" + self.readable_time(self.start_time))
self.log_file.write("Start time: " + self.readable_time(self.start_time) + "\n")
sys.stdout = self.log_file
event_processor.watch_dir(self.work_dir)
def stop(self):
event_processor.stop_watching()
self.end_time = time.time()
self.log_file.write("Stop time: \n" + self.readable_time(self.end_time))
self.log_file.write("Total work time: " +
time.strftime("%H:%M:%S", time.gmtime(self.end_time - self.start_time)))
logger = None
def Main():
def signal_handler(signum, frame):
logger.stop()
signal.signal(signal.SIGINT, signal_handler)
global logger
logger = SkoolOSDaemon("/tmp")
logger.start()

View File

@ -24,28 +24,42 @@ def __method_format(method):
"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",
}[method]
}.get(method, "Unknown event")
def __process_generator(cls, method):
def _method_name(self, event):
print("Event description: {}\n"
"Path name: {}\n"
"Event Name: {}\n"
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.Notifier(watch_manager, EventProcessor())
EVENT_NOTIFIER = pyinotify.Notifier(watch_manager, EventProcessor())
watch_manager.add_watch(dir_to_watch, pyinotify.ALL_EVENTS)
event_notifier.loop()
EVENT_NOTIFIER.loop()#daemonize=True)
def stop_watching():
EVENT_NOTIFIER.stop()