| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright: (c) 2012, Jeroen Hoekx <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
|
| 9 |
DOCUMENTATION = r""" |
| 10 |
--- |
| 11 |
module: wait_for |
| 12 |
short_description: Waits for a condition before continuing |
| 13 |
description: |
| 14 |
- You can wait for a set amount of time O(timeout), this is the default if nothing is specified or just O(timeout) is specified. |
| 15 |
This does not produce an error. |
| 16 |
- Waiting for a port to become available is useful for when services are not immediately available after their init scripts return |
| 17 |
which is true of certain Java application servers. |
| 18 |
- It is also useful when starting guests with the M(community.libvirt.virt) module and needing to pause until they are ready. |
| 19 |
- This module can also be used to wait for a regex match a string to be present in a file. |
| 20 |
- In Ansible 1.6 and later, this module can also be used to wait for a file to be available or |
| 21 |
absent on the filesystem. |
| 22 |
- In Ansible 1.8 and later, this module can also be used to wait for active connections to be closed before continuing, useful if a node |
| 23 |
is being rotated out of a load balancer pool. |
| 24 |
- For Windows targets, use the M(ansible.windows.win_wait_for) module instead. |
| 25 |
version_added: "0.7" |
| 26 |
options: |
| 27 |
host: |
| 28 |
description: |
| 29 |
- A resolvable hostname or IP address to wait for. |
| 30 |
type: str |
| 31 |
default: 127.0.0.1 |
| 32 |
timeout: |
| 33 |
description: |
| 34 |
- Maximum number of seconds to wait for, when used with another condition it will force an error. |
| 35 |
- When used without other conditions it is equivalent of just sleeping. |
| 36 |
type: int |
| 37 |
default: 300 |
| 38 |
connect_timeout: |
| 39 |
description: |
| 40 |
- Maximum number of seconds to wait for a connection to happen before closing and retrying. |
| 41 |
type: int |
| 42 |
default: 5 |
| 43 |
delay: |
| 44 |
description: |
| 45 |
- Number of seconds to wait before starting to poll. |
| 46 |
type: int |
| 47 |
default: 0 |
| 48 |
port: |
| 49 |
description: |
| 50 |
- Port number to poll. |
| 51 |
- O(path) and O(port) are mutually exclusive parameters. |
| 52 |
type: int |
| 53 |
active_connection_states: |
| 54 |
description: |
| 55 |
- The list of TCP connection states which are counted as active connections. |
| 56 |
type: list |
| 57 |
elements: str |
| 58 |
default: [ ESTABLISHED, FIN_WAIT1, FIN_WAIT2, SYN_RECV, SYN_SENT, TIME_WAIT ] |
| 59 |
version_added: "2.3" |
| 60 |
state: |
| 61 |
description: |
| 62 |
- Either V(present), V(started), or V(stopped), V(absent), or V(drained). |
| 63 |
- When checking a port V(started) will ensure the port is open, V(stopped) will check that it is closed, V(drained) will check for active connections. |
| 64 |
- When checking for a file or a search string V(present) or V(started) will ensure that the file or string is present before continuing, |
| 65 |
V(absent) will check that file is absent or removed. |
| 66 |
type: str |
| 67 |
choices: [ absent, drained, present, started, stopped ] |
| 68 |
default: started |
| 69 |
path: |
| 70 |
description: |
| 71 |
- Path to a file on the filesystem that must exist before continuing. |
| 72 |
- O(path) and O(port) are mutually exclusive parameters. |
| 73 |
type: path |
| 74 |
version_added: "1.4" |
| 75 |
search_regex: |
| 76 |
description: |
| 77 |
- Can be used to match a string in either a file or a socket connection. |
| 78 |
- Defaults to a multiline regex. |
| 79 |
- When inspecting a system log file and a static string, remember that Ansible by default logs its own actions there; |
| 80 |
see the notes and examples for information. |
| 81 |
type: str |
| 82 |
version_added: "1.4" |
| 83 |
exclude_hosts: |
| 84 |
description: |
| 85 |
- List of hosts or IPs to ignore when looking for active TCP connections for V(drained) state. |
| 86 |
type: list |
| 87 |
elements: str |
| 88 |
version_added: "1.8" |
| 89 |
sleep: |
| 90 |
description: |
| 91 |
- Number of seconds to sleep between checks. |
| 92 |
- Before Ansible 2.3 this was hardcoded to 1 second. |
| 93 |
type: int |
| 94 |
default: 1 |
| 95 |
version_added: "2.3" |
| 96 |
msg: |
| 97 |
description: |
| 98 |
- This overrides the normal error message from a failure to meet the required conditions. |
| 99 |
type: str |
| 100 |
version_added: "2.4" |
| 101 |
extends_documentation_fragment: action_common_attributes |
| 102 |
attributes: |
| 103 |
check_mode: |
| 104 |
support: none |
| 105 |
diff_mode: |
| 106 |
support: none |
| 107 |
platform: |
| 108 |
platforms: posix |
| 109 |
notes: |
| 110 |
- Under some circumstances when using mandatory access control, a path may always be treated as being absent even if it exists, but |
| 111 |
can't be modified or created by the remote user either. |
| 112 |
- When waiting for a path, symbolic links will be followed. Many other modules that manipulate files do not follow symbolic links, |
| 113 |
so operations on the path using other modules may not work exactly as expected. |
| 114 |
- When searching a static string within a system log file, it is important to account for potential self-matching against log entries |
| 115 |
generated by the Ansible modules. To prevent this, add a regular expression construct into the search string. For example, to match |
| 116 |
a literal string 'this thing', one could use a regular expression like 'this t[h]ing'. |
| 117 |
seealso: |
| 118 |
- module: ansible.builtin.wait_for_connection |
| 119 |
- module: ansible.windows.win_wait_for |
| 120 |
- module: community.windows.win_wait_for_process |
| 121 |
author: |
| 122 |
- Jeroen Hoekx (@jhoekx) |
| 123 |
- John Jarvis (@jarv) |
| 124 |
- Andrii Radyk (@AnderEnder) |
| 125 |
""" |
| 126 |
|
| 127 |
EXAMPLES = r""" |
| 128 |
- name: Sleep for 300 seconds and continue with play |
| 129 |
ansible.builtin.wait_for: |
| 130 |
timeout: 300 |
| 131 |
delegate_to: localhost |
| 132 |
|
| 133 |
- name: Wait for port 8000 to become open on the host, don't start checking for 10 seconds |
| 134 |
ansible.builtin.wait_for: |
| 135 |
port: 8000 |
| 136 |
delay: 10 |
| 137 |
|
| 138 |
- name: Waits for port 8000 of any IP to close active connections, don't start checking for 10 seconds |
| 139 |
ansible.builtin.wait_for: |
| 140 |
host: 0.0.0.0 |
| 141 |
port: 8000 |
| 142 |
delay: 10 |
| 143 |
state: drained |
| 144 |
|
| 145 |
- name: Wait for port 8000 of any IP to close active connections, ignoring connections for specified hosts |
| 146 |
ansible.builtin.wait_for: |
| 147 |
host: 0.0.0.0 |
| 148 |
port: 8000 |
| 149 |
state: drained |
| 150 |
exclude_hosts: 10.2.1.2,10.2.1.3 |
| 151 |
|
| 152 |
- name: Wait until the file /tmp/foo is present before continuing |
| 153 |
ansible.builtin.wait_for: |
| 154 |
path: /tmp/foo |
| 155 |
|
| 156 |
- name: Wait until the string "completed" is in the file /tmp/foo before continuing |
| 157 |
ansible.builtin.wait_for: |
| 158 |
path: /tmp/foo |
| 159 |
search_regex: completed |
| 160 |
|
| 161 |
- name: Wait until the string "tomcat up" is in syslog, use regex character set to avoid self match |
| 162 |
ansible.builtin.wait_for: |
| 163 |
path: /var/log/syslog |
| 164 |
search_regex: 'tomcat [u]p' |
| 165 |
|
| 166 |
- name: Wait until regex pattern matches in the file /tmp/foo and print the matched group |
| 167 |
ansible.builtin.wait_for: |
| 168 |
path: /tmp/foo |
| 169 |
search_regex: completed (?P<task>\w+) |
| 170 |
register: waitfor |
| 171 |
- ansible.builtin.debug: |
| 172 |
msg: Completed {{ waitfor['match_groupdict']['task'] }} |
| 173 |
|
| 174 |
- name: Wait until the lock file is removed |
| 175 |
ansible.builtin.wait_for: |
| 176 |
path: /var/lock/file.lock |
| 177 |
state: absent |
| 178 |
|
| 179 |
- name: Wait until the process is finished and pid was destroyed |
| 180 |
ansible.builtin.wait_for: |
| 181 |
path: /proc/3466/status |
| 182 |
state: absent |
| 183 |
|
| 184 |
- name: Output customized message when failed |
| 185 |
ansible.builtin.wait_for: |
| 186 |
path: /tmp/foo |
| 187 |
state: present |
| 188 |
msg: Timeout to find file /tmp/foo |
| 189 |
|
| 190 |
# Do not assume the inventory_hostname is resolvable and delay 10 seconds at start |
| 191 |
- name: Wait 300 seconds for port 22 to become open and contain "OpenSSH" |
| 192 |
ansible.builtin.wait_for: |
| 193 |
port: 22 |
| 194 |
host: '{{ (ansible_ssh_host|default(ansible_host))|default(inventory_hostname) }}' |
| 195 |
search_regex: OpenSSH |
| 196 |
delay: 10 |
| 197 |
timeout: 300 |
| 198 |
delegate_to: localhost |
| 199 |
|
| 200 |
# Same as above but using config lookup for the target, |
| 201 |
# most plugins use 'remote_addr', but ssh uses 'host' |
| 202 |
- name: Wait 300 seconds for port 22 to become open and contain "OpenSSH" |
| 203 |
ansible.builtin.wait_for: |
| 204 |
port: 22 |
| 205 |
host: "{{ lookup('config', 'host', plugin_name='ssh', plugin_type='connection') }}" |
| 206 |
search_regex: OpenSSH |
| 207 |
delay: 10 |
| 208 |
timeout: 300 |
| 209 |
delegate_to: localhost |
| 210 |
""" |
| 211 |
|
| 212 |
RETURN = r""" |
| 213 |
elapsed: |
| 214 |
description: The number of seconds that elapsed while waiting |
| 215 |
returned: always |
| 216 |
type: int |
| 217 |
sample: 23 |
| 218 |
match_groups: |
| 219 |
description: Tuple containing all the subgroups of the match as returned by U(https://docs.python.org/3/library/re.html#re.Match.groups) |
| 220 |
returned: always |
| 221 |
type: list |
| 222 |
sample: ['match 1', 'match 2'] |
| 223 |
match_groupdict: |
| 224 |
description: Dictionary containing all the named subgroups of the match, keyed by the subgroup name, |
| 225 |
as returned by U(https://docs.python.org/3/library/re.html#re.Match.groupdict) |
| 226 |
returned: always |
| 227 |
type: dict |
| 228 |
sample: |
| 229 |
{ |
| 230 |
'group': 'match' |
| 231 |
} |
| 232 |
""" |
| 233 |
|
| 234 |
import binascii |
| 235 |
import contextlib |
| 236 |
import errno |
| 237 |
import math |
| 238 |
import mmap |
| 239 |
import os |
| 240 |
import re |
| 241 |
import select |
| 242 |
import socket |
| 243 |
import time |
| 244 |
|
| 245 |
from datetime import datetime, timedelta, timezone |
| 246 |
|
| 247 |
from ansible.module_utils.basic import AnsibleModule, missing_required_lib |
| 248 |
from ansible.module_utils.common.sys_info import get_platform_subclass |
| 249 |
from ansible.module_utils.common.text.converters import to_bytes, to_native |
| 250 |
|
| 251 |
|
| 252 |
HAS_PSUTIL = False |
| 253 |
PSUTIL_IMP_ERR = None |
| 254 |
try: |
| 255 |
import psutil |
| 256 |
HAS_PSUTIL = True |
| 257 |
# just because we can import it on Linux doesn't mean we will use it |
| 258 |
except ImportError as ex: |
| 259 |
PSUTIL_IMP_ERR = ex |
| 260 |
|
| 261 |
|
| 262 |
class TCPConnectionInfo(object): |
| 263 |
""" |
| 264 |
This is a generic TCP Connection Info strategy class that relies |
| 265 |
on the psutil module, which is not ideal for targets, but necessary |
| 266 |
for cross platform support. |
| 267 |
|
| 268 |
A subclass may wish to override some or all of these methods. |
| 269 |
- _get_exclude_ips() |
| 270 |
- get_active_connections() |
| 271 |
|
| 272 |
All subclasses MUST define platform and distribution (which may be None). |
| 273 |
""" |
| 274 |
platform = 'Generic' |
| 275 |
distribution = None |
| 276 |
|
| 277 |
match_all_ips = { |
| 278 |
socket.AF_INET: '0.0.0.0', |
| 279 |
socket.AF_INET6: '::', |
| 280 |
} |
| 281 |
ipv4_mapped_ipv6_address = { |
| 282 |
'prefix': '::ffff', |
| 283 |
'match_all': '::ffff:0.0.0.0' |
| 284 |
} |
| 285 |
|
| 286 |
def __new__(cls, *args, **kwargs): |
| 287 |
new_cls = get_platform_subclass(TCPConnectionInfo) |
| 288 |
return super(cls, new_cls).__new__(new_cls) |
| 289 |
|
| 290 |
def __init__(self, module): |
| 291 |
self.module = module |
| 292 |
self.ips = _convert_host_to_ip(module.params['host']) |
| 293 |
self.port = int(self.module.params['port']) |
| 294 |
self.exclude_ips = self._get_exclude_ips() |
| 295 |
if not HAS_PSUTIL: |
| 296 |
module.fail_json(msg=missing_required_lib('psutil'), exception=PSUTIL_IMP_ERR) |
| 297 |
|
| 298 |
def _get_exclude_ips(self): |
| 299 |
exclude_hosts = self.module.params['exclude_hosts'] |
| 300 |
exclude_ips = [] |
| 301 |
if exclude_hosts is not None: |
| 302 |
for host in exclude_hosts: |
| 303 |
exclude_ips.extend(_convert_host_to_ip(host)) |
| 304 |
return exclude_ips |
| 305 |
|
| 306 |
def get_active_connections_count(self): |
| 307 |
active_connections = 0 |
| 308 |
for p in psutil.process_iter(): |
| 309 |
try: |
| 310 |
if hasattr(p, 'get_connections'): |
| 311 |
connections = p.get_connections(kind='inet') |
| 312 |
else: |
| 313 |
connections = p.connections(kind='inet') |
| 314 |
except psutil.Error: |
| 315 |
# Process is Zombie or other error state |
| 316 |
continue |
| 317 |
for conn in connections: |
| 318 |
if conn.status not in self.module.params['active_connection_states']: |
| 319 |
continue |
| 320 |
if hasattr(conn, 'local_address'): |
| 321 |
(local_ip, local_port) = conn.local_address |
| 322 |
else: |
| 323 |
(local_ip, local_port) = conn.laddr |
| 324 |
if self.port != local_port: |
| 325 |
continue |
| 326 |
if hasattr(conn, 'remote_address'): |
| 327 |
(remote_ip, remote_port) = conn.remote_address |
| 328 |
else: |
| 329 |
(remote_ip, remote_port) = conn.raddr |
| 330 |
if (conn.family, remote_ip) in self.exclude_ips: |
| 331 |
continue |
| 332 |
if any(( |
| 333 |
(conn.family, local_ip) in self.ips, |
| 334 |
(conn.family, self.match_all_ips[conn.family]) in self.ips, |
| 335 |
local_ip.startswith(self.ipv4_mapped_ipv6_address['prefix']) and |
| 336 |
(conn.family, self.ipv4_mapped_ipv6_address['match_all']) in self.ips, |
| 337 |
)): |
| 338 |
active_connections += 1 |
| 339 |
return active_connections |
| 340 |
|
| 341 |
|
| 342 |
# =========================================== |
| 343 |
# Subclass: Linux |
| 344 |
|
| 345 |
class LinuxTCPConnectionInfo(TCPConnectionInfo): |
| 346 |
""" |
| 347 |
This is a TCP Connection Info evaluation strategy class |
| 348 |
that utilizes information from Linux's procfs. While less universal, |
| 349 |
does allow Linux targets to not require an additional library. |
| 350 |
""" |
| 351 |
platform = 'Linux' |
| 352 |
distribution = None |
| 353 |
|
| 354 |
source_file = { |
| 355 |
socket.AF_INET: '/proc/net/tcp', |
| 356 |
socket.AF_INET6: '/proc/net/tcp6' |
| 357 |
} |
| 358 |
match_all_ips = { |
| 359 |
socket.AF_INET: '00000000', |
| 360 |
socket.AF_INET6: '00000000000000000000000000000000', |
| 361 |
} |
| 362 |
ipv4_mapped_ipv6_address = { |
| 363 |
'prefix': '0000000000000000FFFF0000', |
| 364 |
'match_all': '0000000000000000FFFF000000000000' |
| 365 |
} |
| 366 |
local_address_field = 1 |
| 367 |
remote_address_field = 2 |
| 368 |
connection_state_field = 3 |
| 369 |
|
| 370 |
def __init__(self, module): |
| 371 |
self.module = module |
| 372 |
self.ips = _convert_host_to_hex(module.params['host']) |
| 373 |
self.port = "%0.4X" % int(module.params['port']) |
| 374 |
self.exclude_ips = self._get_exclude_ips() |
| 375 |
|
| 376 |
def _get_exclude_ips(self): |
| 377 |
exclude_hosts = self.module.params['exclude_hosts'] |
| 378 |
exclude_ips = [] |
| 379 |
if exclude_hosts is not None: |
| 380 |
for host in exclude_hosts: |
| 381 |
exclude_ips.extend(_convert_host_to_hex(host)) |
| 382 |
return exclude_ips |
| 383 |
|
| 384 |
def get_active_connections_count(self): |
| 385 |
active_connections = 0 |
| 386 |
for family in self.source_file.keys(): |
| 387 |
if not os.path.isfile(self.source_file[family]): |
| 388 |
continue |
| 389 |
try: |
| 390 |
with open(self.source_file[family]) as f: |
| 391 |
for tcp_connection in f.readlines(): |
| 392 |
tcp_connection = tcp_connection.strip().split() |
| 393 |
if tcp_connection[self.local_address_field] == 'local_address': |
| 394 |
continue |
| 395 |
if (tcp_connection[self.connection_state_field] not in |
| 396 |
[get_connection_state_id(_connection_state) for _connection_state in self.module.params['active_connection_states']]): |
| 397 |
continue |
| 398 |
(local_ip, local_port) = tcp_connection[self.local_address_field].split(':') |
| 399 |
if self.port != local_port: |
| 400 |
continue |
| 401 |
(remote_ip, remote_port) = tcp_connection[self.remote_address_field].split(':') |
| 402 |
if (family, remote_ip) in self.exclude_ips: |
| 403 |
continue |
| 404 |
if any(( |
| 405 |
(family, local_ip) in self.ips, |
| 406 |
(family, self.match_all_ips[family]) in self.ips, |
| 407 |
local_ip.startswith(self.ipv4_mapped_ipv6_address['prefix']) and |
| 408 |
(family, self.ipv4_mapped_ipv6_address['match_all']) in self.ips, |
| 409 |
)): |
| 410 |
active_connections += 1 |
| 411 |
except OSError: |
| 412 |
pass |
| 413 |
|
| 414 |
return active_connections |
| 415 |
|
| 416 |
|
| 417 |
def _convert_host_to_ip(host): |
| 418 |
""" |
| 419 |
Perform forward DNS resolution on host, IP will give the same IP |
| 420 |
|
| 421 |
Args: |
| 422 |
host: String with either hostname, IPv4, or IPv6 address |
| 423 |
|
| 424 |
Returns: |
| 425 |
List of tuples containing address family and IP |
| 426 |
""" |
| 427 |
addrinfo = socket.getaddrinfo(host, 80, 0, 0, socket.SOL_TCP) |
| 428 |
ips = [] |
| 429 |
for family, socktype, proto, canonname, sockaddr in addrinfo: |
| 430 |
ip = sockaddr[0] |
| 431 |
ips.append((family, ip)) |
| 432 |
if family == socket.AF_INET: |
| 433 |
ips.append((socket.AF_INET6, "::ffff:" + ip)) |
| 434 |
return ips |
| 435 |
|
| 436 |
|
| 437 |
def _convert_host_to_hex(host): |
| 438 |
""" |
| 439 |
Convert the provided host to the format in /proc/net/tcp* |
| 440 |
|
| 441 |
/proc/net/tcp uses little-endian four byte hex for ipv4 |
| 442 |
/proc/net/tcp6 uses little-endian per 4B word for ipv6 |
| 443 |
|
| 444 |
Args: |
| 445 |
host: String with either hostname, IPv4, or IPv6 address |
| 446 |
|
| 447 |
Returns: |
| 448 |
List of tuples containing address family and the |
| 449 |
little-endian converted host |
| 450 |
""" |
| 451 |
ips = [] |
| 452 |
if host is not None: |
| 453 |
for family, ip in _convert_host_to_ip(host): |
| 454 |
hexip_nf = binascii.b2a_hex(socket.inet_pton(family, ip)) |
| 455 |
hexip_hf = "" |
| 456 |
for i in range(0, len(hexip_nf), 8): |
| 457 |
ipgroup_nf = hexip_nf[i:i + 8] |
| 458 |
ipgroup_hf = socket.ntohl(int(ipgroup_nf, base=16)) |
| 459 |
hexip_hf = "%s%08X" % (hexip_hf, ipgroup_hf) |
| 460 |
ips.append((family, hexip_hf)) |
| 461 |
return ips |
| 462 |
|
| 463 |
|
| 464 |
def _timedelta_total_seconds(timedelta): |
| 465 |
return ( |
| 466 |
timedelta.microseconds + 0.0 + |
| 467 |
(timedelta.seconds + timedelta.days * 24 * 3600) * 10 ** 6) / 10 ** 6 |
| 468 |
|
| 469 |
|
| 470 |
def get_connection_state_id(state): |
| 471 |
connection_state_id = { |
| 472 |
'ESTABLISHED': '01', |
| 473 |
'SYN_SENT': '02', |
| 474 |
'SYN_RECV': '03', |
| 475 |
'FIN_WAIT1': '04', |
| 476 |
'FIN_WAIT2': '05', |
| 477 |
'TIME_WAIT': '06', |
| 478 |
} |
| 479 |
return connection_state_id[state] |
| 480 |
|
| 481 |
|
| 482 |
def main(): |
| 483 |
|
| 484 |
module = AnsibleModule( |
| 485 |
argument_spec=dict( |
| 486 |
host=dict(type='str', default='127.0.0.1'), |
| 487 |
timeout=dict(type='int', default=300), |
| 488 |
connect_timeout=dict(type='int', default=5), |
| 489 |
delay=dict(type='int', default=0), |
| 490 |
port=dict(type='int'), |
| 491 |
active_connection_states=dict(type='list', elements='str', default=['ESTABLISHED', 'FIN_WAIT1', 'FIN_WAIT2', 'SYN_RECV', 'SYN_SENT', 'TIME_WAIT']), |
| 492 |
path=dict(type='path'), |
| 493 |
search_regex=dict(type='str'), |
| 494 |
state=dict(type='str', default='started', choices=['absent', 'drained', 'present', 'started', 'stopped']), |
| 495 |
exclude_hosts=dict(type='list', elements='str'), |
| 496 |
sleep=dict(type='int', default=1), |
| 497 |
msg=dict(type='str'), |
| 498 |
), |
| 499 |
) |
| 500 |
|
| 501 |
host = module.params['host'] |
| 502 |
timeout = module.params['timeout'] |
| 503 |
connect_timeout = module.params['connect_timeout'] |
| 504 |
delay = module.params['delay'] |
| 505 |
port = module.params['port'] |
| 506 |
state = module.params['state'] |
| 507 |
|
| 508 |
path = module.params['path'] |
| 509 |
b_path = to_bytes(path, errors='surrogate_or_strict', nonstring='passthru') |
| 510 |
|
| 511 |
search_regex = module.params['search_regex'] |
| 512 |
b_search_regex = to_bytes(search_regex, errors='surrogate_or_strict', nonstring='passthru') |
| 513 |
|
| 514 |
msg = module.params['msg'] |
| 515 |
|
| 516 |
if search_regex is not None: |
| 517 |
try: |
| 518 |
b_compiled_search_re = re.compile(b_search_regex, re.MULTILINE) |
| 519 |
except re.error as e: |
| 520 |
module.fail_json(msg="Invalid regular expression: %s" % e) |
| 521 |
else: |
| 522 |
b_compiled_search_re = None |
| 523 |
|
| 524 |
match_groupdict = {} |
| 525 |
match_groups = () |
| 526 |
|
| 527 |
if port and path: |
| 528 |
module.fail_json(msg="port and path parameter can not both be passed to wait_for", elapsed=0) |
| 529 |
if path and state == 'stopped': |
| 530 |
module.fail_json(msg="state=stopped should only be used for checking a port in the wait_for module", elapsed=0) |
| 531 |
if path and state == 'drained': |
| 532 |
module.fail_json(msg="state=drained should only be used for checking a port in the wait_for module", elapsed=0) |
| 533 |
if module.params['exclude_hosts'] is not None and state != 'drained': |
| 534 |
module.fail_json(msg="exclude_hosts should only be with state=drained", elapsed=0) |
| 535 |
for _connection_state in module.params['active_connection_states']: |
| 536 |
try: |
| 537 |
get_connection_state_id(_connection_state) |
| 538 |
except Exception: |
| 539 |
module.fail_json(msg="unknown active_connection_state (%s) defined" % _connection_state, elapsed=0) |
| 540 |
|
| 541 |
start = datetime.now(timezone.utc) |
| 542 |
|
| 543 |
if delay: |
| 544 |
time.sleep(delay) |
| 545 |
|
| 546 |
if not port and not path and state != 'drained': |
| 547 |
time.sleep(timeout) |
| 548 |
elif state in ['absent', 'stopped']: |
| 549 |
# first wait for the stop condition |
| 550 |
end = start + timedelta(seconds=timeout) |
| 551 |
|
| 552 |
while datetime.now(timezone.utc) < end: |
| 553 |
if path: |
| 554 |
try: |
| 555 |
if not os.access(b_path, os.F_OK): |
| 556 |
break |
| 557 |
except OSError: |
| 558 |
break |
| 559 |
elif port: |
| 560 |
try: |
| 561 |
s = socket.create_connection((host, port), connect_timeout) |
| 562 |
s.shutdown(socket.SHUT_RDWR) |
| 563 |
s.close() |
| 564 |
except Exception: |
| 565 |
break |
| 566 |
# Conditions not yet met, wait and try again |
| 567 |
time.sleep(module.params['sleep']) |
| 568 |
else: |
| 569 |
elapsed = datetime.now(timezone.utc) - start |
| 570 |
if port: |
| 571 |
module.fail_json(msg=msg or "Timeout when waiting for %s:%s to stop." % (host, port), elapsed=elapsed.seconds) |
| 572 |
elif path: |
| 573 |
module.fail_json(msg=msg or "Timeout when waiting for %s to be absent." % (path), elapsed=elapsed.seconds) |
| 574 |
|
| 575 |
elif state in ['started', 'present']: |
| 576 |
# wait for start condition |
| 577 |
end = start + timedelta(seconds=timeout) |
| 578 |
while datetime.now(timezone.utc) < end: |
| 579 |
if path: |
| 580 |
try: |
| 581 |
os.stat(b_path) |
| 582 |
except OSError as e: |
| 583 |
# If anything except file not present, throw an error |
| 584 |
if e.errno != errno.ENOENT: |
| 585 |
elapsed = datetime.now(timezone.utc) - start |
| 586 |
module.fail_json(msg=msg or "Failed to stat %s, %s" % (path, e.strerror), elapsed=elapsed.seconds) |
| 587 |
# file doesn't exist yet, so continue |
| 588 |
else: |
| 589 |
# File exists. Are there additional things to check? |
| 590 |
if not b_compiled_search_re: |
| 591 |
# nope, succeed! |
| 592 |
break |
| 593 |
|
| 594 |
try: |
| 595 |
with open(b_path, 'rb') as f: |
| 596 |
try: |
| 597 |
with contextlib.closing(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as mm: |
| 598 |
search = b_compiled_search_re.search(mm) |
| 599 |
if search: |
| 600 |
if search.groupdict(): |
| 601 |
match_groupdict = search.groupdict() |
| 602 |
if search.groups(): |
| 603 |
match_groups = search.groups() |
| 604 |
break |
| 605 |
except (ValueError, OSError) as e: |
| 606 |
module.debug('wait_for failed to use mmap on "%s": %s. Falling back to file read().' % (path, to_native(e))) |
| 607 |
# cannot mmap this file, try normal read |
| 608 |
search = re.search(b_compiled_search_re, f.read()) |
| 609 |
if search: |
| 610 |
if search.groupdict(): |
| 611 |
match_groupdict = search.groupdict() |
| 612 |
if search.groups(): |
| 613 |
match_groups = search.groups() |
| 614 |
break |
| 615 |
except Exception as e: |
| 616 |
module.warn('wait_for failed on "%s", unexpected exception(%s): %s.).' % (path, to_native(e.__class__), to_native(e))) |
| 617 |
except OSError: |
| 618 |
pass |
| 619 |
elif port: |
| 620 |
alt_connect_timeout = math.ceil( |
| 621 |
_timedelta_total_seconds(end - datetime.now(timezone.utc)), |
| 622 |
) |
| 623 |
try: |
| 624 |
s = socket.create_connection((host, int(port)), min(connect_timeout, alt_connect_timeout)) |
| 625 |
except Exception: |
| 626 |
# Failed to connect by connect_timeout. wait and try again |
| 627 |
pass |
| 628 |
else: |
| 629 |
# Connected -- are there additional conditions? |
| 630 |
if b_compiled_search_re: |
| 631 |
b_data = b'' |
| 632 |
matched = False |
| 633 |
while datetime.now(timezone.utc) < end: |
| 634 |
max_timeout = math.ceil( |
| 635 |
_timedelta_total_seconds( |
| 636 |
end - datetime.now(timezone.utc), |
| 637 |
), |
| 638 |
) |
| 639 |
readable = select.select([s], [], [], max_timeout)[0] |
| 640 |
if not readable: |
| 641 |
# No new data. Probably means our timeout |
| 642 |
# expired |
| 643 |
continue |
| 644 |
response = s.recv(1024) |
| 645 |
if not response: |
| 646 |
# Server shutdown |
| 647 |
break |
| 648 |
b_data += response |
| 649 |
if b_compiled_search_re.search(b_data): |
| 650 |
matched = True |
| 651 |
break |
| 652 |
|
| 653 |
# Shutdown the client socket |
| 654 |
try: |
| 655 |
s.shutdown(socket.SHUT_RDWR) |
| 656 |
except OSError as ex: |
| 657 |
if ex.errno != errno.ENOTCONN: |
| 658 |
raise |
| 659 |
# else, the server broke the connection on its end, assume it's not ready |
| 660 |
else: |
| 661 |
s.close() |
| 662 |
if matched: |
| 663 |
# Found our string, success! |
| 664 |
break |
| 665 |
else: |
| 666 |
# Connection established, success! |
| 667 |
try: |
| 668 |
s.shutdown(socket.SHUT_RDWR) |
| 669 |
except OSError as ex: |
| 670 |
if ex.errno != errno.ENOTCONN: |
| 671 |
raise |
| 672 |
# else, the server broke the connection on its end, assume it's not ready |
| 673 |
else: |
| 674 |
s.close() |
| 675 |
break |
| 676 |
|
| 677 |
# Conditions not yet met, wait and try again |
| 678 |
time.sleep(module.params['sleep']) |
| 679 |
|
| 680 |
else: # while-else |
| 681 |
# Timeout expired |
| 682 |
elapsed = datetime.now(timezone.utc) - start |
| 683 |
if port: |
| 684 |
if search_regex: |
| 685 |
module.fail_json(msg=msg or "Timeout when waiting for search string %s in %s:%s" % (search_regex, host, port), elapsed=elapsed.seconds) |
| 686 |
else: |
| 687 |
module.fail_json(msg=msg or "Timeout when waiting for %s:%s" % (host, port), elapsed=elapsed.seconds) |
| 688 |
elif path: |
| 689 |
if search_regex: |
| 690 |
module.fail_json(msg=msg or "Timeout when waiting for search string %s in %s" % (search_regex, path), elapsed=elapsed.seconds) |
| 691 |
else: |
| 692 |
module.fail_json(msg=msg or "Timeout when waiting for file %s" % (path), elapsed=elapsed.seconds) |
| 693 |
|
| 694 |
elif state == 'drained': |
| 695 |
# wait until all active connections are gone |
| 696 |
end = start + timedelta(seconds=timeout) |
| 697 |
tcpconns = TCPConnectionInfo(module) |
| 698 |
while datetime.now(timezone.utc) < end: |
| 699 |
if tcpconns.get_active_connections_count() == 0: |
| 700 |
break |
| 701 |
|
| 702 |
# Conditions not yet met, wait and try again |
| 703 |
time.sleep(module.params['sleep']) |
| 704 |
else: |
| 705 |
elapsed = datetime.now(timezone.utc) - start |
| 706 |
module.fail_json(msg=msg or "Timeout when waiting for %s:%s to drain" % (host, port), elapsed=elapsed.seconds) |
| 707 |
|
| 708 |
elapsed = datetime.now(timezone.utc) - start |
| 709 |
module.exit_json(state=state, port=port, search_regex=search_regex, match_groups=match_groups, match_groupdict=match_groupdict, path=path, |
| 710 |
elapsed=elapsed.seconds) |
| 711 |
|
| 712 |
|
| 713 |
if __name__ == '__main__': |
| 714 |
main() |