Advertisement
rfmonk

is_pastebin_up.py

Jun 26th, 2014
282
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env python
  2. #
  3. # Let me know when the server comes back online
  4.  
  5.  
  6. import argparse
  7. import socket
  8. import errno
  9. from time import time as now
  10.  
  11. DEFAULT_TIMEOUT = 120
  12. DEFAULT_SERVER_HOST = 'http://pastebin.com/'
  13. DEFAULT_SERVER_PORT = 80
  14.  
  15.  
  16. class NetServiceChecker(object):
  17.     """ waiting for service to come back on line """
  18.     def __init__(self, host, port, timeout=DEFAULT_TIMEOUT):
  19.         self.host = host
  20.         self.port = port
  21.         self.timeout = timeout
  22.         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  23.  
  24.     def end_wait(self):
  25.         self.sock.close()
  26.  
  27.     def check(self):
  28.         """ Check the service """
  29.         if self.timeout:
  30.             end_time = now() + self.timeout
  31.  
  32.         while  True:
  33.             try:
  34.                 if self.timeout:
  35.                     next_timeout = end_time - now()
  36.                     if next_timeout < 0:
  37.                         return False
  38.                     else:
  39.                         print "Setting socket next timeout %ss"\
  40.                         %round(next_timeout)
  41.                         self.sock.settimeout(next_timeout)
  42.                 self.sock.connect((self.host, self.port))
  43.             # handle exceptions
  44.             except socket.timeout, err:
  45.                 if self.timeout:
  46.                     return False
  47.             except socket.error, err:
  48.                 print "Exception: %s" %err
  49.             else:
  50.                 self.end_wait()
  51.                 return True
  52.  
  53.  
  54. if __name__ == '__main__':
  55.     parser = argparse.ArgumentParser(description='Wait for Network Service')
  56.     parser.add_argument('--host', action="store", dest="host", default=DEFAULT_SERVER_HOST)
  57.     parser.add_argument('--port', action="store", dest="port", type=int,\
  58.         default=DEFAULT_SERVER_PORT)
  59.     parser.add_argument('--timeout', action="store", dest="timeout", type=int,\
  60.         default=DEFAULT_TIMEOUT)
  61.     given_args = parser.parse_args()
  62.     host, port, timeout = given_args.host, given_args.port, given_args.timeout
  63.     service_checker = NetServiceChecker(host, port, timeout=timeout)
  64.     print "Checking for net service %s:%s ..." %(host, port)
  65.     if service_checker.check():
  66.         print "Service is available again!"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement