Coverage for lib/ansible/executor/task_executor.py : 59%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
except ImportError: from ansible.utils.display import Display display = Display()
''' Remove args with a value equal to the ``omit_token`` recursively to align with now having suboptions in the argument_spec '''
continue else:
''' This is the main worker class for the executor pipeline, which handles loading an action plugin to actually dispatch the task to a given host. This class roughly corresponds to the old Runner() class. '''
# Modules that we optimize by squashing loop items into a single call to # the module
''' The main executor entrypoint, where we determine if the specified task requires looping and either runs the task with self._run_loop() or self._execute(). After that, the returned results are parsed and returned as a dict. '''
except AnsibleUndefinedVariable as e: # save the error raised here for use later items = None self._loop_eval_error = e
# create the overall result item
# loop through the item results, and set the global changed/failed result flags based on any item. item_ignore = item.pop('_ansible_ignore_errors') if not res.get('failed'): res['failed'] = True res['msg'] = 'One or more items failed' self._task.ignore_errors = item_ignore elif self._task.ignore_errors and not item_ignore: self._task.ignore_errors = item_ignore
# ensure to accumulate these if array not in res: res[array] = [] if not isinstance(item[array], list): item[array] = [item[array]] res[array] = res[array] + item[array] del item[array]
else: res = dict(changed=False, skipped=True, skipped_reason='No items in the list', results=[]) else:
# make sure changed is set in the result, if it's not present
return res._obj except UnicodeError: if k == 'diff': # If this is a diff, substitute a replacement character if the value # is undecodable as utf8. (Fix #21804) display.warning("We were unable to decode all characters in the module return data." " Replaced some in an effort to return as much as possible") res[k] = _clean_res(res[k], errors='surrogate_then_replace') else: raise
except AnsibleError as e: return dict(failed=True, msg=to_text(e, nonstring='simplerepr')) except Exception as e: return dict(failed=True, msg='Unexpected failure during module execution.', exception=to_text(traceback.format_exc()), stdout='') finally: except Exception as e: display.debug(u"error closing connection: %s" % to_text(e))
''' Loads a lookup plugin to handle the with_* portion of a task (if specified), and returns the items result. '''
# save the play context variables to a temporary dictionary, # so that we can modify the job vars without doing a full copy # and later restore them to avoid modifying things too early
# get search path for this task to pass to lookup plugins
# first_found loops are special. If the item is undefined then we want to fall through to the next value rather than failing.
convert_bare=False)
# get lookup
# give lookup task 'context' for subdir (mostly needed for first_found)
# run lookup else: raise AnsibleError("Unexpected failure in finding the lookup named '%s' in the available lookup plugins" % self._task.loop_with)
items = templar.template(self._task.loop) if not isinstance(items, list): raise AnsibleError("Invalid data passed to 'loop' it requires a list, got this instead: %s" % items)
# now we restore any old job variables that may have been modified, # and delete them if they were in the play context vars but not in # the old variables dictionary else:
# ensure basedir is always in (dwim already searches here but we need to display it)
''' Runs the task with the loop items specified and collates the result into an array named 'results' which is inserted into the final result along with the item for which the loop ran. '''
# make copies of the job vars and task so we can add the item to # the variables and re-validate the task with the item variable # task_vars = self._job_vars.copy()
# FIXME: move this to the object itself to allow post_validate to take care of templating # the these may be 'None', so we still need to default to something useful # this is tempalted below after an item is assigned
display.warning(u"The loop variable '%s' is already in use. " u"You should set the `loop_var` value in the `loop_control` option for the task" u" to something else to avoid variable collisions and unexpected behavior." % loop_var)
# Only squash with 'with_:' not with the 'loop:', 'magic' squashing can be removed once with_ loops are
task_vars[index_var] = item_index
# pause between loop iterations try: time.sleep(float(loop_pause)) except ValueError as e: raise AnsibleError('Invalid pause value: %s, produced error: %s' % (loop_pause, to_native(e))) else:
except AnsibleParserError as e: results.append(dict(failed=True, msg=to_text(e))) continue
# now we swap the internal task and play context with their copies, # execute, and swap them back so we can do the next iteration cleanly
# now update the result with the item info, and append the result # to the list of results res[index_var] = item_index
TaskResult( self._host.name, self._task._uuid, res, task_fields=task_fields, ), block=False, )
''' Squash items down to a comma-separated list for certain modules which support it (typically package management modules). ''' # _task.action could contain templatable strings (via action: and # local_action:) Template it before comparing. If we don't end up # optimizing it here, the templatable string might use template vars # that aren't available until later (it could even use vars from the # with_items loop) so don't make the templated string permanent yet. task_action = templar.template(task_action, fail_on_undefined=False)
if all(isinstance(o, string_types) for o in items): final_items = []
for allowed in ['name', 'pkg', 'package']: name = self._task.args.pop(allowed, None) if name is not None: break
# This gets the information to check whether the name field # contains a template that we can squash for template_no_item = template_with_item = None if name: if templar._contains_vars(name): variables[loop_var] = '\0$' template_no_item = templar.template(name, variables, cache=False) variables[loop_var] = '\0@' template_with_item = templar.template(name, variables, cache=False) del variables[loop_var]
# Check if the user is doing some operation that doesn't take # name/pkg or the name/pkg field doesn't have any variables # and thus the items can't be squashed if template_no_item != template_with_item: for item in items: variables[loop_var] = item if self._task.evaluate_conditional(templar, variables): new_item = templar.template(name, cache=False) final_items.append(new_item) self._task.args['name'] = final_items # Wrap this in a list so that the calling function loop # executes exactly once return [final_items] else: # Restore the name parameter self._task.args['name'] = name # elif: # Right now we only optimize single entries. In the future we # could optimize more types: # * lists can be squashed together # * dicts could squash entries that match in all cases except the # name or pkg field. except Exception: # Squashing is an optimization. If it fails for any reason, # simply use the unoptimized list of items.
# Restore the name parameter if name is not None: self._task.args['name'] = name
''' The primary workhorse of the executor system, this runs the task on the specified host (which may be the delegated_to host) and handles the retry/until and block rescue/always execution '''
# apply the given task's information to the connection info, # which may override some fields already set by the play or # the options specified on the command line
# fields set from the play/task may be based on variables, so we have to # do the same kind of post validation step on it here before we use it.
# now that the play context is finalized, if the remote_addr is not set # default to using the host's address field as the remote address
# We also add "magic" variables back into the variables dict to make sure # a certain subset of variables exist.
# FIXME: update connection/shell plugin options except AnsibleError as e: # save the error, which we'll raise later if we don't end up # skipping this task during the conditional evaluation step context_validation_error = e
# Evaluate the conditional (if any) for this task, which we do before running # the final task post-validation. We do this before the post validation due to # the fact that the conditional may specify that the task be skipped due to a # variable not being present which would otherwise cause validation to fail except AnsibleError: # loop error takes precedence if self._loop_eval_error is not None: raise self._loop_eval_error # pylint: disable=raising-bad-type # skip conditional exception in the case of includes as the vars needed might not be available except in the included tasks or due to tags if self._task.action not in ['include', 'include_tasks', 'include_role']: raise
# Not skipping, if we had loop error raised earlier we need to raise it now to halt the execution of this task raise self._loop_eval_error # pylint: disable=raising-bad-type
# if we ran into an error while setting up the PlayContext, raise it now raise context_validation_error # pylint: disable=raising-bad-type
# if this task is a TaskInclude, we just return now with a success code so the # main thread can expand the task list for the given host return dict(failed=True, msg="No include file was specified to the include")
# if this task is a IncludeRole, we just return now with a success code so the main thread can expand the task list for the given host include_variables = self._task.args.copy() return dict(include_variables=include_variables)
# Now we do final validation on the task, which sets all fields to their final values. variable_params = self._task.args.pop('_variable_params') if isinstance(variable_params, dict): display.deprecated("Using variables for task params is unsafe, especially if the variables come from an external source like facts", version="2.6") variable_params.update(self._task.args) self._task.args = variable_params
# get the connection and the handler for this execution not getattr(self._connection, 'connected', False) or self._play_context.remote_addr != self._connection._play_context.remote_addr): else: # if connection is reused, its _play_context is no longer valid and needs # to be replaced with the one templated above, in case other data changed self._connection._play_context = self._play_context
# get handler
# And filter out any fields which were set to default(omit), and got the omit token value
# Read some values from the task, so that we can modify them if need be retries = self._task.retries if retries is None: retries = 3 elif retries <= 0: retries = 1 else: retries += 1 else:
delay = 1
# make a copy of the job vars here, in case we need to update them # with the registered variable value later on when testing conditions
except AnsibleActionSkip as e: return dict(skipped=True, msg=to_text(e)) except AnsibleActionFail as e: return dict(failed=True, msg=to_text(e)) except AnsibleConnectionFailure as e: return dict(unreachable=True, msg=to_text(e))
# preserve no log
# update the local copy of vars with the registered value, if specified, # or any facts which may have been generated by the module execution
if self._task.poll > 0 and not result.get('skipped') and not result.get('failed'): result = self._poll_async_result(result=result, templar=templar, task_vars=vars_copy) # FIXME callback 'v2_runner_on_async_poll' here
# ensure no log is preserved result["_ansible_no_log"] = self._play_context.no_log
# helper methods for use below in evaluating changed/failed_when cond = Conditional(loader=self._loader) cond.when = self._task.changed_when result['changed'] = cond.evaluate_conditional(templar, vars_copy)
cond = Conditional(loader=self._loader) cond.when = self._task.failed_when failed_when_result = cond.evaluate_conditional(templar, vars_copy) result['failed_when_result'] = result['failed'] = failed_when_result else:
# set the failed property if it was missing. # rc is here for backwards compatibility and modules that use it instead of 'failed' result['failed'] = True else:
# Make attempts and retries available early to allow their use in changed/failed_when result['attempts'] = attempt
# set the changed property if it was missing.
# re-update the local copy of vars with the registered value, if specified, # or any facts which may have been generated by the module execution # This gives changed/failed_when access to additional recently modified # attributes of result
# if we didn't skip this task, use the helpers to evaluate the changed/ # failed_when properties
cond = Conditional(loader=self._loader) cond.when = self._task.until if cond.evaluate_conditional(templar, vars_copy): break else: # no conditional check, or it failed, so sleep for the specified time if attempt < retries: result['_ansible_retry'] = True result['retries'] = retries display.debug('Retrying task, attempt %d of %d' % (attempt, retries)) self._rslt_q.put(TaskResult(self._host.name, self._task._uuid, result, task_fields=self._task.dump_attrs()), block=False) time.sleep(delay) else: # we ran out of attempts, so mark the result as failed result['attempts'] = retries - 1 result['failed'] = True
# do the final update of the local variables here, for both registered # values and any facts which may have been created
# save the notification target in the result, if it was specified, as # this task may be running in a loop in which case the notification # may be item-specific, ie. "notify: service {{item}}" result['_ansible_notify'] = self._task.notify
# add the delegated vars to the result, so we can reference them # on the results side without having to do any further templating # FIXME: we only want a limited set of variables here, so this is currently # hardcoded but should be possibly fixed if we want more or if # there is another source of truth we can use result["_ansible_delegated_vars"] = {'ansible_delegated_host': self._task.delegate_to} for k in ('ansible_host', ): result["_ansible_delegated_vars"][k] = delegated_vars.get(k)
# and return
''' Polls for the specified JID to be complete '''
if task_vars is None: task_vars = self._job_vars
async_jid = result.get('ansible_job_id') if async_jid is None: return dict(failed=True, msg="No job id was returned by the async task")
# Create a new pseudo-task to run the async_status module, and run # that (with a sleep for "poll" seconds between each retry) until the # async time limit is exceeded.
async_task = Task().load(dict(action='async_status jid=%s' % async_jid))
# FIXME: this is no longer the case, normal takes care of all, see if this can just be generalized # Because this is an async task, the action handler is async. However, # we need the 'normal' action handler for the status check, so get it # now via the action_loader normal_handler = self._shared_loader_obj.action_loader.get( 'normal', task=async_task, connection=self._connection, play_context=self._play_context, loader=self._loader, templar=templar, shared_loader_obj=self._shared_loader_obj, )
time_left = self._task.async_val while time_left > 0: time.sleep(self._task.poll)
try: async_result = normal_handler.run(task_vars=task_vars) # We do not bail out of the loop in cases where the failure # is associated with a parsing error. The async_runner can # have issues which result in a half-written/unparseable result # file on disk, which manifests to the user as a timeout happening # before it's time to timeout. if (int(async_result.get('finished', 0)) == 1 or ('failed' in async_result and async_result.get('_ansible_parsed', False)) or 'skipped' in async_result): break except Exception as e: # Connections can raise exceptions during polling (eg, network bounce, reboot); these should be non-fatal. # On an exception, call the connection's reset method if it has one # (eg, drop/recreate WinRM connection; some reused connections are in a broken state) display.vvvv("Exception during async poll, retrying... (%s)" % to_text(e)) display.debug("Async poll exception was:\n%s" % to_text(traceback.format_exc())) try: normal_handler._connection._reset() except AttributeError: pass
# Little hack to raise the exception if we've exhausted the timeout period time_left -= self._task.poll if time_left <= 0: raise else: time_left -= self._task.poll
if int(async_result.get('finished', 0)) != 1: if async_result.get('_ansible_parsed'): return dict(failed=True, msg="async task did not complete within the requested time") else: return dict(failed=True, msg="async task produced unparseable results", async_result=async_result) else: return async_result
''' Reads the connection property for the host, and returns the correct connection object from the list of connection plugins '''
# since we're delegating, we don't want to use interpreter values # which would have been set for the original target host for i in list(variables.keys()): if isinstance(i, string_types) and i.startswith('ansible_') and i.endswith('_interpreter'): del variables[i] # now replace the interpreter values with those that may have come # from the delegated-to host delegated_vars = variables.get('ansible_delegated_vars', dict()).get(self._task.delegate_to, dict()) if isinstance(delegated_vars, dict): for i in delegated_vars: if isinstance(i, string_types) and i.startswith("ansible_") and i.endswith("_interpreter"): variables[i] = delegated_vars[i]
raise AnsibleError("the connection plugin '%s' was not found" % conn_type)
# FIXME: remove once all plugins pull all data from self._options
# create copy with delegation built in
# grab list of usable vars for this plugin
# create dict of 'templated vars'
# add extras if plugin supports them for k in final_vars: if k.startswith('ansible_%s_' % self._connection._load_name) and k not in options: options['_extras'][k] = templar.template(final_vars[k])
# set options with 'templated vars' specific to this plugin
options[k] = templar.template(variables[k])
''' Returns the correct action plugin to handle the requestion task action '''
# let action plugin override module, fallback to 'normal' action plugin otherwise else:
handler_name, task=self._task, connection=connection, play_context=self._play_context, loader=self._loader, templar=templar, shared_loader_obj=self._shared_loader_obj, )
raise AnsibleError("the handler '%s' was not found" % handler_name)
''' Starts the persistent connection '''
# Need to force a protocol that is compatible with both py2 and py3. # That would be protocol=2 or less. # Also need to force a protocol that excludes certain control chars as # stdin in this case is a pty and control chars will cause problems. # that means only protocol=0 will work.
else: result = json.loads(to_text(stderr))
if self._play_context.verbosity > 2: msg = "The full traceback is:\n" + result['exception'] display.display(msg, color=C.COLOR_ERROR) raise AnsibleError(result['error'])
|