| 1 |
# (c) 2012-2014, Michael DeHaan <[email protected]> |
| 2 |
# |
| 3 |
# This file is part of Ansible |
| 4 |
# |
| 5 |
# Ansible is free software: you can redistribute it and/or modify |
| 6 |
# it under the terms of the GNU General Public License as published by |
| 7 |
# the Free Software Foundation, either version 3 of the License, or |
| 8 |
# (at your option) any later version. |
| 9 |
# |
| 10 |
# Ansible is distributed in the hope that it will be useful, |
| 11 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 |
# GNU General Public License for more details. |
| 14 |
# |
| 15 |
# You should have received a copy of the GNU General Public License |
| 16 |
# along with Ansible. If not, see <http://www.gnu.org/licenses/>. |
| 17 |
from __future__ import annotations |
| 18 |
|
| 19 |
DOCUMENTATION = """ |
| 20 |
name: linear |
| 21 |
short_description: Executes tasks in a linear fashion |
| 22 |
description: |
| 23 |
- Task execution is in lockstep per host batch as defined by C(serial) (default all). |
| 24 |
Up to the fork limit of hosts will execute each task at the same time and then |
| 25 |
the next series of hosts until the batch is done, before going on to the next task. |
| 26 |
version_added: "2.0" |
| 27 |
notes: |
| 28 |
- This was the default Ansible behaviour before 'strategy plugins' were introduced in 2.0. |
| 29 |
author: Ansible Core Team |
| 30 |
""" |
| 31 |
|
| 32 |
from ansible import constants as C |
| 33 |
from ansible._internal import _task |
| 34 |
from ansible.errors import AnsibleError, AnsibleAssertionError, AnsibleParserError, AnsibleValueOmittedError, AnsibleUndefinedVariable |
| 35 |
from ansible.playbook.handler import Handler |
| 36 |
from ansible.playbook.included_file import IncludedFile |
| 37 |
from ansible.plugins.action import ActionBase |
| 38 |
from ansible.plugins.loader import action_loader |
| 39 |
from ansible.plugins.strategy import StrategyBase |
| 40 |
from ansible._internal._templating._engine import TemplateEngine |
| 41 |
from ansible.utils.display import Display |
| 42 |
from ansible.inventory.host import Host |
| 43 |
from ansible.playbook.task import Task |
| 44 |
from ansible.executor.play_iterator import PlayIterator |
| 45 |
from ansible.playbook.play_context import PlayContext |
| 46 |
|
| 47 |
display = Display() |
| 48 |
|
| 49 |
|
| 50 |
class StrategyModule(StrategyBase): |
| 51 |
|
| 52 |
def _get_next_task_lockstep(self, hosts: list[Host], iterator: PlayIterator) -> list[tuple[Host, Task]]: |
| 53 |
""" |
| 54 |
Returns a list of (host, task) tuples, where the task may |
| 55 |
be a noop task to keep the iterator in lock step across |
| 56 |
all hosts. |
| 57 |
""" |
| 58 |
|
| 59 |
state_task_per_host = {} |
| 60 |
for host in hosts: |
| 61 |
state, task = iterator.get_next_task_for_host(host, peek=True) |
| 62 |
if task is not None: |
| 63 |
state_task_per_host[host] = state, task |
| 64 |
|
| 65 |
if not state_task_per_host: |
| 66 |
return [] |
| 67 |
|
| 68 |
task_uuids = {t._uuid for s, t in state_task_per_host.values()} |
| 69 |
_loop_cnt = 0 |
| 70 |
while _loop_cnt <= 1: |
| 71 |
try: |
| 72 |
cur_task = iterator.all_tasks[iterator.cur_task] |
| 73 |
except IndexError: |
| 74 |
# pick up any tasks left after clear_host_errors |
| 75 |
iterator.cur_task = 0 |
| 76 |
_loop_cnt += 1 |
| 77 |
else: |
| 78 |
iterator.cur_task += 1 |
| 79 |
if cur_task._uuid in task_uuids: |
| 80 |
break |
| 81 |
else: |
| 82 |
# prevent infinite loop |
| 83 |
raise AnsibleAssertionError( |
| 84 |
'BUG: There seems to be a mismatch between tasks in PlayIterator and HostStates.' |
| 85 |
) |
| 86 |
|
| 87 |
host_tasks = [] |
| 88 |
for host, (state, task) in state_task_per_host.items(): |
| 89 |
if cur_task._uuid == task._uuid: |
| 90 |
iterator.set_state_for_host(host.name, state) |
| 91 |
host_tasks.append((host, task)) |
| 92 |
|
| 93 |
if cur_task._get_meta() == 'flush_handlers': |
| 94 |
iterator.all_tasks[iterator.cur_task:iterator.cur_task] = [h for b in iterator._play.handlers for h in b.block] |
| 95 |
|
| 96 |
return host_tasks |
| 97 |
|
| 98 |
def run(self, iterator: PlayIterator, play_context: PlayContext): # type: ignore[override] |
| 99 |
""" |
| 100 |
The linear strategy is simple - get the next task and queue |
| 101 |
it for all hosts, then wait for the queue to drain before |
| 102 |
moving on to the next task |
| 103 |
""" |
| 104 |
|
| 105 |
# iterate over each task, while there is one left to run |
| 106 |
result = int(self._tqm.RUN_OK) |
| 107 |
work_to_do = True |
| 108 |
|
| 109 |
self._set_hosts_cache(iterator._play) |
| 110 |
|
| 111 |
while work_to_do and not self._tqm._terminated: |
| 112 |
|
| 113 |
try: |
| 114 |
display.debug("getting the remaining hosts for this loop") |
| 115 |
hosts_left = self.get_hosts_left(iterator) |
| 116 |
display.debug("done getting the remaining hosts for this loop") |
| 117 |
|
| 118 |
# queue up this task for each host in the inventory |
| 119 |
callback_sent = False |
| 120 |
work_to_do = False |
| 121 |
|
| 122 |
host_tasks = self._get_next_task_lockstep(hosts_left, iterator) |
| 123 |
|
| 124 |
# skip control |
| 125 |
skip_rest = False |
| 126 |
choose_step = True |
| 127 |
run_once: bool | None = None |
| 128 |
any_errors_fatal: bool | None = None |
| 129 |
|
| 130 |
results: list[_task.HostTaskResult] = [] |
| 131 |
for (host, task) in host_tasks: |
| 132 |
if self._tqm._terminated: |
| 133 |
break |
| 134 |
|
| 135 |
work_to_do = True |
| 136 |
|
| 137 |
display.debug("getting variables") |
| 138 |
task_vars = self._variable_manager.get_vars(play=iterator._play, host=host, task=task, |
| 139 |
_hosts=self._hosts_cache, _hosts_all=self._hosts_cache_all) |
| 140 |
self.add_tqm_variables(task_vars, play=iterator._play) |
| 141 |
templar = TemplateEngine(loader=self._loader, variables=task_vars) |
| 142 |
display.debug("done getting variables") |
| 143 |
|
| 144 |
# test to see if the task across all hosts points to an action plugin which |
| 145 |
# sets BYPASS_HOST_LOOP to true, or if it has run_once enabled. If so, we |
| 146 |
# will only send this task to the first host in the list. |
| 147 |
|
| 148 |
task_action: str | None = None |
| 149 |
action: ActionBase | None = None |
| 150 |
|
| 151 |
try: |
| 152 |
task_action = templar.template(task.action) |
| 153 |
except AnsibleValueOmittedError: |
| 154 |
raise AnsibleParserError("Omit is not valid for the `action` keyword.", obj=task.action) from None |
| 155 |
except AnsibleUndefinedVariable: |
| 156 |
pass # may be loop dependent -- this prevents us from checking for 'meta' and BYPASS_HOST_LOOP |
| 157 |
else: |
| 158 |
try: |
| 159 |
action = action_loader.get(task_action, class_only=True, collection_list=task.collections) |
| 160 |
except KeyError: |
| 161 |
# we don't care here, because the action may simply not have a |
| 162 |
# corresponding action plugin |
| 163 |
pass |
| 164 |
|
| 165 |
if task_action in C._ACTION_META: |
| 166 |
# for the linear strategy, we run meta tasks just once and for |
| 167 |
# all hosts currently being iterated over rather than one host |
| 168 |
results.extend(self._execute_meta(task, play_context, iterator, host)) |
| 169 |
|
| 170 |
pending_run_once = task._get_meta() not in ('noop', 'reset_connection', 'end_host', 'role_complete', 'flush_handlers', 'end_role') |
| 171 |
else: |
| 172 |
# handle step if needed, skip meta actions as they are used internally |
| 173 |
if self._step and choose_step: |
| 174 |
if self._take_step(task): |
| 175 |
choose_step = False |
| 176 |
else: |
| 177 |
skip_rest = True |
| 178 |
break |
| 179 |
|
| 180 |
pending_run_once = action and action.BYPASS_HOST_LOOP or templar.template(task.run_once) |
| 181 |
|
| 182 |
if not callback_sent: |
| 183 |
task.post_validate_attribute("name", templar=templar) |
| 184 |
|
| 185 |
if isinstance(task, Handler): |
| 186 |
self._tqm.send_callback('v2_playbook_on_handler_task_start', task) |
| 187 |
else: |
| 188 |
self._tqm.send_callback('v2_playbook_on_task_start', task, is_conditional=False) |
| 189 |
callback_sent = True |
| 190 |
|
| 191 |
self._queue_task(host, task, task_vars, play_context) |
| 192 |
del task_vars |
| 193 |
|
| 194 |
if run_once is None: |
| 195 |
run_once = pending_run_once |
| 196 |
task.run_once = run_once |
| 197 |
elif run_once != pending_run_once: |
| 198 |
display.warning( |
| 199 |
msg="The calculated run_once value changed between hosts and will be ignored.", |
| 200 |
obj=task.get_ds(), |
| 201 |
help_text="The calculated value of run_once must not change between hosts for the same task, " |
| 202 |
"including implied values from dynamically resolved actions.", |
| 203 |
) |
| 204 |
|
| 205 |
pending_any_errors_fatal = templar.template(task.any_errors_fatal) |
| 206 |
|
| 207 |
if any_errors_fatal is None: |
| 208 |
any_errors_fatal = pending_any_errors_fatal |
| 209 |
elif any_errors_fatal != pending_any_errors_fatal: |
| 210 |
display.warning( |
| 211 |
msg="The value of any_errors_fatal changed on a subsequent host and will be ignored.", |
| 212 |
obj=task.get_ds(), |
| 213 |
help_text="The value of any_errors_fatal must not change between hosts for the same task.", |
| 214 |
) |
| 215 |
|
| 216 |
if isinstance(task, Handler): |
| 217 |
if run_once: |
| 218 |
task.clear_hosts() |
| 219 |
else: |
| 220 |
task.remove_host(host) |
| 221 |
|
| 222 |
# if we're bypassing the host loop, break out now |
| 223 |
if run_once: |
| 224 |
break |
| 225 |
|
| 226 |
results.extend(self._process_pending_results(iterator, max_passes=max(1, int(len(self._tqm._workers) * 0.1)))) |
| 227 |
|
| 228 |
# go to next host/task group |
| 229 |
if skip_rest: |
| 230 |
continue |
| 231 |
|
| 232 |
display.debug("done queuing things up, now waiting for results queue to drain") |
| 233 |
if self._pending_results > 0: |
| 234 |
results.extend(self._wait_on_pending_results(iterator)) |
| 235 |
|
| 236 |
self.update_active_connections(results) |
| 237 |
|
| 238 |
included_files = IncludedFile.process_include_results( |
| 239 |
results, |
| 240 |
iterator=iterator, |
| 241 |
loader=self._loader, |
| 242 |
variable_manager=self._variable_manager |
| 243 |
) |
| 244 |
|
| 245 |
if len(included_files) > 0: |
| 246 |
display.debug("we have included files to process") |
| 247 |
|
| 248 |
display.debug("generating all_blocks data") |
| 249 |
all_blocks = dict((host, []) for host in hosts_left) |
| 250 |
display.debug("done generating all_blocks data") |
| 251 |
included_tasks = [] |
| 252 |
failed_includes_hosts = set() |
| 253 |
for included_file in included_files: |
| 254 |
display.debug("processing included file: %s" % included_file._filename) |
| 255 |
is_handler = False |
| 256 |
try: |
| 257 |
if included_file._is_role: |
| 258 |
new_ir = self._copy_included_file(included_file) |
| 259 |
|
| 260 |
new_blocks, handler_blocks = new_ir.get_block_list( |
| 261 |
play=iterator._play, |
| 262 |
variable_manager=self._variable_manager, |
| 263 |
loader=self._loader, |
| 264 |
) |
| 265 |
else: |
| 266 |
is_handler = isinstance(included_file._task, Handler) |
| 267 |
new_blocks = self._load_included_file( |
| 268 |
included_file, |
| 269 |
iterator=iterator, |
| 270 |
is_handler=is_handler, |
| 271 |
) |
| 272 |
|
| 273 |
# let PlayIterator know about any new handlers included via include_role or |
| 274 |
# import_role within include_role/include_taks |
| 275 |
iterator.handlers = [h for b in iterator._play.handlers for h in b.block] |
| 276 |
|
| 277 |
display.debug("iterating over new_blocks loaded from include file") |
| 278 |
for new_block in new_blocks: |
| 279 |
if is_handler: |
| 280 |
for task in new_block.block: |
| 281 |
task.notified_hosts = included_file._hosts[:] |
| 282 |
final_block = new_block |
| 283 |
else: |
| 284 |
task_vars = self._variable_manager.get_vars( |
| 285 |
play=iterator._play, |
| 286 |
task=new_block.get_first_parent_include(), |
| 287 |
_hosts=self._hosts_cache, |
| 288 |
_hosts_all=self._hosts_cache_all, |
| 289 |
) |
| 290 |
display.debug("filtering new block on tags") |
| 291 |
final_block = new_block.filter_tagged_tasks(task_vars) |
| 292 |
display.debug("done filtering new block on tags") |
| 293 |
|
| 294 |
included_tasks.extend(final_block.get_tasks()) |
| 295 |
|
| 296 |
for host in hosts_left: |
| 297 |
if host in included_file._hosts: |
| 298 |
all_blocks[host].append(final_block) |
| 299 |
|
| 300 |
display.debug("done iterating over new_blocks loaded from include file") |
| 301 |
except AnsibleParserError: |
| 302 |
raise |
| 303 |
except AnsibleError as ex: |
| 304 |
for r in included_file._results: |
| 305 |
# RPFIX-9: FUTURE: do this better, instead of creating a throw-away UTR to merge onto the existing one |
| 306 |
utr = _task.UnifiedTaskResult._create_from_exception(ex, source_is_module=False) |
| 307 |
|
| 308 |
r.utr.failed = utr.failed |
| 309 |
r.utr.exception = utr.exception |
| 310 |
r.utr.msg = utr.msg |
| 311 |
|
| 312 |
self._tqm._stats.increment('failures', r.host.name) |
| 313 |
self._tqm.send_callback('v2_runner_on_failed', r) |
| 314 |
failed_includes_hosts.add(r.host) |
| 315 |
else: |
| 316 |
# since we skip incrementing the stats when the task result is |
| 317 |
# first processed, we do so now for each host in the list |
| 318 |
for host in included_file._hosts: |
| 319 |
self._tqm._stats.increment('ok', host.name) |
| 320 |
self._tqm.send_callback('v2_playbook_on_include', included_file) |
| 321 |
|
| 322 |
for host in failed_includes_hosts: |
| 323 |
self._tqm._failed_hosts[host.name] = True |
| 324 |
iterator.mark_host_failed(host) |
| 325 |
|
| 326 |
# finally go through all of the hosts and append the |
| 327 |
# accumulated blocks to their list of tasks |
| 328 |
display.debug("extending task lists for all hosts with included blocks") |
| 329 |
|
| 330 |
for host in hosts_left: |
| 331 |
iterator.add_tasks(host, all_blocks[host]) |
| 332 |
|
| 333 |
iterator.all_tasks[iterator.cur_task:iterator.cur_task] = included_tasks |
| 334 |
|
| 335 |
display.debug("done extending task lists") |
| 336 |
display.debug("done processing included files") |
| 337 |
|
| 338 |
display.debug("results queue empty") |
| 339 |
|
| 340 |
display.debug("checking for any_errors_fatal") |
| 341 |
failed_hosts: list[str] = [] |
| 342 |
unreachable_hosts: list[str] = [] |
| 343 |
mark_hosts_failed = False |
| 344 |
|
| 345 |
for res in results: |
| 346 |
if res.utr.failed: |
| 347 |
failed_hosts.append(res.host.name) |
| 348 |
elif res.utr.unreachable: |
| 349 |
unreachable_hosts.append(res.host.name) |
| 350 |
|
| 351 |
if (any_errors_fatal or run_once) and not res.utr.ignore_errors: |
| 352 |
mark_hosts_failed = True |
| 353 |
|
| 354 |
if mark_hosts_failed and (failed_hosts or unreachable_hosts): |
| 355 |
for host in hosts_left: |
| 356 |
if host.name not in failed_hosts: |
| 357 |
self._tqm._failed_hosts[host.name] = True |
| 358 |
iterator.mark_host_failed(host) |
| 359 |
display.debug("done checking for any_errors_fatal") |
| 360 |
|
| 361 |
display.debug("checking for max_fail_percentage") |
| 362 |
if iterator._play.max_fail_percentage is not None and len(results) > 0: |
| 363 |
percentage = iterator._play.max_fail_percentage / 100.0 |
| 364 |
|
| 365 |
if (len(self._tqm._failed_hosts) / iterator.batch_size) > percentage: |
| 366 |
for host in hosts_left: |
| 367 |
# don't double-mark hosts, or the iterator will potentially |
| 368 |
# fail them out of the rescue/always states |
| 369 |
if host.name not in failed_hosts: |
| 370 |
self._tqm._failed_hosts[host.name] = True |
| 371 |
iterator.mark_host_failed(host) |
| 372 |
self._tqm.send_callback('v2_playbook_on_no_hosts_remaining') |
| 373 |
result |= self._tqm.RUN_FAILED_BREAK_PLAY |
| 374 |
display.debug('(%s failed / %s total )> %s max fail' % (len(self._tqm._failed_hosts), iterator.batch_size, percentage)) |
| 375 |
display.debug("done checking for max_fail_percentage") |
| 376 |
|
| 377 |
display.debug("checking to see if all hosts have failed and the running result is not ok") |
| 378 |
if result != self._tqm.RUN_OK and len(self._tqm._failed_hosts) >= len(hosts_left): |
| 379 |
display.debug("^ not ok, so returning result now") |
| 380 |
self._tqm.send_callback('v2_playbook_on_no_hosts_remaining') |
| 381 |
return result |
| 382 |
display.debug("done checking to see if all hosts have failed") |
| 383 |
|
| 384 |
finally: |
| 385 |
# removed unnecessary exception handler, don't want to mis-attribute the entire code block by changing indentation |
| 386 |
pass |
| 387 |
|
| 388 |
# run the base class run() method, which executes the cleanup function |
| 389 |
# and runs any outstanding handlers which have been triggered |
| 390 |
|
| 391 |
return super(StrategyModule, self).run(iterator, play_context, result) |