2012-11-27 17:18:46 +01:00
|
|
|
#!/usr/bin/python
|
2012-08-23 19:41:26 +02:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
|
|
|
# (c) 2012, Jeroen Hoekx <jeroen@hoekx.be>
|
|
|
|
#
|
|
|
|
# This file is part of Ansible
|
|
|
|
#
|
|
|
|
# Ansible is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# Ansible is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
2015-10-28 01:26:51 +01:00
|
|
|
import binascii
|
2012-08-23 19:41:26 +02:00
|
|
|
import datetime
|
2015-10-28 01:26:51 +01:00
|
|
|
import math
|
2013-11-13 01:02:01 +01:00
|
|
|
import re
|
2015-10-28 01:26:51 +01:00
|
|
|
import select
|
|
|
|
import socket
|
|
|
|
import sys
|
|
|
|
import time
|
2014-08-21 23:15:55 +02:00
|
|
|
|
|
|
|
HAS_PSUTIL = False
|
|
|
|
try:
|
|
|
|
import psutil
|
|
|
|
HAS_PSUTIL = True
|
|
|
|
# just because we can import it on Linux doesn't mean we will use it
|
|
|
|
except ImportError:
|
|
|
|
pass
|
2012-08-23 19:41:26 +02:00
|
|
|
|
2012-09-29 00:49:02 +02:00
|
|
|
DOCUMENTATION = '''
|
|
|
|
---
|
|
|
|
module: wait_for
|
2013-11-13 01:02:01 +01:00
|
|
|
short_description: Waits for a condition before continuing.
|
2012-09-29 00:49:02 +02:00
|
|
|
description:
|
2015-04-07 02:41:57 +02:00
|
|
|
- You can wait for a set amount of time C(timeout), this is the default if nothing is specified.
|
|
|
|
- Waiting for a port to become available is useful for when services
|
|
|
|
are not immediately available after their init scripts return
|
|
|
|
which is true of certain Java application servers. It is also
|
2013-11-13 01:02:01 +01:00
|
|
|
useful when starting guests with the M(virt) module and
|
2015-04-07 02:41:57 +02:00
|
|
|
needing to pause until they are ready.
|
2014-03-16 22:10:37 +01:00
|
|
|
- This module can also be used to wait for a regex match a string to be present in a file.
|
2015-04-07 02:41:57 +02:00
|
|
|
- In 1.6 and later, this module can also be used to wait for a file to be available or
|
|
|
|
absent on the filesystem.
|
2014-08-27 03:30:34 +02:00
|
|
|
- In 1.8 and later, this module can also be used to wait for active
|
2014-08-21 23:15:55 +02:00
|
|
|
connections to be closed before continuing, useful if a node
|
|
|
|
is being rotated out of a load balancer pool.
|
2012-09-29 00:49:02 +02:00
|
|
|
version_added: "0.7"
|
|
|
|
options:
|
|
|
|
host:
|
|
|
|
description:
|
2015-02-21 18:44:37 +01:00
|
|
|
- A resolvable hostname or IP address to wait for
|
2012-09-29 00:49:02 +02:00
|
|
|
required: false
|
|
|
|
default: "127.0.0.1"
|
|
|
|
timeout:
|
|
|
|
description:
|
|
|
|
- maximum number of seconds to wait for
|
|
|
|
required: false
|
|
|
|
default: 300
|
2015-02-13 16:02:05 +01:00
|
|
|
connect_timeout:
|
|
|
|
description:
|
|
|
|
- maximum number of seconds to wait for a connection to happen before closing and retrying
|
|
|
|
required: false
|
|
|
|
default: 5
|
2012-09-29 00:49:02 +02:00
|
|
|
delay:
|
|
|
|
description:
|
|
|
|
- number of seconds to wait before starting to poll
|
|
|
|
required: false
|
|
|
|
default: 0
|
|
|
|
port:
|
|
|
|
description:
|
|
|
|
- port number to poll
|
2013-11-13 01:02:01 +01:00
|
|
|
required: false
|
2012-09-29 00:49:02 +02:00
|
|
|
state:
|
|
|
|
description:
|
2014-08-21 23:15:55 +02:00
|
|
|
- either C(present), C(started), or C(stopped), C(absent), or C(drained)
|
|
|
|
- When checking a port C(started) will ensure the port is open, C(stopped) will check that it is closed, C(drained) will check for active connections
|
2013-12-12 09:28:01 +01:00
|
|
|
- When checking for a file or a search string C(present) or C(started) will ensure that the file or string is present before continuing, C(absent) will check that file is absent or removed
|
2014-08-21 23:15:55 +02:00
|
|
|
choices: [ "present", "started", "stopped", "absent", "drained" ]
|
2012-09-29 00:49:02 +02:00
|
|
|
default: "started"
|
2013-11-13 01:02:01 +01:00
|
|
|
path:
|
|
|
|
version_added: "1.4"
|
|
|
|
required: false
|
|
|
|
description:
|
|
|
|
- path to a file on the filesytem that must exist before continuing
|
|
|
|
search_regex:
|
|
|
|
version_added: "1.4"
|
|
|
|
required: false
|
|
|
|
description:
|
2014-04-10 16:03:39 +02:00
|
|
|
- Can be used to match a string in either a file or a socket connection. Defaults to a multiline regex.
|
2014-08-21 23:15:55 +02:00
|
|
|
exclude_hosts:
|
2014-08-27 03:30:34 +02:00
|
|
|
version_added: "1.8"
|
2014-08-21 23:15:55 +02:00
|
|
|
required: false
|
|
|
|
description:
|
|
|
|
- list of hosts or IPs to ignore when looking for active TCP connections for C(drained) state
|
2014-04-10 16:03:39 +02:00
|
|
|
notes:
|
|
|
|
- The ability to use search_regex with a port connection was added in 1.7.
|
2013-05-16 17:13:18 +02:00
|
|
|
requirements: []
|
2015-11-03 11:54:31 +01:00
|
|
|
author:
|
2015-06-15 21:53:30 +02:00
|
|
|
- "Jeroen Hoekx (@jhoekx)"
|
|
|
|
- "John Jarvis (@jarv)"
|
|
|
|
- "Andrii Radyk (@AnderEnder)"
|
2012-09-29 00:49:02 +02:00
|
|
|
'''
|
|
|
|
|
2013-06-02 00:38:16 +02:00
|
|
|
EXAMPLES = '''
|
2013-11-13 01:02:01 +01:00
|
|
|
|
2013-06-02 00:38:16 +02:00
|
|
|
# wait 300 seconds for port 8000 to become open on the host, don't start checking for 10 seconds
|
2014-01-27 19:09:54 +01:00
|
|
|
- wait_for: port=8000 delay=10
|
2013-11-13 01:02:01 +01:00
|
|
|
|
2014-08-21 23:15:55 +02:00
|
|
|
# wait 300 seconds for port 8000 of any IP to close active connections, don't start checking for 10 seconds
|
|
|
|
- wait_for: host=0.0.0.0 port=8000 delay=10 state=drained
|
|
|
|
|
|
|
|
# wait 300 seconds for port 8000 of any IP to close active connections, ignoring connections for specified hosts
|
|
|
|
- wait_for: host=0.0.0.0 port=8000 state=drained exclude_hosts=10.2.1.2,10.2.1.3
|
|
|
|
|
2013-11-13 01:02:01 +01:00
|
|
|
# wait until the file /tmp/foo is present before continuing
|
|
|
|
- wait_for: path=/tmp/foo
|
|
|
|
|
|
|
|
# wait until the string "completed" is in the file /tmp/foo before continuing
|
|
|
|
- wait_for: path=/tmp/foo search_regex=completed
|
|
|
|
|
2013-12-12 09:28:01 +01:00
|
|
|
# wait until the lock file is removed
|
2015-11-03 11:54:31 +01:00
|
|
|
- wait_for: path=/var/lock/file.lock state=absent
|
2013-12-12 09:28:01 +01:00
|
|
|
|
|
|
|
# wait until the process is finished and pid was destroyed
|
|
|
|
- wait_for: path=/proc/3466/status state=absent
|
|
|
|
|
2015-02-21 18:44:37 +01:00
|
|
|
# wait 300 seconds for port 22 to become open and contain "OpenSSH", don't assume the inventory_hostname is resolvable
|
|
|
|
# and don't start checking for 10 seconds
|
|
|
|
- local_action: wait_for port=22 host="{{ ansible_ssh_host | default(inventory_hostname) }}" search_regex=OpenSSH delay=10
|
2014-04-10 16:03:39 +02:00
|
|
|
|
2013-06-02 00:38:16 +02:00
|
|
|
'''
|
|
|
|
|
2014-08-21 23:15:55 +02:00
|
|
|
class TCPConnectionInfo(object):
|
|
|
|
"""
|
|
|
|
This is a generic TCP Connection Info strategy class that relies
|
|
|
|
on the psutil module, which is not ideal for targets, but necessary
|
|
|
|
for cross platform support.
|
|
|
|
|
|
|
|
A subclass may wish to override some or all of these methods.
|
|
|
|
- _get_exclude_ips()
|
|
|
|
- get_active_connections()
|
|
|
|
|
|
|
|
All subclasses MUST define platform and distribution (which may be None).
|
|
|
|
"""
|
|
|
|
platform = 'Generic'
|
|
|
|
distribution = None
|
|
|
|
|
|
|
|
match_all_ips = {
|
|
|
|
socket.AF_INET: '0.0.0.0',
|
|
|
|
socket.AF_INET6: '::',
|
|
|
|
}
|
2015-05-04 21:02:56 +02:00
|
|
|
ipv4_mapped_ipv6_address = {
|
|
|
|
'prefix': '::ffff',
|
|
|
|
'match_all': '::ffff:0.0.0.0'
|
|
|
|
}
|
2014-08-21 23:15:55 +02:00
|
|
|
connection_states = {
|
|
|
|
'01': 'ESTABLISHED',
|
|
|
|
'02': 'SYN_SENT',
|
|
|
|
'03': 'SYN_RECV',
|
|
|
|
'04': 'FIN_WAIT1',
|
|
|
|
'05': 'FIN_WAIT2',
|
|
|
|
'06': 'TIME_WAIT',
|
|
|
|
}
|
|
|
|
|
|
|
|
def __new__(cls, *args, **kwargs):
|
|
|
|
return load_platform_subclass(TCPConnectionInfo, args, kwargs)
|
|
|
|
|
|
|
|
def __init__(self, module):
|
|
|
|
self.module = module
|
2015-05-04 21:02:56 +02:00
|
|
|
self.ips = _convert_host_to_ip(module.params['host'])
|
2014-08-21 23:15:55 +02:00
|
|
|
self.port = int(self.module.params['port'])
|
|
|
|
self.exclude_ips = self._get_exclude_ips()
|
|
|
|
if not HAS_PSUTIL:
|
|
|
|
module.fail_json(msg="psutil module required for wait_for")
|
|
|
|
|
|
|
|
def _get_exclude_ips(self):
|
2014-11-11 21:09:42 +01:00
|
|
|
exclude_hosts = self.module.params['exclude_hosts']
|
2015-05-04 21:02:56 +02:00
|
|
|
exclude_ips = []
|
|
|
|
if exclude_hosts is not None:
|
|
|
|
for host in exclude_hosts:
|
|
|
|
exclude_ips.extend(_convert_host_to_ip(host))
|
|
|
|
return exclude_ips
|
2014-08-21 23:15:55 +02:00
|
|
|
|
|
|
|
def get_active_connections_count(self):
|
|
|
|
active_connections = 0
|
|
|
|
for p in psutil.process_iter():
|
|
|
|
connections = p.get_connections(kind='inet')
|
|
|
|
for conn in connections:
|
|
|
|
if conn.status not in self.connection_states.values():
|
|
|
|
continue
|
|
|
|
(local_ip, local_port) = conn.local_address
|
2015-05-04 21:02:56 +02:00
|
|
|
if self.port != local_port:
|
|
|
|
continue
|
|
|
|
(remote_ip, remote_port) = conn.remote_address
|
|
|
|
if (conn.family, remote_ip) in self.exclude_ips:
|
|
|
|
continue
|
|
|
|
if any((
|
|
|
|
(conn.family, local_ip) in self.ips,
|
|
|
|
(conn.family, self.match_all_ips[conn.family]) in self.ips,
|
|
|
|
local_ip.startswith(self.ipv4_mapped_ipv6_address['prefix']) and
|
|
|
|
(conn.family, self.ipv4_mapped_ipv6_address['match_all']) in self.ips,
|
|
|
|
)):
|
|
|
|
active_connections += 1
|
2014-08-21 23:15:55 +02:00
|
|
|
return active_connections
|
|
|
|
|
|
|
|
|
|
|
|
# ===========================================
|
|
|
|
# Subclass: Linux
|
|
|
|
|
|
|
|
class LinuxTCPConnectionInfo(TCPConnectionInfo):
|
|
|
|
"""
|
|
|
|
This is a TCP Connection Info evaluation strategy class
|
|
|
|
that utilizes information from Linux's procfs. While less universal,
|
|
|
|
does allow Linux targets to not require an additional library.
|
|
|
|
"""
|
|
|
|
platform = 'Linux'
|
|
|
|
distribution = None
|
|
|
|
|
|
|
|
source_file = {
|
|
|
|
socket.AF_INET: '/proc/net/tcp',
|
|
|
|
socket.AF_INET6: '/proc/net/tcp6'
|
|
|
|
}
|
|
|
|
match_all_ips = {
|
|
|
|
socket.AF_INET: '00000000',
|
|
|
|
socket.AF_INET6: '00000000000000000000000000000000',
|
|
|
|
}
|
2015-05-04 21:02:56 +02:00
|
|
|
ipv4_mapped_ipv6_address = {
|
|
|
|
'prefix': '0000000000000000FFFF0000',
|
|
|
|
'match_all': '0000000000000000FFFF000000000000'
|
|
|
|
}
|
2014-08-21 23:15:55 +02:00
|
|
|
local_address_field = 1
|
|
|
|
remote_address_field = 2
|
|
|
|
connection_state_field = 3
|
|
|
|
|
|
|
|
def __init__(self, module):
|
|
|
|
self.module = module
|
2015-05-04 21:02:56 +02:00
|
|
|
self.ips = _convert_host_to_hex(module.params['host'])
|
2014-08-21 23:15:55 +02:00
|
|
|
self.port = "%0.4X" % int(module.params['port'])
|
|
|
|
self.exclude_ips = self._get_exclude_ips()
|
|
|
|
|
|
|
|
def _get_exclude_ips(self):
|
2014-11-11 21:09:42 +01:00
|
|
|
exclude_hosts = self.module.params['exclude_hosts']
|
2015-05-04 21:02:56 +02:00
|
|
|
exclude_ips = []
|
|
|
|
if exclude_hosts is not None:
|
|
|
|
for host in exclude_hosts:
|
|
|
|
exclude_ips.extend(_convert_host_to_hex(host))
|
|
|
|
return exclude_ips
|
2014-08-21 23:15:55 +02:00
|
|
|
|
|
|
|
def get_active_connections_count(self):
|
|
|
|
active_connections = 0
|
2015-05-04 21:02:56 +02:00
|
|
|
for family in self.source_file.keys():
|
|
|
|
f = open(self.source_file[family])
|
|
|
|
for tcp_connection in f.readlines():
|
|
|
|
tcp_connection = tcp_connection.strip().split()
|
|
|
|
if tcp_connection[self.local_address_field] == 'local_address':
|
|
|
|
continue
|
|
|
|
if tcp_connection[self.connection_state_field] not in self.connection_states:
|
|
|
|
continue
|
|
|
|
(local_ip, local_port) = tcp_connection[self.local_address_field].split(':')
|
|
|
|
if self.port != local_port:
|
|
|
|
continue
|
|
|
|
(remote_ip, remote_port) = tcp_connection[self.remote_address_field].split(':')
|
|
|
|
if (family, remote_ip) in self.exclude_ips:
|
|
|
|
continue
|
|
|
|
if any((
|
|
|
|
(family, local_ip) in self.ips,
|
|
|
|
(family, self.match_all_ips[family]) in self.ips,
|
|
|
|
local_ip.startswith(self.ipv4_mapped_ipv6_address['prefix']) and
|
|
|
|
(family, self.ipv4_mapped_ipv6_address['match_all']) in self.ips,
|
|
|
|
)):
|
|
|
|
active_connections += 1
|
|
|
|
f.close()
|
2014-08-21 23:15:55 +02:00
|
|
|
return active_connections
|
|
|
|
|
|
|
|
|
|
|
|
def _convert_host_to_ip(host):
|
|
|
|
"""
|
|
|
|
Perform forward DNS resolution on host, IP will give the same IP
|
|
|
|
|
|
|
|
Args:
|
|
|
|
host: String with either hostname, IPv4, or IPv6 address
|
|
|
|
|
|
|
|
Returns:
|
2015-05-04 21:02:56 +02:00
|
|
|
List of tuples containing address family and IP
|
2014-08-21 23:15:55 +02:00
|
|
|
"""
|
2015-05-04 21:02:56 +02:00
|
|
|
addrinfo = socket.getaddrinfo(host, 80, 0, 0, socket.SOL_TCP)
|
|
|
|
ips = []
|
|
|
|
for family, socktype, proto, canonname, sockaddr in addrinfo:
|
|
|
|
ip = sockaddr[0]
|
|
|
|
ips.append((family, ip))
|
|
|
|
if family == socket.AF_INET:
|
|
|
|
ips.append((socket.AF_INET6, "::ffff:" + ip))
|
|
|
|
return ips
|
2014-08-21 23:15:55 +02:00
|
|
|
|
|
|
|
def _convert_host_to_hex(host):
|
|
|
|
"""
|
|
|
|
Convert the provided host to the format in /proc/net/tcp*
|
|
|
|
|
|
|
|
/proc/net/tcp uses little-endian four byte hex for ipv4
|
|
|
|
/proc/net/tcp6 uses little-endian per 4B word for ipv6
|
|
|
|
|
|
|
|
Args:
|
|
|
|
host: String with either hostname, IPv4, or IPv6 address
|
|
|
|
|
|
|
|
Returns:
|
2015-05-04 21:02:56 +02:00
|
|
|
List of tuples containing address family and the
|
|
|
|
little-endian converted host
|
2014-08-21 23:15:55 +02:00
|
|
|
"""
|
2015-05-04 21:02:56 +02:00
|
|
|
ips = []
|
|
|
|
if host is not None:
|
|
|
|
for family, ip in _convert_host_to_ip(host):
|
|
|
|
hexip_nf = binascii.b2a_hex(socket.inet_pton(family, ip))
|
|
|
|
hexip_hf = ""
|
|
|
|
for i in range(0, len(hexip_nf), 8):
|
|
|
|
ipgroup_nf = hexip_nf[i:i+8]
|
|
|
|
ipgroup_hf = socket.ntohl(int(ipgroup_nf, base=16))
|
|
|
|
hexip_hf = "%s%08X" % (hexip_hf, ipgroup_hf)
|
|
|
|
ips.append((family, hexip_hf))
|
|
|
|
return ips
|
2014-08-21 23:15:55 +02:00
|
|
|
|
2015-01-05 19:05:01 +01:00
|
|
|
def _create_connection( (host, port), connect_timeout):
|
|
|
|
"""
|
|
|
|
Connect to a 2-tuple (host, port) and return
|
|
|
|
the socket object.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
2-tuple (host, port) and connection timeout
|
|
|
|
Returns:
|
|
|
|
Socket object
|
|
|
|
"""
|
|
|
|
if sys.version_info < (2, 6):
|
|
|
|
(family, _) = _convert_host_to_ip(host)
|
|
|
|
connect_socket = socket.socket(family, socket.SOCK_STREAM)
|
|
|
|
connect_socket.settimeout(connect_timeout)
|
|
|
|
connect_socket.connect( (host, port) )
|
|
|
|
else:
|
|
|
|
connect_socket = socket.create_connection( (host, port), connect_timeout)
|
|
|
|
return connect_socket
|
|
|
|
|
2015-11-03 11:54:31 +01:00
|
|
|
def _timedelta_total_seconds(timedelta):
|
|
|
|
return (
|
|
|
|
timedelta.microseconds + 0.0 +
|
|
|
|
(timedelta.seconds + timedelta.days * 24 * 3600) * 10 ** 6) / 10 ** 6
|
|
|
|
|
2012-08-23 19:41:26 +02:00
|
|
|
def main():
|
|
|
|
|
|
|
|
module = AnsibleModule(
|
|
|
|
argument_spec = dict(
|
2012-08-24 20:58:05 +02:00
|
|
|
host=dict(default='127.0.0.1'),
|
2016-02-29 07:30:39 +01:00
|
|
|
timeout=dict(default=300, type='int'),
|
|
|
|
connect_timeout=dict(default=5, type='int'),
|
|
|
|
delay=dict(default=0, type='int'),
|
|
|
|
port=dict(default=None, type='int'),
|
|
|
|
path=dict(default=None, type='path'),
|
2013-11-13 01:02:01 +01:00
|
|
|
search_regex=dict(default=None),
|
2014-08-21 23:15:55 +02:00
|
|
|
state=dict(default='started', choices=['started', 'stopped', 'present', 'absent', 'drained']),
|
2014-11-11 21:34:55 +01:00
|
|
|
exclude_hosts=dict(default=None, type='list')
|
2012-08-23 19:41:26 +02:00
|
|
|
),
|
|
|
|
)
|
|
|
|
|
|
|
|
params = module.params
|
|
|
|
|
2012-08-24 20:58:05 +02:00
|
|
|
host = params['host']
|
2016-02-29 07:30:39 +01:00
|
|
|
timeout = params['timeout']
|
|
|
|
connect_timeout = params['connect_timeout']
|
|
|
|
delay = params['delay']
|
|
|
|
port = params['port']
|
2012-08-24 19:08:45 +02:00
|
|
|
state = params['state']
|
2013-11-13 01:02:01 +01:00
|
|
|
path = params['path']
|
|
|
|
search_regex = params['search_regex']
|
2015-10-28 01:26:51 +01:00
|
|
|
if search_regex is not None:
|
|
|
|
compiled_search_re = re.compile(search_regex, re.MULTILINE)
|
|
|
|
else:
|
|
|
|
compiled_search_re = None
|
2014-11-11 21:09:42 +01:00
|
|
|
|
2013-11-13 01:02:01 +01:00
|
|
|
if port and path:
|
|
|
|
module.fail_json(msg="port and path parameter can not both be passed to wait_for")
|
|
|
|
if path and state == 'stopped':
|
|
|
|
module.fail_json(msg="state=stopped should only be used for checking a port in the wait_for module")
|
2014-08-21 23:15:55 +02:00
|
|
|
if path and state == 'drained':
|
|
|
|
module.fail_json(msg="state=drained should only be used for checking a port in the wait_for module")
|
2014-11-11 21:09:42 +01:00
|
|
|
if params['exclude_hosts'] is not None and state != 'drained':
|
2014-08-21 23:15:55 +02:00
|
|
|
module.fail_json(msg="exclude_hosts should only be with state=drained")
|
2014-11-11 21:09:42 +01:00
|
|
|
|
2015-05-26 15:57:38 +02:00
|
|
|
|
2013-06-28 02:37:40 +02:00
|
|
|
start = datetime.datetime.now()
|
|
|
|
|
2012-08-24 20:58:05 +02:00
|
|
|
if delay:
|
|
|
|
time.sleep(delay)
|
|
|
|
|
2015-05-26 15:57:38 +02:00
|
|
|
if not port and not path and state != 'drained':
|
|
|
|
time.sleep(timeout)
|
|
|
|
elif state in [ 'stopped', 'absent' ]:
|
2013-11-13 01:02:01 +01:00
|
|
|
### first wait for the stop condition
|
2012-09-19 12:29:47 +02:00
|
|
|
end = start + datetime.timedelta(seconds=timeout)
|
2012-08-23 19:41:26 +02:00
|
|
|
|
2012-08-24 19:08:45 +02:00
|
|
|
while datetime.datetime.now() < end:
|
2013-12-12 09:28:01 +01:00
|
|
|
if path:
|
|
|
|
try:
|
|
|
|
f = open(path)
|
|
|
|
f.close()
|
|
|
|
time.sleep(1)
|
|
|
|
pass
|
|
|
|
except IOError:
|
|
|
|
break
|
|
|
|
elif port:
|
|
|
|
try:
|
2015-01-05 19:05:01 +01:00
|
|
|
s = _create_connection( (host, port), connect_timeout)
|
2013-12-12 09:28:01 +01:00
|
|
|
s.shutdown(socket.SHUT_RDWR)
|
|
|
|
s.close()
|
|
|
|
time.sleep(1)
|
|
|
|
except:
|
|
|
|
break
|
2015-05-26 15:57:38 +02:00
|
|
|
else:
|
|
|
|
time.sleep(1)
|
2012-08-24 19:08:45 +02:00
|
|
|
else:
|
2012-09-19 12:29:47 +02:00
|
|
|
elapsed = datetime.datetime.now() - start
|
2013-12-12 09:28:01 +01:00
|
|
|
if port:
|
|
|
|
module.fail_json(msg="Timeout when waiting for %s:%s to stop." % (host, port), elapsed=elapsed.seconds)
|
|
|
|
elif path:
|
|
|
|
module.fail_json(msg="Timeout when waiting for %s to be absent." % (path), elapsed=elapsed.seconds)
|
2012-08-23 19:41:26 +02:00
|
|
|
|
2013-11-13 01:02:01 +01:00
|
|
|
elif state in ['started', 'present']:
|
|
|
|
### wait for start condition
|
2012-09-19 12:29:47 +02:00
|
|
|
end = start + datetime.timedelta(seconds=timeout)
|
2012-08-24 19:08:45 +02:00
|
|
|
while datetime.datetime.now() < end:
|
2013-11-13 01:02:01 +01:00
|
|
|
if path:
|
2014-05-13 18:43:47 +02:00
|
|
|
try:
|
|
|
|
os.stat(path)
|
|
|
|
except OSError, e:
|
2015-10-28 01:26:51 +01:00
|
|
|
# If anything except file not present, throw an error
|
|
|
|
if e.errno != 2:
|
2014-05-13 18:43:47 +02:00
|
|
|
elapsed = datetime.datetime.now() - start
|
|
|
|
module.fail_json(msg="Failed to stat %s, %s" % (path, e.strerror), elapsed=elapsed.seconds)
|
2015-10-28 01:26:51 +01:00
|
|
|
# file doesn't exist yet, so continue
|
|
|
|
else:
|
|
|
|
# File exists. Are there additional things to check?
|
|
|
|
if not compiled_search_re:
|
|
|
|
# nope, succeed!
|
|
|
|
break
|
|
|
|
try:
|
|
|
|
f = open(path)
|
|
|
|
try:
|
|
|
|
if re.search(compiled_search_re, f.read()):
|
|
|
|
# String found, success!
|
|
|
|
break
|
|
|
|
finally:
|
|
|
|
f.close()
|
|
|
|
except IOError:
|
|
|
|
pass
|
2013-11-13 01:02:01 +01:00
|
|
|
elif port:
|
2015-11-03 11:54:31 +01:00
|
|
|
alt_connect_timeout = math.ceil(_timedelta_total_seconds(end - datetime.datetime.now()))
|
2013-11-13 01:02:01 +01:00
|
|
|
try:
|
2015-10-28 01:26:51 +01:00
|
|
|
s = _create_connection((host, port), min(connect_timeout, alt_connect_timeout))
|
|
|
|
except:
|
|
|
|
# Failed to connect by connect_timeout. wait and try again
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
# Connected -- are there additional conditions?
|
|
|
|
if compiled_search_re:
|
2014-04-10 16:03:39 +02:00
|
|
|
data = ''
|
|
|
|
matched = False
|
2015-10-28 01:26:51 +01:00
|
|
|
while datetime.datetime.now() < end:
|
2015-11-03 11:54:31 +01:00
|
|
|
max_timeout = math.ceil(_timedelta_total_seconds(end - datetime.datetime.now()))
|
2015-10-28 01:26:51 +01:00
|
|
|
(readable, w, e) = select.select([s], [], [], max_timeout)
|
|
|
|
if not readable:
|
|
|
|
# No new data. Probably means our timeout
|
|
|
|
# expired
|
|
|
|
continue
|
|
|
|
response = s.recv(1024)
|
|
|
|
if not response:
|
|
|
|
# Server shutdown
|
2014-07-14 21:14:13 +02:00
|
|
|
break
|
2015-10-28 01:26:51 +01:00
|
|
|
data += response
|
|
|
|
if re.search(compiled_search_re, data):
|
2014-04-10 16:03:39 +02:00
|
|
|
matched = True
|
|
|
|
break
|
2015-10-28 01:26:51 +01:00
|
|
|
|
|
|
|
# Shutdown the client socket
|
|
|
|
s.shutdown(socket.SHUT_RDWR)
|
|
|
|
s.close()
|
2014-04-10 16:03:39 +02:00
|
|
|
if matched:
|
2015-10-28 01:26:51 +01:00
|
|
|
# Found our string, success!
|
2014-04-10 16:03:39 +02:00
|
|
|
break
|
|
|
|
else:
|
2015-10-28 01:26:51 +01:00
|
|
|
# Connection established, success!
|
2014-04-10 16:03:39 +02:00
|
|
|
s.shutdown(socket.SHUT_RDWR)
|
|
|
|
s.close()
|
|
|
|
break
|
2015-10-28 01:26:51 +01:00
|
|
|
|
|
|
|
# Conditions not yet met, wait and try again
|
|
|
|
time.sleep(1)
|
|
|
|
|
|
|
|
else: # while-else
|
|
|
|
# Timeout expired
|
2012-09-19 12:29:47 +02:00
|
|
|
elapsed = datetime.datetime.now() - start
|
2013-11-13 01:02:01 +01:00
|
|
|
if port:
|
2014-04-10 16:03:39 +02:00
|
|
|
if search_regex:
|
|
|
|
module.fail_json(msg="Timeout when waiting for search string %s in %s:%s" % (search_regex, host, port), elapsed=elapsed.seconds)
|
|
|
|
else:
|
|
|
|
module.fail_json(msg="Timeout when waiting for %s:%s" % (host, port), elapsed=elapsed.seconds)
|
2013-11-13 01:02:01 +01:00
|
|
|
elif path:
|
|
|
|
if search_regex:
|
|
|
|
module.fail_json(msg="Timeout when waiting for search string %s in %s" % (search_regex, path), elapsed=elapsed.seconds)
|
|
|
|
else:
|
|
|
|
module.fail_json(msg="Timeout when waiting for file %s" % (path), elapsed=elapsed.seconds)
|
|
|
|
|
2014-08-21 23:15:55 +02:00
|
|
|
elif state == 'drained':
|
|
|
|
### wait until all active connections are gone
|
|
|
|
end = start + datetime.timedelta(seconds=timeout)
|
|
|
|
tcpconns = TCPConnectionInfo(module)
|
|
|
|
while datetime.datetime.now() < end:
|
|
|
|
try:
|
|
|
|
if tcpconns.get_active_connections_count() == 0:
|
|
|
|
break
|
|
|
|
except IOError:
|
|
|
|
pass
|
|
|
|
time.sleep(1)
|
|
|
|
else:
|
|
|
|
elapsed = datetime.datetime.now() - start
|
|
|
|
module.fail_json(msg="Timeout when waiting for %s:%s to drain" % (host, port), elapsed=elapsed.seconds)
|
2012-08-24 19:08:45 +02:00
|
|
|
|
2012-09-19 12:29:47 +02:00
|
|
|
elapsed = datetime.datetime.now() - start
|
2013-11-13 01:02:01 +01:00
|
|
|
module.exit_json(state=state, port=port, search_regex=search_regex, path=path, elapsed=elapsed.seconds)
|
2012-08-23 19:41:26 +02:00
|
|
|
|
2013-12-02 21:13:49 +01:00
|
|
|
# import module snippets
|
2013-12-02 21:11:23 +01:00
|
|
|
from ansible.module_utils.basic import *
|
2015-10-28 01:26:51 +01:00
|
|
|
if __name__ == '__main__':
|
|
|
|
main()
|