Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/local/bin/python3
- import sys
- import time
- import logging
- from daemon import runner
- #
- # An example daemon main logic application class.
- # Just keep writing timestamps to a log file periodically.
- # Extended to add an additional 'action' (garbage, which insert garbage into log file) beyond the standard (start, stop, restart)
- #
- class App:
- def __init__(self):
- # python-daemon DaemonRunner requires the below.
- self.stdin_path = '/dev/null'
- self.stdout_path = '/dev/null'
- self.stderr_path = '/dev/null'
- # For debug, you can use '/dev/tty' for stdout/stderr instead.
- #self.stdout_path = '/dev/tty'
- #self.stderr_path = '/dev/tty'
- self.pidfile_path = '/tmp/foo.pid'
- self.pidfile_timeout = 5
- # The above 5 attributes are mandatory.
- #
- # The below are this App specific. (conf file is not implemented now)
- self.log_file = '/tmp/foobar.log'
- self.conf_file = '/etc/pdaemon.conf'
- self.foreground = False
- def garbage(self):
- logging.basicConfig(level=logging.DEBUG,
- format='%(asctime)s %(levelname)s %(message)s',
- filename=self.log_file,
- filemode='a')
- logging.info('avkldjfql4rj43l1kj414lfkjalvkjalkj34132l4k123j413')
- def run(self):
- # Here is your main logic.
- # Initializing code.
- if not self.foreground:
- logging.basicConfig(level=logging.DEBUG,
- format='%(asctime)s %(levelname)s %(message)s',
- filename=self.log_file,
- filemode='a')
- while True:
- # the main loop code.
- try:
- str = time.asctime(time.localtime(time.time()))
- if self.foreground:
- print (str)
- else:
- logging.info('DEBUG: %s' % str)
- time.sleep(1)
- except:
- logging.info(sys.exc_info())
- logging.info('Terminating.')
- sys.exit(1)
- #
- # An example extension of runner.DaemonRunner class of python-daemon.
- # Improvement points are:
- # - Use of argparse, for better readability
- # - extended to show how we add additional 'actions' so we can prod the deamon whilst it's still running
- class MyDaemonRunner(runner.DaemonRunner):
- def __init__(self, app):
- # workaround... :(
- self.app_save = app
- self.detach_process = True
- # this is where we define the 'action' to be function 'self._garbage'
- self.action_funcs['garbage'] = self._garbage
- runner.DaemonRunner.__init__(self, app)
- def _garbage(self, app):
- # for some reason, I needed this to accept two arguments, but we don't need to pass any.
- # run the function 'garbage' inside the app.
- self.app_save.garbage()
- def parse_args(self):
- import argparse
- parser = argparse.ArgumentParser(description='Example arguments.')
- parser.add_argument("-s", "--start", help="Start process", action='store_true')
- parser.add_argument("-g", "--garbage", help="Insert garbage into logfile", action='store_true')
- parser.add_argument("-k", "--stop", help="Stop process", action='store_true')
- parser.add_argument("-r", "--restart", help="Restart process", action='store_true')
- parser.add_argument("-l", "--log_file", dest="filename", help="write log to FILE", metavar="FILE")
- parser.add_argument("-p", "--pid_file", dest="pidname", help="write pid to FILE", metavar="FILE")
- parser.add_argument("-f", "--foreground", help="Run in the foreground", action='store_true')
- parser.add_argument("-v", "--verbose", help="Verbose", action='store_true')
- args = parser.parse_args()
- if args.start:
- self.action = 'start'
- #print("Starting ", parser.prog, "...")
- elif args.stop:
- self.action = 'stop'
- elif args.restart:
- self.action = 'restart'
- elif args.foreground:
- self.detach_process = False
- self.app_save.stdout_path = '/dev/tty'
- self.app_save.stderr_path = '/dev/tty'
- self.app_save.foreground = True
- elif args.garbage:
- self.action = 'garbage'
- else:
- print (parser.print_help())
- #print ("Too few arguments")
- parser.exit()
- sys.exit()
- # optionals
- if args.filename:
- self.app_save.log_file = args.filename
- if args.pidname:
- self.app_save.pidfile_path = args.pidname
- if args.verbose:
- self.verbose = True
- #
- # FYI: The original parse_args() in runner.DaemonRunner class.
- #
- def original_parse_args(self, argv=None):
- """ Parse command-line arguments.
- """
- if argv is None:
- argv = sys.argv
- min_args = 2
- if len(argv) < min_args:
- self._usage_exit(argv)
- self.action = argv[1]
- if self.action not in self.action_funcs:
- self._usage_exit(argv)
- #
- #
- #
- if __name__ == '__main__':
- app = App()
- daemon_runner = MyDaemonRunner(app)
- if not app.foreground:
- daemon_runner.do_action()
- else:
- app.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement