import os import sys import logging, logging.handlers def checkpid(pid): try: os.kill(pid, 0) return True except OSError, info: if info.errno == 3: return False else: return True class Daemon: name = 'basedaemon' loggingsubject = 'BaseDaemon logging' logdir = '/home/lampotila/logs' def __init__(self): self.formatter = logging.Formatter("---------------------\n%(asctime)s %(process)s %(pathname)s:%(lineno)d:\n%(message)s\n", "%Y-%m-%dT%H:%M:%S") self.emailhandler = logging.handlers.SMTPHandler('mail.inet.fi', 'lampotila@warri1.dyndns.org', ['jpa@lm.mail.kapsi.fi'], self.loggingsubject) self.emailhandler.setLevel(logging.ERROR) self.emailhandler.setFormatter(self.formatter) logfile = os.path.join(self.logdir, self.name + ".log") self.filehandler = logging.handlers.RotatingFileHandler(logfile, 'a', 100 * 1024, backupCount = 3) self.filehandler.setLevel(logging.INFO) self.filehandler.setFormatter(self.formatter) self.logger = logging.getLogger() self.logger.addHandler(self.emailhandler) self.logger.addHandler(self.filehandler) self.logger.setLevel(logging.INFO) self.pidfile = os.path.join(self.logdir, self.name + ".pid") def run(self): pass def start(self): if os.path.exists(self.pidfile): oldpid = int(open(self.pidfile, 'r').read()) if checkpid(oldpid): print "Already running under pid %d!" % oldpid return if len(sys.argv) > 1 and sys.argv[1] == '-d': self.screenhandler = logging.handlers.StreamHandler() self.screenhandler.setLevel(logging.DEBUG) self.screenhandler.setFormatter(self.formatter) self.logger.addHandler(self.screenhandler) self.run() return if os.fork() > 0: sys.exit(0) os.chdir('/') os.setsid() os.umask(0) if os.fork() > 0: sys.exit(0) self.logger.info('Started, PID: %d' % os.getpid()) open(self.pidfile, "w").write("%d\n" % os.getpid()) try: self.run() except: self.logger.critical("Main thread crashed", exc_info = True) self.logger.info("Server shut down")