heartbeat.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #!/usr/bin/python
  2. import os, sys
  3. import urllib2
  4. from time import gmtime, strftime, time
  5. try:
  6. from argparse import OptionParser
  7. except ImportError:
  8. from optparse import OptionParser
  9. def log_entry(logfile, response=None):
  10. if response and response.getcode() == 200:
  11. if response.time > 1:
  12. stopwatch = '%ss' % round(response.time, 3)
  13. else:
  14. stopwatch = '%sms' % int(response.time * 1000)
  15. msg = 'OK! HTTP 200 after %s' % stopwatch
  16. else:
  17. msg = 'FAIL!'
  18. print msg
  19. if logfile:
  20. lf = open(logfile, 'a+')
  21. lf.write('%s: ' % strftime("%a, %d %b %Y %X GMT", gmtime()))
  22. lf.write('%s\n' % msg)
  23. lf.close()
  24. def heartbeat():
  25. # Change chdir to current file loation, then add it to pythonpath
  26. sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
  27. os.chdir(os.path.dirname(os.path.abspath(__file__)))
  28. # Parse options
  29. parser = OptionParser()
  30. parser.add_option("--timeout", dest="timeout", default=60, type="int",
  31. help="Number of seconds after which heartbeat timeouts.")
  32. parser.add_option("--path", dest="pypath",
  33. help="Add extra entry to python-path.")
  34. parser.add_option("--log", dest="logfile",
  35. help="Log responses to file.", metavar="FILE")
  36. (options, argv) = parser.parse_args(sys.argv)
  37. # Set extra pythonpath?
  38. if options.pypath:
  39. sys.path.insert(0, options.pypath)
  40. # Validate timeout
  41. if options.timeout < 5 or options.timeout > 300:
  42. raise ValueError("Timeout cannot be lower than 5 seconds and greater than 5 minutes (300 seconds).")
  43. try:
  44. # Read Misago settings
  45. settings = __import__(argv[1]).settings
  46. BOARD_ADDRESS = settings.BOARD_ADDRESS
  47. HEARTBEAT_PATH = settings.HEARTBEAT_PATH
  48. # Validate
  49. if not BOARD_ADDRESS:
  50. raise ValueError('"BOARD_ADDRESS" setting is not set.')
  51. if not HEARTBEAT_PATH:
  52. raise ValueError('"HEARTBEAT_PATH" setting is not set.')
  53. request_url = '%s/%s' % (BOARD_ADDRESS, HEARTBEAT_PATH)
  54. # Send and handle request
  55. try:
  56. stopwatch = time()
  57. response = urllib2.urlopen(request_url, timeout=options.timeout)
  58. body = response.read()
  59. response.close()
  60. response.time = time() - stopwatch
  61. log_entry(options.logfile, response)
  62. except urllib2.URLError:
  63. log_entry(options.logfile)
  64. except IndexError:
  65. raise ValueError("You have to specify name of Misago's settings module used by your forum.")
  66. except ImportError:
  67. raise ValueError('"%s" could not be imported.' % argv[1])
  68. except AttributeError as e:
  69. raise ValueError('"%s" is not correct settings module.' % argv[1])
  70. if __name__ == '__main__':
  71. heartbeat()