Created
December 10, 2014 17:55
-
-
Save lukecampbell/acbf64c29abdb90782b9 to your computer and use it in GitHub Desktop.
Script to watch for a reset file and then restart a service
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import time | |
import argparse | |
import os | |
import shutil | |
import sh | |
import logging | |
from sh import sudo | |
from watchdog.events import FileSystemEventHandler, DirCreatedEvent | |
from watchdog.observers import Observer | |
log = logging.getLogger("watch") | |
def initialize_logging(level=logging.DEBUG): | |
global log | |
log.setLevel(level) | |
ch = logging.StreamHandler() | |
fh = logging.FileHandler('watch.log') | |
ch.setLevel(level) | |
fh.setLevel(level) | |
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') | |
ch.setFormatter(formatter) | |
fh.setFormatter(formatter) | |
log.addHandler(ch) | |
log.addHandler(fh) | |
class HandleReset(FileSystemEventHandler): | |
def __init__(self, base): | |
self.base = base | |
def on_created(self, event): | |
if isinstance(event, DirCreatedEvent): | |
with sudo: | |
sh.rm("-rf", event.src_path) | |
return | |
if os.path.basename(event.src_path) == 'reset': | |
log.info("Restarting ERDDAP") | |
with sudo: | |
log.info(sh.service("tomcat", "restart")) | |
with sudo: | |
sh.rm(event.src_path) | |
log.info("Removing %s" % event.src_path) | |
def main(base_path): | |
if not os.path.exists(base_path): | |
raise IOError("Directory doesn't exist") | |
handler = HandleReset(base_path) | |
log.info("Watching %s" % base_path) | |
observer = Observer() | |
observer.schedule(handler, path=handler.base, recursive=False) | |
observer.start() | |
try: | |
while True: | |
time.sleep(1) | |
except KeyboardInterrupt: | |
observer.stop() | |
observer.join() | |
if __name__ == '__main__': | |
initialize_logging() | |
parser = argparse.ArgumentParser() | |
parser.add_argument('basedir', help='Base directory to watch') | |
args = parser.parse_args() | |
main(args.basedir) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment