Advertisement
Guest User

Untitled

a guest
Jan 21st, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.44 KB | None | 0 0
  1. #!/usr/local/bin/python3
  2. import sys
  3. import time
  4. import logging
  5. from daemon import runner
  6. #
  7. # An example daemon main logic application class.
  8. # Just keep writing timestamps to a log file periodically.
  9. # Extended to add an additional 'action' (garbage, which insert garbage into log file) beyond the standard (start, stop, restart)
  10. #
  11. class App:
  12. def __init__(self):
  13. # python-daemon DaemonRunner requires the below.
  14. self.stdin_path = '/dev/null'
  15. self.stdout_path = '/dev/null'
  16. self.stderr_path = '/dev/null'
  17. # For debug, you can use '/dev/tty' for stdout/stderr instead.
  18. #self.stdout_path = '/dev/tty'
  19. #self.stderr_path = '/dev/tty'
  20. self.pidfile_path = '/tmp/foo.pid'
  21. self.pidfile_timeout = 5
  22. # The above 5 attributes are mandatory.
  23. #
  24. # The below are this App specific. (conf file is not implemented now)
  25. self.log_file = '/tmp/foobar.log'
  26. self.conf_file = '/etc/pdaemon.conf'
  27. self.foreground = False
  28.  
  29. def garbage(self):
  30. logging.basicConfig(level=logging.DEBUG,
  31. format='%(asctime)s %(levelname)s %(message)s',
  32. filename=self.log_file,
  33. filemode='a')
  34.  
  35. logging.info('avkldjfql4rj43l1kj414lfkjalvkjalkj34132l4k123j413')
  36.  
  37. def run(self):
  38. # Here is your main logic.
  39. # Initializing code.
  40. if not self.foreground:
  41. logging.basicConfig(level=logging.DEBUG,
  42. format='%(asctime)s %(levelname)s %(message)s',
  43. filename=self.log_file,
  44. filemode='a')
  45. while True:
  46. # the main loop code.
  47. try:
  48. str = time.asctime(time.localtime(time.time()))
  49. if self.foreground:
  50. print (str)
  51. else:
  52. logging.info('DEBUG: %s' % str)
  53.  
  54. time.sleep(1)
  55. except:
  56. logging.info(sys.exc_info())
  57. logging.info('Terminating.')
  58. sys.exit(1)
  59. #
  60. # An example extension of runner.DaemonRunner class of python-daemon.
  61. # Improvement points are:
  62. # - Use of argparse, for better readability
  63. # - extended to show how we add additional 'actions' so we can prod the deamon whilst it's still running
  64. class MyDaemonRunner(runner.DaemonRunner):
  65.  
  66.  
  67. def __init__(self, app):
  68. # workaround... :(
  69. self.app_save = app
  70.  
  71. self.detach_process = True
  72.  
  73. # this is where we define the 'action' to be function 'self._garbage'
  74. self.action_funcs['garbage'] = self._garbage
  75. runner.DaemonRunner.__init__(self, app)
  76.  
  77. def _garbage(self, app):
  78. # for some reason, I needed this to accept two arguments, but we don't need to pass any.
  79. # run the function 'garbage' inside the app.
  80. self.app_save.garbage()
  81.  
  82. def parse_args(self):
  83. import argparse
  84.  
  85. parser = argparse.ArgumentParser(description='Example arguments.')
  86. parser.add_argument("-s", "--start", help="Start process", action='store_true')
  87. parser.add_argument("-g", "--garbage", help="Insert garbage into logfile", action='store_true')
  88. parser.add_argument("-k", "--stop", help="Stop process", action='store_true')
  89. parser.add_argument("-r", "--restart", help="Restart process", action='store_true')
  90. parser.add_argument("-l", "--log_file", dest="filename", help="write log to FILE", metavar="FILE")
  91. parser.add_argument("-p", "--pid_file", dest="pidname", help="write pid to FILE", metavar="FILE")
  92. parser.add_argument("-f", "--foreground", help="Run in the foreground", action='store_true')
  93. parser.add_argument("-v", "--verbose", help="Verbose", action='store_true')
  94.  
  95.  
  96. args = parser.parse_args()
  97.  
  98. if args.start:
  99. self.action = 'start'
  100. #print("Starting ", parser.prog, "...")
  101. elif args.stop:
  102. self.action = 'stop'
  103. elif args.restart:
  104. self.action = 'restart'
  105. elif args.foreground:
  106. self.detach_process = False
  107. self.app_save.stdout_path = '/dev/tty'
  108. self.app_save.stderr_path = '/dev/tty'
  109. self.app_save.foreground = True
  110. elif args.garbage:
  111. self.action = 'garbage'
  112. else:
  113. print (parser.print_help())
  114. #print ("Too few arguments")
  115. parser.exit()
  116. sys.exit()
  117.  
  118. # optionals
  119.  
  120. if args.filename:
  121. self.app_save.log_file = args.filename
  122.  
  123. if args.pidname:
  124. self.app_save.pidfile_path = args.pidname
  125.  
  126. if args.verbose:
  127. self.verbose = True
  128. #
  129. # FYI: The original parse_args() in runner.DaemonRunner class.
  130. #
  131. def original_parse_args(self, argv=None):
  132. """ Parse command-line arguments.
  133. """
  134. if argv is None:
  135. argv = sys.argv
  136.  
  137. min_args = 2
  138. if len(argv) < min_args:
  139. self._usage_exit(argv)
  140.  
  141. self.action = argv[1]
  142. if self.action not in self.action_funcs:
  143. self._usage_exit(argv)
  144. #
  145. #
  146. #
  147. if __name__ == '__main__':
  148. app = App()
  149. daemon_runner = MyDaemonRunner(app)
  150. if not app.foreground:
  151. daemon_runner.do_action()
  152. else:
  153. app.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement