shakaran

Untitled

Jun 17th, 2012
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.27 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8; tab-width: 4; mode: python -*-
  3. # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: t -*-
  4. # vi: set ft=python sts=4 ts=4 sw=4 noet
  5. #
  6. # This file is part of FreeStation.
  7. #
  8. # FreeStation is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation; either version 3 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # FreeStation is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with Fail2Ban; if not, write to the Free Software
  20. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  21.  
  22. # Author: Ángel Guzmán Maeso
  23. #
  24. # $Revision$
  25.  
  26. __author__ = 'Ángel Guzmán Maeso'
  27. __version__ = '$Revision$'
  28. __date__ = '$Date$'
  29. __copyright__ = 'Copyright (c) 2012 Ángel Guzmán Maeso'
  30. __license__ = 'GPL'
  31.  
  32. from time import time, sleep
  33. from os import getppid, getpid, kill, setpgrp, killpg
  34. from signal import signal, SIGTERM, SIGKILL
  35. import sys
  36. from traceback import print_exc
  37. from logger import Logger
  38. LOG = Logger('Watchdog').get()
  39.  
  40. from freestationapp2 import FreeStationApp2
  41.  
  42. class Watchdog(object):
  43.  
  44. MONITOR_TIME = 1
  45. PROCESS_MONITORED_NAME = 'FreeStation'
  46.  
  47. def __init__(self):
  48. '''
  49. Init the watchdog
  50. '''
  51.  
  52. LOG.debug('Parent PID: {0}'.format(getppid()))
  53. LOG.debug('Watchdog PID: {0}'.format(getpid()))
  54.  
  55. signal(SIGTERM, self.handler)
  56.  
  57. self.play = True
  58.  
  59. def handler(self, signal, object): #@ReservedAssignment
  60. '''
  61. Catch SIGTERM signal and destroy the app if alive
  62. '''
  63. if hasattr(self, 'p'):
  64. if self.p and self.p.is_alive():
  65. self.p.on_destroy(None, None)
  66.  
  67. LOG.debug('Exiting by interrupt. Bye')
  68. # This shows: Exception SystemExit: 0 in <module 'threading' from '/usr/lib/python2.7/threading.pyc'> ignored
  69. # But it is only closing with nice exit. SystemExit when it is not handled, the Python interpreter exits
  70. sys.exit(0)
  71.  
  72. def launch(self, alive_time = None, enable_gui = True):
  73. '''
  74. Launch the threaded application
  75. @param alive_time msec for live app, normally used by test. Default None for ignore
  76. @param enable_gui launch the program loading the GUI if True
  77. '''
  78. if hasattr(self, 'p'):
  79. self.p.destroy()
  80. del self.p
  81.  
  82. # Cleanup any state set by the FreeStationApp.
  83. #
  84. import signal
  85. if signal.__dict__.has_key('SIGHUP'):
  86. signal.signal(signal.SIGHUP, signal.SIG_DFL)
  87. if signal.__dict__.has_key('SIGBREAK'):
  88. signal.signal(signal.SIGBREAK, signal.SIG_DFL) #@UndefinedVariable
  89. signal.signal(signal.SIGINT, signal.SIG_DFL)
  90. signal.signal(signal.SIGTERM, signal.SIG_DFL)
  91.  
  92. import os
  93. if os.path.exists('webkit.lock'):
  94. os.remove('webkit.lock')
  95. self.p = None
  96. self.p = FreeStationApp2(alive_time, enable_gui)
  97. self.p.setName(self.PROCESS_MONITORED_NAME + '-' + str(time()))
  98. self.p.start()
  99.  
  100.  
  101. def monitor(self, alive_time = None, enable_gui = True, executions = None):
  102. '''
  103. Check if the app is alive, and restart if the app dead
  104. '''
  105.  
  106. while(self.play):
  107. LOG.debug('Sleeping {0} seconds'.format(str(self.MONITOR_TIME)))
  108. sleep(self.MONITOR_TIME)
  109.  
  110. if not hasattr(self, 'p'):
  111. self.launch(alive_time, enable_gui)
  112.  
  113. LOG.debug('Checking if alive...')
  114.  
  115. if(self.p.is_alive() == False):
  116. self.p.on_destroy(None, None)
  117.  
  118. LOG.error('Restarting process ...')
  119. self.launch(alive_time, enable_gui)
  120.  
  121. if executions:
  122. executions -= 1
  123. if executions <= 0:
  124. self.exit()
  125. else:
  126. LOG.debug('Process still running: {0}'.format(self.p.getName()))
  127. self.p.join(timeout=1.0)
  128.  
  129. def stop(self):
  130. self.play = False
  131.  
  132. def exit(self): #@ReservedAssignment
  133. '''
  134. Send a SIGTERM himself
  135. '''
  136. kill(getpid(), SIGTERM)
  137.  
  138. if __name__ == '__main__':
  139. setpgrp() # create new process group, become its leader
  140. try:
  141. watchdog = Watchdog().monitor(None, True, None)
  142. except KeyboardInterrupt:
  143. LOG.debug('Exiting by keyboard. Bye')
  144. sys.exit(0)
  145. except Exception, e:
  146. sys.stderr.write('Fatal error: {0}\n'.format(str(e)))
  147. LOG.exception(print_exc())
  148. sys.exit(1)
  149. finally: # Ensure kill all the children and avoid zombies
  150. LOG.debug('Ensure killing children zombie process')
  151. killpg(0, SIGKILL)
Advertisement
Add Comment
Please, Sign In to add comment