等待网络服务是否可用

#coding:utf-8
__author__ = 'similarface'
import argparse
import socket
import errno
from time import time as now

DEFAULT_TIMEOUT = 120
DEFAULT_SERVER_HOST = 'localhost'
DEFAULT_SERVER_PORT = 80

class NetServiceChecker(object):
    """ Wait for a network service to come online"""
    def __init__(self, host, port, timeout=DEFAULT_TIMEOUT):
        self.host = host
        self.port = port
        self.timeout = timeout
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def end_wait(self):
        self.sock.close()

    def check(self):
        """ Check the service """
        if self.timeout:
            #超时时间间隔+加上现在的时间
            end_time = now() + self.timeout

        while True:
            try:
                if self.timeout:
                    #下一次的超时时间
                    next_timeout = end_time - now()
                    if next_timeout < 0:
                        return False
                    else:
                        print "设置soct的timeout参数 %ss" %round(next_timeout)
                        self.sock.settimeout(next_timeout)
                #连接sock
                self.sock.connect((self.host, self.port))
            # handle exceptions
            except socket.timeout, err:
                if self.timeout:
                    return False
            except socket.error, err:
                print "Exception: %s" %err
            else:
                #如果soct能建立
                self.end_wait()
                return True

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Wait for Network Service')
    parser.add_argument('--host', action="store", dest="host",  default=DEFAULT_SERVER_HOST)
    parser.add_argument('--port', action="store", dest="port", type=int, default=DEFAULT_SERVER_PORT)
    parser.add_argument('--timeout', action="store", dest="timeout", type=int, default=DEFAULT_TIMEOUT)
    given_args = parser.parse_args()
    host, port, timeout = given_args.host, given_args.port, given_args.timeout
    service_checker = NetServiceChecker(host, port, timeout=timeout)
    print "检测网络服务 %s:%s ..." %(host, port)
    if service_checker.check():
        print "服务可用!"
    else:
        print "服务不可用!"

  

posted @ 2016-05-26 14:41  similarface  阅读(199)  评论(0编辑  收藏  举报