o nnhj@sBddlmZdZdZdZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlmZmZddlmZddlmZmZdd lmZd ZdZzddlZd ZWn eyqeZYnwGd d d e Z!Gddde!Z"ddZ#ddZ$ddZ%ddZ&ddZ'e(dkre'dSdS)) annotationsa --- module: wait_for short_description: Waits for a condition before continuing description: - 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. This does not produce an error. - 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 useful when starting guests with the M(community.libvirt.virt) module and needing to pause until they are ready. - This module can also be used to wait for a regex match a string to be present in a file. - In Ansible 1.6 and later, this module can also be used to wait for a file to be available or absent on the filesystem. - 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 is being rotated out of a load balancer pool. - For Windows targets, use the M(ansible.windows.win_wait_for) module instead. version_added: "0.7" options: host: description: - A resolvable hostname or IP address to wait for. type: str default: 127.0.0.1 timeout: description: - Maximum number of seconds to wait for, when used with another condition it will force an error. - When used without other conditions it is equivalent of just sleeping. type: int default: 300 connect_timeout: description: - Maximum number of seconds to wait for a connection to happen before closing and retrying. type: int default: 5 delay: description: - Number of seconds to wait before starting to poll. type: int default: 0 port: description: - Port number to poll. - O(path) and O(port) are mutually exclusive parameters. type: int active_connection_states: description: - The list of TCP connection states which are counted as active connections. type: list elements: str default: [ ESTABLISHED, FIN_WAIT1, FIN_WAIT2, SYN_RECV, SYN_SENT, TIME_WAIT ] version_added: "2.3" state: description: - Either V(present), V(started), or V(stopped), V(absent), or V(drained). - 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. - 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, V(absent) will check that file is absent or removed. type: str choices: [ absent, drained, present, started, stopped ] default: started path: description: - Path to a file on the filesystem that must exist before continuing. - O(path) and O(port) are mutually exclusive parameters. type: path version_added: "1.4" search_regex: description: - Can be used to match a string in either a file or a socket connection. - Defaults to a multiline regex. type: str version_added: "1.4" exclude_hosts: description: - List of hosts or IPs to ignore when looking for active TCP connections for V(drained) state. type: list elements: str version_added: "1.8" sleep: description: - Number of seconds to sleep between checks. - Before Ansible 2.3 this was hardcoded to 1 second. type: int default: 1 version_added: "2.3" msg: description: - This overrides the normal error message from a failure to meet the required conditions. type: str version_added: "2.4" extends_documentation_fragment: action_common_attributes attributes: check_mode: support: none diff_mode: support: none platform: platforms: posix notes: - The ability to use search_regex with a port connection was added in Ansible 1.7. - Prior to Ansible 2.4, testing for the absence of a directory or UNIX socket did not work correctly. - Prior to Ansible 2.4, testing for the presence of a file did not work correctly if the remote user did not have read access to that file. - Under some circumstances when using mandatory access control, a path may always be treated as being absent even if it exists, but can't be modified or created by the remote user either. - When waiting for a path, symbolic links will be followed. Many other modules that manipulate files do not follow symbolic links, so operations on the path using other modules may not work exactly as expected. seealso: - module: ansible.builtin.wait_for_connection - module: ansible.windows.win_wait_for - module: community.windows.win_wait_for_process author: - Jeroen Hoekx (@jhoekx) - John Jarvis (@jarv) - Andrii Radyk (@AnderEnder) a - name: Sleep for 300 seconds and continue with play ansible.builtin.wait_for: timeout: 300 delegate_to: localhost - name: Wait for port 8000 to become open on the host, don't start checking for 10 seconds ansible.builtin.wait_for: port: 8000 delay: 10 - name: Waits for port 8000 of any IP to close active connections, don't start checking for 10 seconds ansible.builtin.wait_for: host: 0.0.0.0 port: 8000 delay: 10 state: drained - name: Wait for port 8000 of any IP to close active connections, ignoring connections for specified hosts ansible.builtin.wait_for: host: 0.0.0.0 port: 8000 state: drained exclude_hosts: 10.2.1.2,10.2.1.3 - name: Wait until the file /tmp/foo is present before continuing ansible.builtin.wait_for: path: /tmp/foo - name: Wait until the string "completed" is in the file /tmp/foo before continuing ansible.builtin.wait_for: path: /tmp/foo search_regex: completed - name: Wait until regex pattern matches in the file /tmp/foo and print the matched group ansible.builtin.wait_for: path: /tmp/foo search_regex: completed (?P\w+) register: waitfor - ansible.builtin.debug: msg: Completed {{ waitfor['match_groupdict']['task'] }} - name: Wait until the lock file is removed ansible.builtin.wait_for: path: /var/lock/file.lock state: absent - name: Wait until the process is finished and pid was destroyed ansible.builtin.wait_for: path: /proc/3466/status state: absent - name: Output customized message when failed ansible.builtin.wait_for: path: /tmp/foo state: present msg: Timeout to find file /tmp/foo # Do not assume the inventory_hostname is resolvable and delay 10 seconds at start - name: Wait 300 seconds for port 22 to become open and contain "OpenSSH" ansible.builtin.wait_for: port: 22 host: '{{ (ansible_ssh_host|default(ansible_host))|default(inventory_hostname) }}' search_regex: OpenSSH delay: 10 timeout: 300 delegate_to: localhost # Same as above but using config lookup for the target, # most plugins use 'remote_addr', but ssh uses 'host' - name: Wait 300 seconds for port 22 to become open and contain "OpenSSH" ansible.builtin.wait_for: port: 22 host: "{{ lookup('config', 'host', plugin_name='ssh', plugin_type='connection') }}" search_regex: OpenSSH delay: 10 timeout: 300 delegate_to: localhost at elapsed: description: The number of seconds that elapsed while waiting returned: always type: int sample: 23 match_groups: description: Tuple containing all the subgroups of the match as returned by U(https://docs.python.org/3/library/re.html#re.MatchObject.groups) returned: always type: list sample: ['match 1', 'match 2'] match_groupdict: description: Dictionary containing all the named subgroups of the match, keyed by the subgroup name, as returned by U(https://docs.python.org/3/library/re.html#re.MatchObject.groupdict) returned: always type: dict sample: { 'group': 'match' } N) AnsibleModulemissing_required_lib)get_platform_subclass)to_bytes to_native)utcnowFTcsZeZdZdZdZdZejdejdiZ dddZ fd d Z d d Z d dZ ddZZS)TCPConnectionInfoa 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). GenericNz0.0.0.0z::z::ffffz::ffff:0.0.0.0prefix match_allcstt}t|||S)N)rr super__new__)clsargskwargsnew_cls __class__C/usr/local/lib/python3.10/dist-packages/ansible/modules/wait_for.pyrszTCPConnectionInfo.__new__cCsP||_t|jd|_t|jjd|_||_ts&|j t dt ddSdS)Nhostportpsutil)msg exception) module_convert_host_to_ipparamsipsintr_get_exclude_ips exclude_ips HAS_PSUTIL fail_jsonrPSUTIL_IMP_ERRselfrrrr__init__s zTCPConnectionInfo.__init__cC4|jjd}g}|dur|D] }|t|q|SN exclude_hosts)rrextendrr(r,r#rrrrr"$ z"TCPConnectionInfo._get_exclude_ipsc Cs(d}tD]}zt|dr|jdd}n|jdd}Wn tjy&Yqw|D]g}|j|jjdvr5q)t|dr@|j \}}n|j \}}|j |krKq)t|drV|j \}}n|j \}}|j|f|jvrdq)t|j|f|jv|j|j|jf|jv||jdo|j|jd f|jvfr|d 7}q)q|S) Nrget_connectionsinet)kindactive_connection_states local_addressremote_addressr r )r process_iterhasattrr0 connectionsErrorstatusrrr4laddrrr5raddrfamilyr#anyr match_all_ips startswithipv4_mapped_ipv6_address) r(active_connectionspr9connlocal_ip local_port remote_ip remote_portrrrget_active_connections_count,sB          z.TCPConnectionInfo.get_active_connections_count)__name__ __module__ __qualname____doc__platform distributionsocketAF_INETAF_INET6r@rBrr)r"rJ __classcell__rrrrr s  r c@sfeZdZdZdZdZejdejdiZ ejdejdiZ dd d Z d Z d Z d ZddZddZddZdS)LinuxTCPConnectionInfoz 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. LinuxNz /proc/net/tcpz/proc/net/tcp600000000 000000000000000000000000000000000000000000000000FFFF0000 0000000000000000FFFF000000000000r r6cCs8||_t|jd|_dt|jd|_||_dS)Nrz%0.4Xr)r_convert_host_to_hexrr r!rr"r#r'rrrr)lszLinuxTCPConnectionInfo.__init__cCr*r+)rrr-r]r.rrrr"rr/z'LinuxTCPConnectionInfo._get_exclude_ipsc CsZd}|jD]}tj|j|sqzzyt|j|}|D]k}|}||j dkr0q ||j dd|j j dDvrAq ||j d\}}|j |krQq ||jd\}}||f|jvrcq t||f|jv||j|f|jv||jdo||jdf|jvfr|d 7}q Wnty} zWYd} ~ nd} ~ wwW|q|w|S) Nrr4cSsg|]}t|qSr)get_connection_state_id).0_connection_staterrr szGLinuxTCPConnectionInfo.get_active_connections_count..r3:r r r6) source_filekeysospathisfileopen readlinesstripsplitlocal_address_fieldconnection_state_fieldrrrremote_address_fieldr#r?r r@rArBIOErrorclose) r(rCr>ftcp_connectionrFrGrHrIerrrrJzsH     z3LinuxTCPConnectionInfo.get_active_connections_count)rKrLrMrNrOrPrQrRrSrcr@rBrlrnrmr)r"rJrrrrrUSs& rUc Csdt|dddtj}g}|D]!\}}}}}|d}|||f|tjkr/|tjd|fq|S)z Perform forward DNS resolution on host, IP will give the same IP Args: host: String with either hostname, IPv4, or IPv6 address Returns: List of tuples containing address family and IP Prz::ffff:)rQ getaddrinfoSOL_TCPappendrRrS) raddrinfor r>socktypeproto canonnamesockaddriprrrrs  rc Csg}|durCt|D]8\}}tt||}d}tdt|dD]}|||d}tt|dd}d||f}q!| ||fq |S)as 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: List of tuples containing address family and the little-endian converted host Nr)basez%s%08X) rbinasciib2a_hexrQ inet_ptonrangelenntohlr!rw) rr r>r}hexip_nfhexip_hfi ipgroup_nf ipgroup_hfrrrr]sr]cCs&|jd|j|jddddS)Ngii@B) microsecondssecondsdays) timedeltarrr_timedelta_total_secondss rcCsddddddd}||S)N010203040506) ESTABLISHEDSYN_SENTSYN_RECV FIN_WAIT1 FIN_WAIT2 TIME_WAITr)stateconnection_state_idrrrr^sr^cCstttdddtdddtdddtdddtddtd dgd d td dtddtdd gddtd ddtdddtddd d}|jd}|jd}|jd}|jd}|jd}|jd}|jd }t|ddd}|jd} t| ddd} |jd} | durz t| tj} Wntjy} z|jd| d WYd} ~ nd} ~ wwd} i}d!}|r|r|jd"dd#|r|d$kr|jd%dd#|r|d&kr|jd'dd#|jd(dur|d&kr|jd)dd#|jd*D]}zt |Wqt y|jd+|dd#Yqwt }|rt ||s$|s$|d&kr$t |n|d,vr|tj|d-}t |kr|rQz t|tjsEWneWn,tyPYnZw|rszt||f|}|tj|Wn t yrYn8wt |jd.t |ks7t |}|r|j| pd/||f|jd#n|r|j| pd0||jd#n|d1vr|tj|d-}t |kr|rzt|Wn/ty} z"| jd2krt |}|j| pd3|| jf|jd#WYd} ~ nd} ~ ww| snzt|d4}zLt t!j!|"dt!j#d53}| $|}|r@|%r&|%}|&r/|&} WdWWdWnWdn 1sKwYWnlt'tfy} z<|(d6|t)| ft$| |*}|r|%r{|%}|&r|&}WYd} ~ WdWnWYd} ~ n&d} ~ wt y} z|+d7|t)| j,t)| fWYd} ~ nd} ~ wwWdn 1swYWntyYnw|rt-.t/|t }z t||ft0||}Wn t yYnw| rpd8}d9}t |krBt-.t/|t }t11|ggg|d}|s&q|2d:}|s/n||7}| $|r| |f|jd#nO|j| pd?||jd#nA|d&kr9|tj|d-}t4|}t |kr%|5dkrn"t |jd.t |kst |}|j| p4d@||f|jd#t |}|j6||| ||||jdAdS)BNstrz 127.0.0.1)typedefaultr!i,r)rlist)rrrrrr)relementsrrfstarted)absentdrainedpresentrstopped)rrchoices)rrr6) rtimeoutconnect_timeoutdelayrr3rf search_regexrr,sleepr) argument_specrrrrrrsurrogate_or_strictpassthru)errors nonstringrrzInvalid regular expression: %s)rrz:port and path parameter can not both be passed to wait_for)relapsedrzLstate=stopped should only be used for checking a port in the wait_for modulerzLstate=drained should only be used for checking a port in the wait_for moduler,z/exclude_hosts should only be with state=drainedr3z,unknown active_connection_state (%s) defined)rr)rrz'Timeout when waiting for %s:%s to stop.z)Timeout when waiting for %s to be absent.)rrr[zFailed to stat %s, %srb)accesszEwait_for failed to use mmap on "%s": %s. Falling back to file read().z8wait_for failed on "%s", unexpected exception(%s): %s.).FiTz2Timeout when waiting for search string %s in %s:%szTimeout when waiting for %s:%sz/Timeout when waiting for search string %s in %sz Timeout when waiting for file %sz'Timeout when waiting for %s:%s to drain)rrr match_groupsmatch_groupdictrfr)7rdictrrrecompile MULTILINEerrorr%r^ ExceptionrtimerdatetimerrerF_OKrorQcreate_connectionshutdown SHUT_RDWRrprstatOSErrorerrnostrerrorrh contextlibclosingmmapfileno ACCESS_READsearch groupdictgroups ValueErrordebugrreadwarnrmathceilrminselectrecvENOTCONNr rJ exit_json)rrrrrrrrfb_pathrb_search_regexrb_compiled_search_rersrrr`startendsrrqmmralt_connect_timeoutb_datamatched max_timeoutreadableresponsetcpconnsrrrmains                        "             *       b"       r__main__)) __future__r DOCUMENTATIONEXAMPLESRETURNrrrrrrrerrrQr tracebackansible.module_utils.basicrr$ansible.module_utils.common.sys_infor+ansible.module_utils.common.text.convertersrr$ansible.module_utils.compat.datetimerr$r&r ImportError format_excobjectr rUrr]rr^rrKrrrrsN tP    SJ b