Add elapsed return value to select modules (#37969)

* Add elapsed return value to select modules

It can be quite useful to know exactly how much time has elapsed
downloading/waiting. This improves existing modules or updates
documentation.

* Ensure elapsed is always returned

* Added changelog fragment
pull/45051/head
Dag Wieers 6 years ago committed by GitHub
parent af3bac1320
commit b64e666643
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -0,0 +1,3 @@
minor_changes:
- Now emits 'elapsed' as a return value for get_url, uri and win_uri
- Ensures 'elapsed' is always returned, when timed out or failed

@ -1,7 +1,7 @@
#!/usr/bin/python #!/usr/bin/python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# (c) 2012, Jan-Piet Mens <jpmens () gmail.com> # Copyright: (c) 2012, Jan-Piet Mens <jpmens () gmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function from __future__ import absolute_import, division, print_function
@ -226,6 +226,11 @@ dest:
returned: success returned: success
type: string type: string
sample: /path/to/file.txt sample: /path/to/file.txt
elapsed:
description: The number of seconds that elapsed while performing the download
returned: always
type: int
sample: 23
gid: gid:
description: group id of the file description: group id of the file
returned: success returned: success
@ -268,7 +273,7 @@ size:
sample: 1220 sample: 1220
src: src:
description: source file used after download description: source file used after download
returned: changed returned: always
type: string type: string
sample: /tmp/tmpAdFLdV sample: /tmp/tmpAdFLdV
state: state:
@ -327,17 +332,19 @@ def url_get(module, url, dest, use_proxy, last_mod_time, force, timeout=10, head
else: else:
method = 'GET' method = 'GET'
start = datetime.datetime.utcnow()
rsp, info = fetch_url(module, url, use_proxy=use_proxy, force=force, last_mod_time=last_mod_time, timeout=timeout, headers=headers, method=method) rsp, info = fetch_url(module, url, use_proxy=use_proxy, force=force, last_mod_time=last_mod_time, timeout=timeout, headers=headers, method=method)
elapsed = (datetime.datetime.utcnow() - start).seconds
if info['status'] == 304: if info['status'] == 304:
module.exit_json(url=url, dest=dest, changed=False, msg=info.get('msg', '')) module.exit_json(url=url, dest=dest, changed=False, msg=info.get('msg', ''), elapsed=elapsed)
# Exceptions in fetch_url may result in a status -1, the ensures a proper error to the user in all cases # Exceptions in fetch_url may result in a status -1, the ensures a proper error to the user in all cases
if info['status'] == -1: if info['status'] == -1:
module.fail_json(msg=info['msg'], url=url, dest=dest) module.fail_json(msg=info['msg'], url=url, dest=dest, elapsed=elapsed)
if info['status'] != 200 and not url.startswith('file:/') and not (url.startswith('ftp:/') and info.get('msg', '').startswith('OK')): if info['status'] != 200 and not url.startswith('file:/') and not (url.startswith('ftp:/') and info.get('msg', '').startswith('OK')):
module.fail_json(msg="Request failed", status_code=info['status'], response=info['msg'], url=url, dest=dest) module.fail_json(msg="Request failed", status_code=info['status'], response=info['msg'], url=url, dest=dest, elapsed=elapsed)
# create a temporary file and copy content to do checksum-based replacement # create a temporary file and copy content to do checksum-based replacement
if tmp_dest: if tmp_dest:
@ -345,9 +352,9 @@ def url_get(module, url, dest, use_proxy, last_mod_time, force, timeout=10, head
tmp_dest_is_dir = os.path.isdir(tmp_dest) tmp_dest_is_dir = os.path.isdir(tmp_dest)
if not tmp_dest_is_dir: if not tmp_dest_is_dir:
if os.path.exists(tmp_dest): if os.path.exists(tmp_dest):
module.fail_json(msg="%s is a file but should be a directory." % tmp_dest) module.fail_json(msg="%s is a file but should be a directory." % tmp_dest, elapsed=elapsed)
else: else:
module.fail_json(msg="%s directory does not exist." % tmp_dest) module.fail_json(msg="%s directory does not exist." % tmp_dest, elapsed=elapsed)
else: else:
tmp_dest = module.tmpdir tmp_dest = module.tmpdir
@ -358,7 +365,7 @@ def url_get(module, url, dest, use_proxy, last_mod_time, force, timeout=10, head
shutil.copyfileobj(rsp, f) shutil.copyfileobj(rsp, f)
except Exception as e: except Exception as e:
os.remove(tempname) os.remove(tempname)
module.fail_json(msg="failed to create temporary content file: %s" % to_native(e), exception=traceback.format_exc()) module.fail_json(msg="failed to create temporary content file: %s" % to_native(e), elapsed=elapsed, exception=traceback.format_exc())
f.close() f.close()
rsp.close() rsp.close()
return tempname, info return tempname, info
@ -418,6 +425,15 @@ def main():
timeout = module.params['timeout'] timeout = module.params['timeout']
tmp_dest = module.params['tmp_dest'] tmp_dest = module.params['tmp_dest']
result = dict(
changed=False,
checksum_dest=None,
checksum_src=None,
dest=dest,
elapsed=0,
url=url,
)
# Parse headers to dict # Parse headers to dict
if isinstance(module.params['headers'], dict): if isinstance(module.params['headers'], dict):
headers = module.params['headers'] headers = module.params['headers']
@ -426,7 +442,7 @@ def main():
headers = dict(item.split(':', 1) for item in module.params['headers'].split(',')) headers = dict(item.split(':', 1) for item in module.params['headers'].split(','))
module.deprecate('Supplying `headers` as a string is deprecated. Please use dict/hash format for `headers`', version='2.10') module.deprecate('Supplying `headers` as a string is deprecated. Please use dict/hash format for `headers`', version='2.10')
except Exception: except Exception:
module.fail_json(msg="The string representation for the `headers` parameter requires a key:value,key:value syntax to be properly parsed.") module.fail_json(msg="The string representation for the `headers` parameter requires a key:value,key:value syntax to be properly parsed.", **result)
else: else:
headers = None headers = None
@ -456,7 +472,7 @@ def main():
# Ensure the checksum portion is a hexdigest # Ensure the checksum portion is a hexdigest
int(checksum, 16) int(checksum, 16)
except ValueError: except ValueError:
module.fail_json(msg="The checksum parameter has to be in format <algorithm>:<checksum>") module.fail_json(msg="The checksum parameter has to be in format <algorithm>:<checksum>", **result)
if not dest_is_dir and os.path.exists(dest): if not dest_is_dir and os.path.exists(dest):
checksum_mismatch = False checksum_mismatch = False
@ -472,10 +488,10 @@ def main():
module.params['path'] = dest module.params['path'] = dest
file_args = module.load_file_common_arguments(module.params) file_args = module.load_file_common_arguments(module.params)
file_args['path'] = dest file_args['path'] = dest
changed = module.set_fs_attributes_if_different(file_args, False) result['changed'] = module.set_fs_attributes_if_different(file_args, False)
if changed: if result['changed']:
module.exit_json(msg="file already exists but file attributes changed", dest=dest, url=url, changed=changed) module.exit_json(msg="file already exists but file attributes changed", **result)
module.exit_json(msg="file already exists", dest=dest, url=url, changed=changed) module.exit_json(msg="file already exists", **result)
checksum_mismatch = True checksum_mismatch = True
@ -490,7 +506,10 @@ def main():
force = True force = True
# download to tmpsrc # download to tmpsrc
start = datetime.datetime.utcnow()
tmpsrc, info = url_get(module, url, dest, use_proxy, last_mod_time, force, timeout, headers, tmp_dest) tmpsrc, info = url_get(module, url, dest, use_proxy, last_mod_time, force, timeout, headers, tmp_dest)
result['elapsed'] = (datetime.datetime.utcnow() - start).seconds
result['src'] = tmpsrc
# Now the request has completed, we can finally generate the final # Now the request has completed, we can finally generate the final
# destination file name from the info dict. # destination file name from the info dict.
@ -504,44 +523,41 @@ def main():
filename = url_filename(info['url']) filename = url_filename(info['url'])
dest = os.path.join(dest, filename) dest = os.path.join(dest, filename)
checksum_src = None
checksum_dest = None
# If the remote URL exists, we're done with check mode # If the remote URL exists, we're done with check mode
if module.check_mode: if module.check_mode:
os.remove(tmpsrc) os.remove(tmpsrc)
res_args = dict(url=url, dest=dest, src=tmpsrc, changed=True, msg=info.get('msg', '')) result['changed'] = True
module.exit_json(**res_args) module.exit_json(msg=info.get('msg', ''), **result)
# raise an error if there is no tmpsrc file # raise an error if there is no tmpsrc file
if not os.path.exists(tmpsrc): if not os.path.exists(tmpsrc):
os.remove(tmpsrc) os.remove(tmpsrc)
module.fail_json(msg="Request failed", status_code=info['status'], response=info['msg']) module.fail_json(msg="Request failed", status_code=info['status'], response=info['msg'], **result)
if not os.access(tmpsrc, os.R_OK): if not os.access(tmpsrc, os.R_OK):
os.remove(tmpsrc) os.remove(tmpsrc)
module.fail_json(msg="Source %s is not readable" % (tmpsrc)) module.fail_json(msg="Source %s is not readable" % (tmpsrc), **result)
checksum_src = module.sha1(tmpsrc) result['checksum_src'] = module.sha1(tmpsrc)
# check if there is no dest file # check if there is no dest file
if os.path.exists(dest): if os.path.exists(dest):
# raise an error if copy has no permission on dest # raise an error if copy has no permission on dest
if not os.access(dest, os.W_OK): if not os.access(dest, os.W_OK):
os.remove(tmpsrc) os.remove(tmpsrc)
module.fail_json(msg="Destination %s is not writable" % (dest)) module.fail_json(msg="Destination %s is not writable" % (dest), **result)
if not os.access(dest, os.R_OK): if not os.access(dest, os.R_OK):
os.remove(tmpsrc) os.remove(tmpsrc)
module.fail_json(msg="Destination %s is not readable" % (dest)) module.fail_json(msg="Destination %s is not readable" % (dest), **result)
checksum_dest = module.sha1(dest) result['checksum_dest'] = module.sha1(dest)
else: else:
if not os.path.exists(os.path.dirname(dest)): if not os.path.exists(os.path.dirname(dest)):
os.remove(tmpsrc) os.remove(tmpsrc)
module.fail_json(msg="Destination %s does not exist" % (os.path.dirname(dest))) module.fail_json(msg="Destination %s does not exist" % (os.path.dirname(dest)), **result)
if not os.access(os.path.dirname(dest), os.W_OK): if not os.access(os.path.dirname(dest), os.W_OK):
os.remove(tmpsrc) os.remove(tmpsrc)
module.fail_json(msg="Destination %s is not writable" % (os.path.dirname(dest))) module.fail_json(msg="Destination %s is not writable" % (os.path.dirname(dest)), **result)
backup_file = None backup_file = None
if checksum_src != checksum_dest: if result['checksum_src'] != result['checksum_dest']:
try: try:
if backup: if backup:
if os.path.exists(dest): if os.path.exists(dest):
@ -551,10 +567,10 @@ def main():
if os.path.exists(tmpsrc): if os.path.exists(tmpsrc):
os.remove(tmpsrc) os.remove(tmpsrc)
module.fail_json(msg="failed to copy %s to %s: %s" % (tmpsrc, dest, to_native(e)), module.fail_json(msg="failed to copy %s to %s: %s" % (tmpsrc, dest, to_native(e)),
exception=traceback.format_exc()) exception=traceback.format_exc(), **result)
changed = True result['changed'] = True
else: else:
changed = False result['changed'] = False
if os.path.exists(tmpsrc): if os.path.exists(tmpsrc):
os.remove(tmpsrc) os.remove(tmpsrc)
@ -563,29 +579,25 @@ def main():
if checksum != destination_checksum: if checksum != destination_checksum:
os.remove(dest) os.remove(dest)
module.fail_json(msg="The checksum for %s did not match %s; it was %s." % (dest, checksum, destination_checksum)) module.fail_json(msg="The checksum for %s did not match %s; it was %s." % (dest, checksum, destination_checksum), **result)
# allow file attribute changes # allow file attribute changes
module.params['path'] = dest module.params['path'] = dest
file_args = module.load_file_common_arguments(module.params) file_args = module.load_file_common_arguments(module.params)
file_args['path'] = dest file_args['path'] = dest
changed = module.set_fs_attributes_if_different(file_args, changed) result['changed'] = module.set_fs_attributes_if_different(file_args, result['changed'])
# Backwards compat only. We'll return None on FIPS enabled systems # Backwards compat only. We'll return None on FIPS enabled systems
try: try:
md5sum = module.md5(dest) result['md5sum'] = module.md5(dest)
except ValueError: except ValueError:
md5sum = None result['md5sum'] = None
res_args = dict(
url=url, dest=dest, src=tmpsrc, md5sum=md5sum, checksum_src=checksum_src,
checksum_dest=checksum_dest, changed=changed, msg=info.get('msg', ''), status_code=info.get('status', '')
)
if backup_file: if backup_file:
res_args['backup_file'] = backup_file result['backup_file'] = backup_file
# Mission complete # Mission complete
module.exit_json(**res_args) module.exit_json(msg=info.get('msg', ''), status_code=info.get('status', ''), **result)
if __name__ == '__main__': if __name__ == '__main__':

@ -54,8 +54,8 @@ options:
method: method:
description: description:
- The HTTP method of the request or response. It MUST be uppercase. - The HTTP method of the request or response. It MUST be uppercase.
choices: [ "GET", "POST", "PUT", "HEAD", "DELETE", "OPTIONS", "PATCH", "TRACE", "CONNECT", "REFRESH" ] choices: [ CONNECT, DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT, REFRESH, TRACE ]
default: "GET" default: GET
return_content: return_content:
description: description:
- Whether or not to return the body of the response as a "content" key in - Whether or not to return the body of the response as a "content" key in
@ -234,6 +234,11 @@ EXAMPLES = r'''
RETURN = r''' RETURN = r'''
# The return information includes all the HTTP headers in lower-case. # The return information includes all the HTTP headers in lower-case.
elapsed:
description: The number of seconds that elapsed while performing the download
returned: always
type: int
sample: 23
msg: msg:
description: The HTTP message from the request description: The HTTP message from the request
returned: always returned: always
@ -275,7 +280,7 @@ from ansible.module_utils.urls import fetch_url, url_argument_spec
JSON_CANDIDATES = ('text', 'json', 'javascript') JSON_CANDIDATES = ('text', 'json', 'javascript')
def write_file(module, url, dest, content): def write_file(module, url, dest, content, resp):
# create a tempfile with some test content # create a tempfile with some test content
fd, tmpsrc = tempfile.mkstemp(dir=module.tmpdir) fd, tmpsrc = tempfile.mkstemp(dir=module.tmpdir)
f = open(tmpsrc, 'wb') f = open(tmpsrc, 'wb')
@ -284,7 +289,7 @@ def write_file(module, url, dest, content):
except Exception as e: except Exception as e:
os.remove(tmpsrc) os.remove(tmpsrc)
module.fail_json(msg="failed to create temporary content file: %s" % to_native(e), module.fail_json(msg="failed to create temporary content file: %s" % to_native(e),
exception=traceback.format_exc()) exception=traceback.format_exc(), **resp)
f.close() f.close()
checksum_src = None checksum_src = None
@ -293,10 +298,10 @@ def write_file(module, url, dest, content):
# raise an error if there is no tmpsrc file # raise an error if there is no tmpsrc file
if not os.path.exists(tmpsrc): if not os.path.exists(tmpsrc):
os.remove(tmpsrc) os.remove(tmpsrc)
module.fail_json(msg="Source '%s' does not exist" % tmpsrc) module.fail_json(msg="Source '%s' does not exist" % tmpsrc, **resp)
if not os.access(tmpsrc, os.R_OK): if not os.access(tmpsrc, os.R_OK):
os.remove(tmpsrc) os.remove(tmpsrc)
module.fail_json(msg="Source '%s' not readable" % tmpsrc) module.fail_json(msg="Source '%s' not readable" % tmpsrc, **resp)
checksum_src = module.sha1(tmpsrc) checksum_src = module.sha1(tmpsrc)
# check if there is no dest file # check if there is no dest file
@ -304,15 +309,15 @@ def write_file(module, url, dest, content):
# raise an error if copy has no permission on dest # raise an error if copy has no permission on dest
if not os.access(dest, os.W_OK): if not os.access(dest, os.W_OK):
os.remove(tmpsrc) os.remove(tmpsrc)
module.fail_json(msg="Destination '%s' not writable" % dest) module.fail_json(msg="Destination '%s' not writable" % dest, **resp)
if not os.access(dest, os.R_OK): if not os.access(dest, os.R_OK):
os.remove(tmpsrc) os.remove(tmpsrc)
module.fail_json(msg="Destination '%s' not readable" % dest) module.fail_json(msg="Destination '%s' not readable" % dest, **resp)
checksum_dest = module.sha1(dest) checksum_dest = module.sha1(dest)
else: else:
if not os.access(os.path.dirname(dest), os.W_OK): if not os.access(os.path.dirname(dest), os.W_OK):
os.remove(tmpsrc) os.remove(tmpsrc)
module.fail_json(msg="Destination dir '%s' not writable" % os.path.dirname(dest)) module.fail_json(msg="Destination dir '%s' not writable" % os.path.dirname(dest), **resp)
if checksum_src != checksum_dest: if checksum_src != checksum_dest:
try: try:
@ -320,7 +325,7 @@ def write_file(module, url, dest, content):
except Exception as e: except Exception as e:
os.remove(tmpsrc) os.remove(tmpsrc)
module.fail_json(msg="failed to copy %s to %s: %s" % (tmpsrc, dest, to_native(e)), module.fail_json(msg="failed to copy %s to %s: %s" % (tmpsrc, dest, to_native(e)),
exception=traceback.format_exc()) exception=traceback.format_exc(), **resp)
os.remove(tmpsrc) os.remove(tmpsrc)
@ -401,7 +406,7 @@ def uri(module, url, dest, body, body_format, method, headers, socket_timeout):
}) })
data = open(src, 'rb') data = open(src, 'rb')
except OSError: except OSError:
module.fail_json(msg='Unable to open source file %s' % src, exception=traceback.format_exc()) module.fail_json(msg='Unable to open source file %s' % src, exception=traceback.format_exc(), elapsed=0)
else: else:
data = body data = body
@ -463,7 +468,7 @@ def main():
body=dict(type='raw'), body=dict(type='raw'),
body_format=dict(type='str', default='raw', choices=['form-urlencoded', 'json', 'raw']), body_format=dict(type='str', default='raw', choices=['form-urlencoded', 'json', 'raw']),
src=dict(type='path'), src=dict(type='path'),
method=dict(type='str', default='GET', choices=['GET', 'POST', 'PUT', 'HEAD', 'DELETE', 'OPTIONS', 'PATCH', 'TRACE', 'CONNECT', 'REFRESH']), method=dict(type='str', default='GET', choices=['CONNECT', 'DELETE', 'GET', 'HEAD', 'OPTIONS', 'PATCH', 'POST', 'PUT', 'REFRESH', 'TRACE']),
return_content=dict(type='bool', default=False), return_content=dict(type='bool', default=False),
follow_redirects=dict(type='str', default='safe', choices=['all', 'no', 'none', 'safe', 'urllib2', 'yes']), follow_redirects=dict(type='str', default='safe', choices=['all', 'no', 'none', 'safe', 'urllib2', 'yes']),
creates=dict(type='path'), creates=dict(type='path'),
@ -505,7 +510,7 @@ def main():
try: try:
body = form_urlencoded(body) body = form_urlencoded(body)
except ValueError as e: except ValueError as e:
module.fail_json(msg='failed to parse body as form_urlencoded: %s' % to_native(e)) module.fail_json(msg='failed to parse body as form_urlencoded: %s' % to_native(e), elapsed=0)
if 'content-type' not in [header.lower() for header in dict_headers]: if 'content-type' not in [header.lower() for header in dict_headers]:
dict_headers['Content-Type'] = 'application/x-www-form-urlencoded' dict_headers['Content-Type'] = 'application/x-www-form-urlencoded'
@ -525,35 +530,37 @@ def main():
# and the filename already exists. This allows idempotence # and the filename already exists. This allows idempotence
# of uri executions. # of uri executions.
if os.path.exists(creates): if os.path.exists(creates):
module.exit_json(stdout="skipped, since '%s' exists" % creates, changed=False, rc=0) module.exit_json(stdout="skipped, since '%s' exists" % creates, changed=False)
if removes is not None: if removes is not None:
# do not run the command if the line contains removes=filename # do not run the command if the line contains removes=filename
# and the filename does not exist. This allows idempotence # and the filename does not exist. This allows idempotence
# of uri executions. # of uri executions.
if not os.path.exists(removes): if not os.path.exists(removes):
module.exit_json(stdout="skipped, since '%s' does not exist" % removes, changed=False, rc=0) module.exit_json(stdout="skipped, since '%s' does not exist" % removes, changed=False)
# Make the request # Make the request
start = datetime.datetime.utcnow()
resp, content, dest = uri(module, url, dest, body, body_format, method, resp, content, dest = uri(module, url, dest, body, body_format, method,
dict_headers, socket_timeout) dict_headers, socket_timeout)
resp['elapsed'] = (datetime.datetime.utcnow() - start).seconds
resp['status'] = int(resp['status']) resp['status'] = int(resp['status'])
# Write the file out if requested # Write the file out if requested
if dest is not None: if dest is not None:
if resp['status'] == 304: if resp['status'] == 304:
changed = False resp['changed'] = False
else: else:
write_file(module, url, dest, content) write_file(module, url, dest, content, resp)
# allow file attribute changes # allow file attribute changes
changed = True resp['changed'] = True
module.params['path'] = dest module.params['path'] = dest
file_args = module.load_file_common_arguments(module.params) file_args = module.load_file_common_arguments(module.params)
file_args['path'] = dest file_args['path'] = dest
changed = module.set_fs_attributes_if_different(file_args, changed) resp['changed'] = module.set_fs_attributes_if_different(file_args, resp['changed'])
resp['path'] = dest resp['path'] = dest
else: else:
changed = False resp['changed'] = False
# Transmogrify the headers, replacing '-' with '_', since variables don't # Transmogrify the headers, replacing '-' with '_', since variables don't
# work with dashes. # work with dashes.
@ -588,9 +595,9 @@ def main():
uresp['msg'] = 'Status code was %s and not %s: %s' % (resp['status'], status_code, uresp.get('msg', '')) uresp['msg'] = 'Status code was %s and not %s: %s' % (resp['status'], status_code, uresp.get('msg', ''))
module.fail_json(content=u_content, **uresp) module.fail_json(content=u_content, **uresp)
elif return_content: elif return_content:
module.exit_json(changed=changed, content=u_content, **uresp) module.exit_json(content=u_content, **uresp)
else: else:
module.exit_json(changed=changed, **uresp) module.exit_json(**uresp)
if __name__ == '__main__': if __name__ == '__main__':

@ -1,7 +1,7 @@
#!/usr/bin/python #!/usr/bin/python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# (c) 2012, Jeroen Hoekx <jeroen@hoekx.be> # Copyright: (c) 2012, Jeroen Hoekx <jeroen@hoekx.be>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function from __future__ import absolute_import, division, print_function
@ -170,6 +170,14 @@ EXAMPLES = r'''
ansible_connection: local ansible_connection: local
''' '''
RETURN = r'''
elapsed:
description: The number of seconds that elapsed while waiting
returned: always
type: int
sample: 23
'''
import binascii import binascii
import datetime import datetime
import errno import errno
@ -459,18 +467,18 @@ def main():
compiled_search_re = None compiled_search_re = None
if port and path: if port and path:
module.fail_json(msg="port and path parameter can not both be passed to wait_for") module.fail_json(msg="port and path parameter can not both be passed to wait_for", elapsed=0)
if path and state == 'stopped': if path and state == 'stopped':
module.fail_json(msg="state=stopped should only be used for checking a port in the wait_for module") module.fail_json(msg="state=stopped should only be used for checking a port in the wait_for module", elapsed=0)
if path and state == 'drained': if path and state == 'drained':
module.fail_json(msg="state=drained should only be used for checking a port in the wait_for module") module.fail_json(msg="state=drained should only be used for checking a port in the wait_for module", elapsed=0)
if module.params['exclude_hosts'] is not None and state != 'drained': if module.params['exclude_hosts'] is not None and state != 'drained':
module.fail_json(msg="exclude_hosts should only be with state=drained") module.fail_json(msg="exclude_hosts should only be with state=drained", elapsed=0)
for _connection_state in module.params['active_connection_states']: for _connection_state in module.params['active_connection_states']:
try: try:
get_connection_state_id(_connection_state) get_connection_state_id(_connection_state)
except: except:
module.fail_json(msg="unknown active_connection_state (%s) defined" % _connection_state) module.fail_json(msg="unknown active_connection_state (%s) defined" % _connection_state, elapsed=0)
start = datetime.datetime.utcnow() start = datetime.datetime.utcnow()

@ -1,7 +1,7 @@
#!/usr/bin/python #!/usr/bin/python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# (c) 2017, Dag Wieers <dag@wieers.com> # Copyright: (c) 2017, Dag Wieers (@dagwieers) <dag@wieers.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function from __future__ import absolute_import, division, print_function

@ -95,6 +95,8 @@ Function CheckModified-File($url, $dest, $headers, $credentials, $timeout, $use_
Function Download-File($result, $url, $dest, $headers, $credentials, $timeout, $use_proxy, $proxy, $whatif) { Function Download-File($result, $url, $dest, $headers, $credentials, $timeout, $use_proxy, $proxy, $whatif) {
$module_start = Get-Date
# Check $dest parent folder exists before attempting download, which avoids unhelpful generic error message. # Check $dest parent folder exists before attempting download, which avoids unhelpful generic error message.
$dest_parent = Split-Path -LiteralPath $dest $dest_parent = Split-Path -LiteralPath $dest
if (-not (Test-Path -LiteralPath $dest_parent -PathType Container)) { if (-not (Test-Path -LiteralPath $dest_parent -PathType Container)) {
@ -132,8 +134,10 @@ Function Download-File($result, $url, $dest, $headers, $credentials, $timeout, $
$extWebClient.DownloadFile($url, $dest) $extWebClient.DownloadFile($url, $dest)
} Catch [System.Net.WebException] { } Catch [System.Net.WebException] {
$result.status_code = [int] $_.Exception.Response.StatusCode $result.status_code = [int] $_.Exception.Response.StatusCode
$result.elapsed = ((Get-Date) - $module_start).TotalSeconds
Fail-Json -obj $result -message "Error downloading '$url' to '$dest': $($_.Exception.Message)" Fail-Json -obj $result -message "Error downloading '$url' to '$dest': $($_.Exception.Message)"
} Catch { } Catch {
$result.elapsed = ((Get-Date) - $module_start).TotalSeconds
Fail-Json -obj $result -message "Unknown error downloading '$url' to '$dest': $($_.Exception.Message)" Fail-Json -obj $result -message "Unknown error downloading '$url' to '$dest': $($_.Exception.Message)"
} }
} }
@ -142,6 +146,8 @@ Function Download-File($result, $url, $dest, $headers, $credentials, $timeout, $
$result.changed = $true $result.changed = $true
$result.msg = 'OK' $result.msg = 'OK'
$result.dest = $dest $result.dest = $dest
$result.elapsed = ((Get-Date) - $module_start).TotalSeconds
} }
$url = Get-AnsibleParam -obj $params -name "url" -type "str" -failifempty $true $url = Get-AnsibleParam -obj $params -name "url" -type "str" -failifempty $true
@ -162,6 +168,7 @@ $force = Get-AnsibleParam -obj $params -name "force" -type "bool" -default $true
$result = @{ $result = @{
changed = $false changed = $false
dest = $dest dest = $dest
elapsed = 0
url = $url url = $url
# This is deprecated as of v2.4, remove in v2.8 # This is deprecated as of v2.4, remove in v2.8
win_get_url = @{ win_get_url = @{
@ -221,14 +228,14 @@ $result.dest = $dest
$result.win_get_url.dest = $dest $result.win_get_url.dest = $dest
# Enable TLS1.1/TLS1.2 if they're available but disabled (eg. .NET 4.5) # Enable TLS1.1/TLS1.2 if they're available but disabled (eg. .NET 4.5)
$security_protcols = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::SystemDefault $security_protocols = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::SystemDefault
if ([Net.SecurityProtocolType].GetMember("Tls11").Count -gt 0) { if ([Net.SecurityProtocolType].GetMember("Tls11").Count -gt 0) {
$security_protcols = $security_protcols -bor [Net.SecurityProtocolType]::Tls11 $security_protocols = $security_protocols -bor [Net.SecurityProtocolType]::Tls11
} }
if ([Net.SecurityProtocolType].GetMember("Tls12").Count -gt 0) { if ([Net.SecurityProtocolType].GetMember("Tls12").Count -gt 0) {
$security_protcols = $security_protcols -bor [Net.SecurityProtocolType]::Tls12 $security_protocols = $security_protocols -bor [Net.SecurityProtocolType]::Tls12
} }
[Net.ServicePointManager]::SecurityProtocol = $security_protcols [Net.ServicePointManager]::SecurityProtocol = $security_protocols
if ($force -or -not (Test-Path -LiteralPath $dest)) { if ($force -or -not (Test-Path -LiteralPath $dest)) {

@ -141,6 +141,11 @@ dest:
returned: always returned: always
type: string type: string
sample: C:\Users\RandomUser\earthrise.jpg sample: C:\Users\RandomUser\earthrise.jpg
elapsed:
description: The elapsed seconds between the start of poll and the end of the module.
returned: always
type: float
sample: 2.1406487
url: url:
description: requested url description: requested url
returned: always returned: always

@ -89,6 +89,6 @@ rebooted:
elapsed: elapsed:
description: The number of seconds that elapsed waiting for the system to be rebooted. description: The number of seconds that elapsed waiting for the system to be rebooted.
returned: always returned: always
type: int type: float
sample: 23 sample: 23.2
''' '''

@ -40,6 +40,7 @@ $JSON_CANDIDATES = @('text', 'json', 'javascript')
$result = @{ $result = @{
changed = $false changed = $false
elapsed = 0
url = $url url = $url
} }
@ -181,9 +182,12 @@ if ($null -ne $body) {
} }
} }
$module_start = Get-Date
try { try {
$response = $client.GetResponse() $response = $client.GetResponse()
} catch [System.Net.WebException] { } catch [System.Net.WebException] {
$result.elapsed = ((Get-Date) - $module_start).TotalSeconds
$response = $null $response = $null
if ($_.Exception.PSObject.Properties.Name -match "Response") { if ($_.Exception.PSObject.Properties.Name -match "Response") {
# was a non-successful response but we at least have a response and # was a non-successful response but we at least have a response and
@ -194,13 +198,17 @@ try {
# in the case a response (or empty response) was on the exception like in # in the case a response (or empty response) was on the exception like in
# a timeout scenario, we should still fail # a timeout scenario, we should still fail
if ($null -eq $response) { if ($null -eq $response) {
$result.elapsed = ((Get-Date) - $module_start).TotalSeconds
Fail-Json -obj $result -message "WebException occurred when sending web request: $($_.Exception.Message)" Fail-Json -obj $result -message "WebException occurred when sending web request: $($_.Exception.Message)"
} }
} catch [System.Net.ProtocolViolationException] { } catch [System.Net.ProtocolViolationException] {
$result.elapsed = ((Get-Date) - $module_start).TotalSeconds
Fail-Json -obj $result -message "ProtocolViolationException when sending web request: $($_.Exception.Message)" Fail-Json -obj $result -message "ProtocolViolationException when sending web request: $($_.Exception.Message)"
} catch { } catch {
$result.elapsed = ((Get-Date) - $module_start).TotalSeconds
Fail-Json -obj $result -message "Unhandled exception occured when sending web request. Exception: $($_.Exception.Message)" Fail-Json -obj $result -message "Unhandled exception occured when sending web request. Exception: $($_.Exception.Message)"
} }
$result.elapsed = ((Get-Date) - $module_start).TotalSeconds
ForEach ($prop in $response.psobject.properties) { ForEach ($prop in $response.psobject.properties) {
$result_key = Convert-StringToSnakeCase -string $prop.Name $result_key = Convert-StringToSnakeCase -string $prop.Name

@ -174,6 +174,11 @@ EXAMPLES = r'''
''' '''
RETURN = r''' RETURN = r'''
elapsed:
description: The number of seconds that elapsed while performing the download
returned: always
type: float
sample: 23.2
url: url:
description: The Target URL description: The Target URL
returned: always returned: always

@ -23,6 +23,7 @@ $timeout = Get-AnsibleParam -obj $params -name "timeout" -type "int" -default 30
$result = @{ $result = @{
changed = $false changed = $false
elapsed = 0
} }
# validate the input with the various options # validate the input with the various options
@ -126,9 +127,8 @@ if ($path -eq $null -and $port -eq $null -and $state -ne "drained") {
} }
if ($complete -eq $false) { if ($complete -eq $false) {
$elapsed_seconds = ((Get-Date) - $module_start).TotalSeconds $result.elapsed = ((Get-Date) - $module_start).TotalSeconds
$result.wait_attempts = $attempts $result.wait_attempts = $attempts
$result.elapsed = $elapsed_seconds
if ($search_regex -eq $null) { if ($search_regex -eq $null) {
Fail-Json $result "timeout while waiting for file $path to be present" Fail-Json $result "timeout while waiting for file $path to be present"
} else { } else {
@ -158,9 +158,8 @@ if ($path -eq $null -and $port -eq $null -and $state -ne "drained") {
} }
if ($complete -eq $false) { if ($complete -eq $false) {
$elapsed_seconds = ((Get-Date) - $module_start).TotalSeconds $result.elapsed = ((Get-Date) - $module_start).TotalSeconds
$result.wait_attempts = $attempts $result.wait_attempts = $attempts
$result.elapsed = $elapsed_seconds
if ($search_regex -eq $null) { if ($search_regex -eq $null) {
Fail-Json $result "timeout while waiting for file $path to be absent" Fail-Json $result "timeout while waiting for file $path to be absent"
} else { } else {
@ -185,9 +184,8 @@ if ($path -eq $null -and $port -eq $null -and $state -ne "drained") {
} }
if ($complete -eq $false) { if ($complete -eq $false) {
$elapsed_seconds = ((Get-Date) - $module_start).TotalSeconds $result.elapsed = ((Get-Date) - $module_start).TotalSeconds
$result.wait_attempts = $attempts $result.wait_attempts = $attempts
$result.elapsed = $elapsed_seconds
Fail-Json $result "timeout while waiting for $($hostname):$port to start listening" Fail-Json $result "timeout while waiting for $($hostname):$port to start listening"
} }
} elseif ($state -in @("stopped","absent")) { } elseif ($state -in @("stopped","absent")) {
@ -206,9 +204,8 @@ if ($path -eq $null -and $port -eq $null -and $state -ne "drained") {
} }
if ($complete -eq $false) { if ($complete -eq $false) {
$elapsed_seconds = ((Get-Date) - $module_start).TotalSeconds $result.elapsed = ((Get-Date) - $module_start).TotalSeconds
$result.wait_attempts = $attempts $result.wait_attempts = $attempts
$result.elapsed = $elapsed_seconds
Fail-Json $result "timeout while waiting for $($hostname):$port to stop listening" Fail-Json $result "timeout while waiting for $($hostname):$port to stop listening"
} }
} elseif ($state -eq "drained") { } elseif ($state -eq "drained") {
@ -247,15 +244,14 @@ if ($path -eq $null -and $port -eq $null -and $state -ne "drained") {
} }
if ($complete -eq $false) { if ($complete -eq $false) {
$elapsed_seconds = ((Get-Date) - $module_start).TotalSeconds $result.elapsed = ((Get-Date) - $module_start).TotalSeconds
$result.wait_attempts = $attempts $result.wait_attempts = $attempts
$result.elapsed = $elapsed_seconds
Fail-Json $result "timeout while waiting for $($hostname):$port to drain" Fail-Json $result "timeout while waiting for $($hostname):$port to drain"
} }
} }
} }
$result.wait_attempts = $attempts
$result.elapsed = ((Get-Date) - $module_start).TotalSeconds $result.elapsed = ((Get-Date) - $module_start).TotalSeconds
$result.wait_attempts = $attempts
Exit-Json $result Exit-Json $result

Loading…
Cancel
Save