Debian Codegraph @

lib/ansible/executor/play_iterator.py

raw
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
18 from __future__ import annotations
19
20 import fnmatch
21
22 from enum import IntEnum, IntFlag
23
24 from ansible import constants as C
25 from ansible.errors import AnsibleAssertionError
26 from ansible.module_utils.parsing.convert_bool import boolean
27 from ansible.playbook.block import Block
28 from ansible.playbook.task import Task
29 from ansible.utils.display import Display
30
31
32 display = Display()
33
34
35 __all__ = ['PlayIterator', 'IteratingStates', 'FailedStates']
36
37
38 class IteratingStates(IntEnum):
39 SETUP = 0
40 TASKS = 1
41 RESCUE = 2
42 ALWAYS = 3
43 HANDLERS = 4
44 COMPLETE = 5
45 VALIDATE = 6
46
47
48 class FailedStates(IntFlag):
49 NONE = 0
50 SETUP = 1
51 TASKS = 2
52 RESCUE = 4
53 ALWAYS = 8
54 HANDLERS = 16 # NOTE not in use anymore
55 VALIDATE = 32
56
57
58 class HostState:
59 def __init__(self, blocks):
60 self._blocks = blocks[:]
61 self.handlers = []
62
63 self.handler_notifications = []
64
65 self.cur_block = 0
66 self.cur_regular_task = 0
67 self.cur_rescue_task = 0
68 self.cur_always_task = 0
69 self.cur_handlers_task = 0
70 self.run_state = IteratingStates.SETUP
71 self.fail_state = FailedStates.NONE
72 self.pre_flushing_run_state = None
73 self.update_handlers = True
74 self.tasks_child_state = None
75 self.rescue_child_state = None
76 self.always_child_state = None
77 self.did_rescue = False
78 self.did_start_at_task = False
79
80 def __repr__(self):
81 return "HostState(%r)" % self._blocks
82
83 def __str__(self):
84 return ("HOST STATE: block=%d, task=%d, rescue=%d, always=%d, handlers=%d, run_state=%s, fail_state=%s, "
85 "pre_flushing_run_state=%s, update_handlers=%s, "
86 "tasks child state? (%s), rescue child state? (%s), always child state? (%s), "
87 "did rescue? %s, did start at task? %s" % (
88 self.cur_block,
89 self.cur_regular_task,
90 self.cur_rescue_task,
91 self.cur_always_task,
92 self.cur_handlers_task,
93 self.run_state,
94 self.fail_state,
95 self.pre_flushing_run_state,
96 self.update_handlers,
97 self.tasks_child_state,
98 self.rescue_child_state,
99 self.always_child_state,
100 self.did_rescue,
101 self.did_start_at_task,
102 ))
103
104 def __eq__(self, other):
105 if not isinstance(other, HostState):
106 return False
107
108 for attr in ('_blocks',
109 'cur_block', 'cur_regular_task', 'cur_rescue_task', 'cur_always_task', 'cur_handlers_task',
110 'run_state', 'fail_state', 'pre_flushing_run_state', 'update_handlers',
111 'tasks_child_state', 'rescue_child_state', 'always_child_state'):
112 if getattr(self, attr) != getattr(other, attr):
113 return False
114
115 return True
116
117 def get_current_block(self):
118 return self._blocks[self.cur_block]
119
120 def copy(self):
121 new_state = HostState(self._blocks)
122 new_state.handlers = self.handlers[:]
123 new_state.handler_notifications = self.handler_notifications[:]
124 new_state.cur_block = self.cur_block
125 new_state.cur_regular_task = self.cur_regular_task
126 new_state.cur_rescue_task = self.cur_rescue_task
127 new_state.cur_always_task = self.cur_always_task
128 new_state.cur_handlers_task = self.cur_handlers_task
129 new_state.run_state = self.run_state
130 new_state.fail_state = self.fail_state
131 new_state.pre_flushing_run_state = self.pre_flushing_run_state
132 new_state.update_handlers = self.update_handlers
133 new_state.did_rescue = self.did_rescue
134 new_state.did_start_at_task = self.did_start_at_task
135 if self.tasks_child_state is not None:
136 new_state.tasks_child_state = self.tasks_child_state.copy()
137 if self.rescue_child_state is not None:
138 new_state.rescue_child_state = self.rescue_child_state.copy()
139 if self.always_child_state is not None:
140 new_state.always_child_state = self.always_child_state.copy()
141 return new_state
142
143
144 class PlayIterator:
145
146 def __init__(self, inventory, play, play_context, variable_manager, all_vars, start_at_done=False):
147 self._play = play
148 self._blocks = []
149 self._variable_manager = variable_manager
150
151 setup_block = Block(play=self._play)
152 # Gathering facts with run_once would copy the facts from one host to
153 # the others.
154 setup_block.run_once = False
155 setup_task = Task(block=setup_block)
156 setup_task.action = 'gather_facts'
157 setup_task.name = 'Gathering Facts'
158 setup_task.args = {}
159
160 # Unless play is specifically tagged, gathering should 'always' run
161 if not self._play.tags:
162 setup_task.tags = ['always']
163
164 # Default options to gather
165 for option in ('gather_subset', 'gather_timeout', 'fact_path'):
166 value = getattr(self._play, option, None)
167 if value is not None:
168 setup_task.args[option] = value
169
170 setup_task.set_loader(self._play._loader)
171 # short circuit fact gathering if the entire playbook is conditional
172 if self._play._included_conditional is not None:
173 setup_task.when = self._play._included_conditional[:]
174 setup_block.block = [setup_task]
175
176 validation_task = Task.load({
177 'name': f'Validating arguments against arg spec {self._play.validate_argspec}',
178 'action': 'ansible.builtin.validate_argument_spec',
179 'args': {
180 # 'provided_arguments': {}, # allow configuration via module_defaults
181 'argument_spec': self._play.argument_spec,
182 'validate_args_context': {
183 'type': 'play',
184 'name': self._play.validate_argspec,
185 'argument_spec_name': self._play.validate_argspec,
186 'path': self._play._metadata_path,
187 },
188 },
189 'tags': ['always'] if not self._play.tags else [],
190 }, block=setup_block)
191
192 validation_task.set_loader(self._play._loader)
193 if self._play._included_conditional is not None:
194 validation_task.when = self._play._included_conditional[:]
195 setup_block.block.append(validation_task)
196
197 setup_block = setup_block.filter_tagged_tasks(all_vars)
198 self._blocks.append(setup_block)
199
200 # keep flatten (no blocks) list of all tasks from the play
201 # used for the lockstep mechanism in the linear strategy
202 self.all_tasks = setup_block.get_tasks()
203
204 for block in self._play.compile():
205 new_block = block.filter_tagged_tasks(all_vars)
206 if new_block.has_tasks():
207 self._blocks.append(new_block)
208 self.all_tasks.extend(new_block.get_tasks())
209
210 # keep list of all handlers, it is copied into each HostState
211 # at the beginning of IteratingStates.HANDLERS
212 # the copy happens at each flush in order to restore the original
213 # list and remove any included handlers that might not be notified
214 # at the particular flush
215 self.handlers = [h for b in self._play.handlers for h in b.block]
216
217 self._host_states = {}
218 start_at_matched = False
219 batch = inventory.get_hosts(self._play.hosts, order=self._play.order)
220 self.batch_size = len(batch)
221 for host in batch:
222 self.set_state_for_host(host.name, HostState(blocks=self._blocks))
223 # if we're looking to start at a specific task, iterate through
224 # the tasks for this host until we find the specified task
225 if play_context.start_at_task is not None and not start_at_done:
226 while True:
227 (s, task) = self.get_next_task_for_host(host, peek=True)
228 if s.run_state == IteratingStates.COMPLETE:
229 break
230 if task.name == play_context.start_at_task or (task.name and fnmatch.fnmatch(task.name, play_context.start_at_task)) or \
231 task.get_name() == play_context.start_at_task or fnmatch.fnmatch(task.get_name(), play_context.start_at_task):
232 start_at_matched = True
233 break
234 self.set_state_for_host(host.name, s)
235
236 # finally, reset the host's state to IteratingStates.SETUP
237 if start_at_matched:
238 self._host_states[host.name].did_start_at_task = True
239 self._host_states[host.name].run_state = IteratingStates.SETUP
240
241 if start_at_matched:
242 # we have our match, so clear the start_at_task field on the
243 # play context to flag that we've started at a task (and future
244 # plays won't try to advance)
245 play_context.start_at_task = None
246
247 self.end_play = False
248 self.cur_task = 0
249
250 def get_host_state(self, host):
251 # Since we're using the PlayIterator to carry forward failed hosts,
252 # in the event that a previous host was not in the current inventory
253 # we create a stub state for it now
254 if host.name not in self._host_states:
255 self.set_state_for_host(host.name, HostState(blocks=[]))
256
257 return self._host_states[host.name].copy()
258
259 def get_next_task_for_host(self, host, peek=False):
260
261 display.debug("getting the next task for host %s" % host.name)
262 s = self.get_host_state(host)
263
264 task = None
265 if s.run_state == IteratingStates.COMPLETE:
266 display.debug("host %s is done iterating, returning" % host.name)
267 return (s, None)
268
269 (s, task) = self._get_next_task_from_state(s, host=host)
270
271 if not peek:
272 self.set_state_for_host(host.name, s)
273
274 display.debug("done getting next task for host %s" % host.name)
275 display.debug(" ^ state is: %s" % s)
276 return (s, task)
277
278 def _get_next_task_from_state(self, state, host):
279
280 task = None
281
282 # try and find the next task, given the current state.
283 while True:
284 # try to get the current block from the list of blocks, and
285 # if we run past the end of the list we know we're done with
286 # this block
287 try:
288 block = state._blocks[state.cur_block]
289 except IndexError:
290 state.run_state = IteratingStates.COMPLETE
291 return (state, None)
292
293 if state.run_state == IteratingStates.SETUP:
294 # Gather facts if the default is 'smart' and we have not yet
295 # done it for this host; or if 'explicit' and the play sets
296 # gather_facts to True; or if 'implicit' and the play does
297 # NOT explicitly set gather_facts to False.
298 gather_facts = len(self._blocks[0].block) >= 1
299 gathering = C.DEFAULT_GATHERING
300 implied = self._play.gather_facts is None or boolean(self._play.gather_facts, strict=False)
301 if gather_facts and (
302 (gathering == 'implicit' and implied) or
303 (gathering == 'explicit' and boolean(self._play.gather_facts, strict=False)) or
304 (gathering == 'smart' and implied and not self._variable_manager._facts_gathered_for_host(host.name))
305 ):
306 task = self._blocks[0].block[0]
307
308 state.run_state = IteratingStates.VALIDATE
309
310 elif state.run_state == IteratingStates.VALIDATE:
311 if len(self._blocks[0].block) >= 2 and self._play.validate_argspec:
312 task = self._blocks[0].block[1]
313
314 state.run_state = IteratingStates.TASKS
315 if not state.did_start_at_task:
316 state.cur_block += 1
317 state.cur_regular_task = 0
318 state.cur_rescue_task = 0
319 state.cur_always_task = 0
320 state.tasks_child_state = None
321 state.rescue_child_state = None
322 state.always_child_state = None
323
324 elif state.run_state == IteratingStates.TASKS:
325 # First, we check for a child task state that is not failed, and if we
326 # have one recurse into it for the next task. If we're done with the child
327 # state, we clear it and drop back to getting the next task from the list.
328 if state.tasks_child_state:
329 (state.tasks_child_state, task) = self._get_next_task_from_state(state.tasks_child_state, host=host)
330 if self._check_failed_state(state.tasks_child_state):
331 # failed child state, so clear it and move into the rescue portion
332 state.tasks_child_state = None
333 self._set_failed_state(state)
334 else:
335 # get the next task recursively
336 if task is None or state.tasks_child_state.run_state == IteratingStates.COMPLETE:
337 # we're done with the child state, so clear it and continue
338 # back to the top of the loop to get the next task
339 state.tasks_child_state = None
340 continue
341 else:
342 # First here, we check to see if we've failed anywhere down the chain
343 # of states we have, and if so we move onto the rescue portion. Otherwise,
344 # we check to see if we've moved past the end of the list of tasks. If so,
345 # we move into the always portion of the block, otherwise we get the next
346 # task from the list.
347 if self._check_failed_state(state):
348 state.run_state = IteratingStates.RESCUE
349 elif state.cur_regular_task >= len(block.block):
350 state.run_state = IteratingStates.ALWAYS
351 else:
352 task = block.block[state.cur_regular_task]
353 # if the current task is actually a child block, create a child
354 # state for us to recurse into on the next pass
355 if isinstance(task, Block):
356 state.tasks_child_state = HostState(blocks=[task])
357 state.tasks_child_state.run_state = IteratingStates.TASKS
358 # since we've created the child state, clear the task
359 # so we can pick up the child state on the next pass
360 task = None
361 state.cur_regular_task += 1
362
363 elif state.run_state == IteratingStates.RESCUE:
364 # The process here is identical to IteratingStates.TASKS, except instead
365 # we move into the always portion of the block.
366 if state.rescue_child_state:
367 (state.rescue_child_state, task) = self._get_next_task_from_state(state.rescue_child_state, host=host)
368 if self._check_failed_state(state.rescue_child_state):
369 state.rescue_child_state = None
370 self._set_failed_state(state)
371 else:
372 if task is None or state.rescue_child_state.run_state == IteratingStates.COMPLETE:
373 state.rescue_child_state = None
374 continue
375 else:
376 if state.fail_state & FailedStates.RESCUE == FailedStates.RESCUE:
377 state.run_state = IteratingStates.ALWAYS
378 elif state.cur_rescue_task >= len(block.rescue):
379 if len(block.rescue) > 0:
380 state.fail_state = FailedStates.NONE
381 state.run_state = IteratingStates.ALWAYS
382 state.did_rescue = True
383 else:
384 task = block.rescue[state.cur_rescue_task]
385 if isinstance(task, Block):
386 state.rescue_child_state = HostState(blocks=[task])
387 state.rescue_child_state.run_state = IteratingStates.TASKS
388 task = None
389 state.cur_rescue_task += 1
390
391 elif state.run_state == IteratingStates.ALWAYS:
392 # And again, the process here is identical to IteratingStates.TASKS, except
393 # instead we either move onto the next block in the list, or we set the
394 # run state to IteratingStates.COMPLETE in the event of any errors, or when we
395 # have hit the end of the list of blocks.
396 if state.always_child_state:
397 (state.always_child_state, task) = self._get_next_task_from_state(state.always_child_state, host=host)
398 if self._check_failed_state(state.always_child_state):
399 state.always_child_state = None
400 self._set_failed_state(state)
401 else:
402 if task is None or state.always_child_state.run_state == IteratingStates.COMPLETE:
403 state.always_child_state = None
404 continue
405 else:
406 if state.cur_always_task >= len(block.always):
407 if state.fail_state != FailedStates.NONE:
408 state.run_state = IteratingStates.COMPLETE
409 else:
410 state.cur_block += 1
411 state.cur_regular_task = 0
412 state.cur_rescue_task = 0
413 state.cur_always_task = 0
414 state.run_state = IteratingStates.TASKS
415 state.tasks_child_state = None
416 state.rescue_child_state = None
417 state.always_child_state = None
418 state.did_rescue = False
419 else:
420 task = block.always[state.cur_always_task]
421 if isinstance(task, Block):
422 state.always_child_state = HostState(blocks=[task])
423 state.always_child_state.run_state = IteratingStates.TASKS
424 task = None
425 state.cur_always_task += 1
426
427 elif state.run_state == IteratingStates.HANDLERS:
428 if state.update_handlers:
429 # reset handlers for HostState since handlers from include_tasks
430 # might be there from previous flush
431 state.handlers = self.handlers[:]
432 state.update_handlers = False
433
434 while True:
435 try:
436 task = state.handlers[state.cur_handlers_task]
437 except IndexError:
438 task = None
439 state.cur_handlers_task = 0
440 state.run_state = state.pre_flushing_run_state
441 state.update_handlers = True
442 break
443 else:
444 state.cur_handlers_task += 1
445 if task.is_host_notified(host):
446 return state, task
447
448 elif state.run_state == IteratingStates.COMPLETE:
449 return (state, None)
450
451 # if something above set the task, break out of the loop now
452 if task:
453 # skip implicit flush_handlers if there are no handlers notified
454 if (
455 task.implicit
456 and task._get_meta() == 'flush_handlers'
457 and (
458 # the state store in the `state` variable could be a nested state,
459 # notifications are always stored in the top level state, get it here
460 not self.get_state_for_host(host.name).handler_notifications
461 # in case handlers notifying other handlers, the notifications are not
462 # saved in `handler_notifications` and handlers are notified directly
463 # to prevent duplicate handler runs, so check whether any handler
464 # is notified
465 and all(not h.notified_hosts for h in self.handlers)
466 )
467 ):
468 display.debug("No handler notifications for %s, skipping." % host.name)
469 elif (
470 (role := task._role)
471 and role._metadata.allow_duplicates is False
472 and host.name in self._play._get_cached_role(role)._completed
473 ):
474 display.debug("'%s' skipped because role has already run" % task)
475 else:
476 break
477
478 return (state, task)
479
480 def _set_failed_state(self, state):
481 if state.run_state == IteratingStates.SETUP:
482 state.fail_state |= FailedStates.SETUP
483 state.run_state = IteratingStates.COMPLETE
484 elif state.run_state == IteratingStates.VALIDATE:
485 state.fail_state |= FailedStates.VALIDATE
486 state.run_state = IteratingStates.COMPLETE
487 elif state.run_state == IteratingStates.TASKS:
488 if state.tasks_child_state is not None:
489 state.tasks_child_state = self._set_failed_state(state.tasks_child_state)
490 else:
491 state.fail_state |= FailedStates.TASKS
492 if state._blocks[state.cur_block].rescue:
493 state.run_state = IteratingStates.RESCUE
494 elif state._blocks[state.cur_block].always:
495 state.run_state = IteratingStates.ALWAYS
496 else:
497 state.run_state = IteratingStates.COMPLETE
498 elif state.run_state == IteratingStates.RESCUE:
499 if state.rescue_child_state is not None:
500 state.rescue_child_state = self._set_failed_state(state.rescue_child_state)
501 else:
502 state.fail_state |= FailedStates.RESCUE
503 if state._blocks[state.cur_block].always:
504 state.run_state = IteratingStates.ALWAYS
505 else:
506 state.run_state = IteratingStates.COMPLETE
507 elif state.run_state == IteratingStates.ALWAYS:
508 if state.always_child_state is not None:
509 state.always_child_state = self._set_failed_state(state.always_child_state)
510 else:
511 state.fail_state |= FailedStates.ALWAYS
512 state.run_state = IteratingStates.COMPLETE
513 return state
514
515 def mark_host_failed(self, host):
516 s = self.get_host_state(host)
517 display.debug("marking host %s failed, current state: %s" % (host, s))
518 if s.run_state == IteratingStates.HANDLERS:
519 # we are failing `meta: flush_handlers`, so just reset the state to whatever
520 # it was before and let `_set_failed_state` figure out the next state
521 s.run_state = s.pre_flushing_run_state
522 s.update_handlers = True
523 s = self._set_failed_state(s)
524 display.debug("^ failed state is now: %s" % s)
525 self.set_state_for_host(host.name, s)
526 self._play._removed_hosts.append(host.name)
527
528 def get_failed_hosts(self):
529 return dict((host, True) for (host, state) in self._host_states.items() if self._check_failed_state(state))
530
531 def _check_failed_state(self, state):
532 if state is None:
533 return False
534 elif state.run_state == IteratingStates.RESCUE and self._check_failed_state(state.rescue_child_state):
535 return True
536 elif state.run_state == IteratingStates.ALWAYS and self._check_failed_state(state.always_child_state):
537 return True
538 elif state.fail_state != FailedStates.NONE:
539 if state.run_state == IteratingStates.RESCUE and state.fail_state & FailedStates.RESCUE == 0:
540 return False
541 elif state.run_state == IteratingStates.ALWAYS and state.fail_state & FailedStates.ALWAYS == 0:
542 return False
543 else:
544 return not (state.did_rescue and state.fail_state & FailedStates.ALWAYS == 0)
545 elif state.run_state == IteratingStates.TASKS and self._check_failed_state(state.tasks_child_state):
546 cur_block = state._blocks[state.cur_block]
547 if len(cur_block.rescue) > 0 and state.fail_state & FailedStates.RESCUE == 0:
548 return False
549 else:
550 return True
551 return False
552
553 def is_failed(self, host):
554 s = self.get_host_state(host)
555 return self._check_failed_state(s)
556
557 def clear_host_errors(self, host):
558 self._clear_state_errors(self.get_state_for_host(host.name))
559
560 def _clear_state_errors(self, state: HostState) -> None:
561 state.fail_state = FailedStates.NONE
562
563 if state.tasks_child_state is not None:
564 self._clear_state_errors(state.tasks_child_state)
565 elif state.rescue_child_state is not None:
566 self._clear_state_errors(state.rescue_child_state)
567 elif state.always_child_state is not None:
568 self._clear_state_errors(state.always_child_state)
569
570 def get_active_state(self, state):
571 """
572 Finds the active state, recursively if necessary when there are child states.
573 """
574 if state.run_state == IteratingStates.TASKS and state.tasks_child_state is not None:
575 return self.get_active_state(state.tasks_child_state)
576 elif state.run_state == IteratingStates.RESCUE and state.rescue_child_state is not None:
577 return self.get_active_state(state.rescue_child_state)
578 elif state.run_state == IteratingStates.ALWAYS and state.always_child_state is not None:
579 return self.get_active_state(state.always_child_state)
580 return state
581
582 def is_any_block_rescuing(self, state):
583 """
584 Given the current HostState state, determines if the current block, or any child blocks,
585 are in rescue mode.
586 """
587 if state.run_state in (IteratingStates.TASKS, IteratingStates.HANDLERS) and state.get_current_block().rescue:
588 return True
589 if state.tasks_child_state is not None:
590 return self.is_any_block_rescuing(state.tasks_child_state)
591 if state.rescue_child_state is not None:
592 return self.is_any_block_rescuing(state.rescue_child_state)
593 if state.always_child_state is not None:
594 return self.is_any_block_rescuing(state.always_child_state)
595 return False
596
597 def _insert_tasks_into_state(self, state, task_list):
598 # if we've failed at all, or if the task list is empty, just return the current state
599 if (state.fail_state != FailedStates.NONE and state.run_state == IteratingStates.TASKS) or not task_list:
600 return state
601
602 if state.run_state == IteratingStates.TASKS:
603 if state.tasks_child_state:
604 state.tasks_child_state = self._insert_tasks_into_state(state.tasks_child_state, task_list)
605 else:
606 target_block = state._blocks[state.cur_block].copy(exclude_tasks=True)
607 target_block.block[state.cur_regular_task:state.cur_regular_task] = task_list
608 state._blocks[state.cur_block] = target_block
609 elif state.run_state == IteratingStates.RESCUE:
610 if state.rescue_child_state:
611 state.rescue_child_state = self._insert_tasks_into_state(state.rescue_child_state, task_list)
612 else:
613 target_block = state._blocks[state.cur_block].copy(exclude_tasks=True)
614 target_block.rescue[state.cur_rescue_task:state.cur_rescue_task] = task_list
615 state._blocks[state.cur_block] = target_block
616 elif state.run_state == IteratingStates.ALWAYS:
617 if state.always_child_state:
618 state.always_child_state = self._insert_tasks_into_state(state.always_child_state, task_list)
619 else:
620 target_block = state._blocks[state.cur_block].copy(exclude_tasks=True)
621 target_block.always[state.cur_always_task:state.cur_always_task] = task_list
622 state._blocks[state.cur_block] = target_block
623 elif state.run_state == IteratingStates.HANDLERS:
624 state.handlers[state.cur_handlers_task:state.cur_handlers_task] = [h for b in task_list for h in b.block]
625
626 return state
627
628 def add_tasks(self, host, task_list):
629 self.set_state_for_host(host.name, self._insert_tasks_into_state(self.get_host_state(host), task_list))
630
631 @property
632 def host_states(self):
633 return self._host_states
634
635 def get_state_for_host(self, hostname: str) -> HostState:
636 return self._host_states[hostname]
637
638 def set_state_for_host(self, hostname: str, state: HostState) -> None:
639 if not isinstance(state, HostState):
640 raise AnsibleAssertionError('Expected state to be a HostState but was a %s' % type(state))
641 self._host_states[hostname] = state
642
643 def set_run_state_for_host(self, hostname: str, run_state: IteratingStates) -> None:
644 if not isinstance(run_state, IteratingStates):
645 raise AnsibleAssertionError('Expected run_state to be a IteratingStates but was %s' % (type(run_state)))
646 self._host_states[hostname].run_state = run_state
647
648 def set_fail_state_for_host(self, hostname: str, fail_state: FailedStates) -> None:
649 if not isinstance(fail_state, FailedStates):
650 raise AnsibleAssertionError('Expected fail_state to be a FailedStates but was %s' % (type(fail_state)))
651 self._host_states[hostname].fail_state = fail_state
652
653 def add_notification(self, hostname: str, notification: str) -> None:
654 # preserve order
655 host_state = self._host_states[hostname]
656 if notification not in host_state.handler_notifications:
657 host_state.handler_notifications.append(notification)
658
659 def clear_notification(self, hostname: str, notification: str) -> None:
660 self._host_states[hostname].handler_notifications.remove(notification)
661
662 def end_host(self, hostname: str) -> None:
663 """Used by ``end_host``, ``end_batch`` and ``end_play`` meta tasks to end executing given host."""
664 state = self.get_active_state(self.get_state_for_host(hostname))
665 if state.run_state == IteratingStates.RESCUE:
666 # This is a special case for when ending a host occurs in rescue.
667 # By definition the meta task responsible for ending the host
668 # is the last task, so we need to clear the fail state to mark
669 # the host as rescued.
670 # The reason we need to do that is because this operation is
671 # normally done when PlayIterator transitions from rescue to
672 # always when only then we can say that rescue didn't fail
673 # but with ending a host via meta task, we don't get to that transition.
674 self.set_fail_state_for_host(hostname, FailedStates.NONE)
675 self.set_run_state_for_host(hostname, IteratingStates.COMPLETE)
676 self._play._removed_hosts.append(hostname)