Created
September 9, 2016 12:32
-
-
Save makarchuk/f3dec83670d36eb92e4c487596a23461 to your computer and use it in GitHub Desktop.
This file contains 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 os | |
import sys | |
import multiprocessing | |
import signal | |
import logging | |
class Daemonize(): | |
def __init__(self, pid_file='daemon.pid'): | |
self.obj = None | |
self.pid_file = pid_file | |
self.proc = None | |
def __call__(self, func): | |
def runable(obj, *args, **kwargs): | |
self.obj = obj | |
print(obj) | |
proc = multiprocessing.Process(target=func, args=tuple([obj] + list(args)), kwargs=kwargs) | |
self.proc = proc | |
with self: | |
logging.info("STARTING DAEMON") | |
proc.start() | |
self.wait_for_signals() | |
return runable | |
def __enter__(self): | |
self.create_pid_file() | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
self.remove_pid_file() | |
pass | |
def create_pid_file(self): | |
logging.info("CREATING PID FILE") | |
pid = str(os.getpid()) | |
logging.info("PID IS: {0}".format(pid)) | |
with open(self.pid_file, "w") as f: | |
print(pid) | |
f.write(pid) | |
def remove_pid_file(self): | |
logging.info("REMOVING PID FILE") | |
os.remove(self.pid_file) | |
def wait_for_signals(self): | |
signal.signal(signal.SIGTERM, self.sigterm_handle) | |
signal.signal(signal.SIGINT, self.sigint_handle) | |
while 1: | |
pass | |
def sigterm_handle(self, signum, frame): | |
self.hard_exit() | |
def sigint_handle(self, signum, frame): | |
print("SIGINT!") | |
self.soft_exit() | |
def hard_exit(self): | |
logging.info("HARD EXIT. TERMINATING PROCESS") | |
self.proc.terminate() | |
sys.exit(0) | |
def soft_exit(self): | |
logging.info("SOFT EXIT. WAIT FOR A PROCESS TO END") | |
if self.obj and callable(getattr(self.obj, 'exit', None)): | |
self.obj.exit() | |
self.proc.join() | |
else: | |
self.hard_exit() | |
sys.exit(0) |
This file contains 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
from daemonize import Daemonize | |
from multiprocessing import Event | |
import logging | |
import time | |
logging.basicConfig(level=logging.DEBUG) | |
class Sleeper(): | |
def __init__(self): | |
self.quit = Event() | |
@Daemonize('/home/makarchuk/Workspace/polyp/sleeper.pid') | |
def run(self): | |
while not self.quit.is_set(): | |
time.sleep(2) | |
print("Zzzzzz....") | |
print("Graceful death") | |
def exit(self): | |
print("QUITING") | |
self.quit.set() | |
if __name__=="__main__": | |
Sleeper().run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment