From 8912258016899c2080f0a243040caba0682cb247 Mon Sep 17 00:00:00 2001 From: Dag Wieers Date: Wed, 19 Sep 2012 12:29:47 +0200 Subject: [PATCH] Fix on older python versions, plus various improvements This change includes: - (on possibly older python versions ?) a string variable test using the 'is' operator fails (so it always return ok immediately after initial delay) - add a missing socket.settimeout() for the state=started case (if the machine does not exist, timeout defaults to 60 seconds) - add a connect_timeout option to customize the default connection timeout - use socket.shutdown(2) to close immediately - return the elapsed time --- library/wait_for | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/library/wait_for b/library/wait_for index e1cc1b38e00..1fc6e2b866e 100755 --- a/library/wait_for +++ b/library/wait_for @@ -29,6 +29,7 @@ def main(): argument_spec = dict( host=dict(default='127.0.0.1'), timeout=dict(default=300), + connect_timeout=dict(default=5), delay=dict(default=0), port=dict(required=True), state=dict(default='started', choices=['started', 'stopped']), @@ -39,6 +40,7 @@ def main(): host = params['host'] timeout = int(params['timeout']) + connect_timeout = int(params['connect_timeout']) delay = int(params['delay']) port = int(params['port']) state = params['state'] @@ -46,38 +48,47 @@ def main(): if delay: time.sleep(delay) - if state is 'stopped': + start = datetime.datetime.now() + + if state == 'stopped': ### first wait for the host to go down - end = datetime.datetime.now() + datetime.timedelta(seconds=timeout) + end = start + datetime.timedelta(seconds=timeout) while datetime.datetime.now() < end: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.settimeout(5) + s.settimeout(connect_timeout) try: s.connect( (host, port) ) + s.shutdown(socket.SHUT_RDWR) s.close() time.sleep(1) except: break else: - module.fail_json(msg="Timeout when waiting for %s to stop."%(host)) + elapsed = datetime.datetime.now() - start + module.fail_json(msg="Timeout when waiting for %s:%s to stop." % (host, port), elapsed=elapsed.seconds) - if state is 'started': + elif state == 'started': ### wait for the host to come up - end = datetime.datetime.now() + datetime.timedelta(seconds=timeout) + end = start + datetime.timedelta(seconds=timeout) while datetime.datetime.now() < end: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.settimeout(connect_timeout) try: s.connect( (host, port) ) + s.shutdown(socket.SHUT_RDWR) s.close() break except: time.sleep(1) + pass else: - module.fail_json(msg="Timeout when waiting for %s"%(host)) + elapsed = datetime.datetime.now() - start + module.fail_json(msg="Timeout when waiting for %s:%s" % (host, port), elapsed=elapsed.seconds) - module.exit_json(state=state, port=port) + elapsed = datetime.datetime.now() - start + module.exit_json(state=state, port=port, elapsed=elapsed.seconds) # this is magic, see lib/ansible/module_common.py #<>