@ansible-flow/assets 1.1.0-rc.3 → 1.2.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,189 @@
1
+ # Safe render at a pause (ADR-0040 §5, AFD-370): evaluate, watch, pause point conditions and log
2
+ # messages. Before rendering, the Jinja AST is checked: lookup, query and q calls and the vault and
3
+ # unvault filters are refused. The render runs in a forked child: lookups blocked while it runs
4
+ # (also those a lazy variable runs, which disable_lookups misses), a memory cap, and a time limit
5
+ # the parent enforces by killing the child. No SIGALRM: an in-process alarm corrupted the template
6
+ # context on 2.19 and did not stop a loop on 2.21. Nothing the child changes reaches the run.
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ import resource
12
+ import select
13
+ import signal
14
+ import time
15
+ from collections.abc import Callable
16
+
17
+ try:
18
+ from ansible._internal._datatag._tags import TrustedAsTemplate
19
+
20
+ TAGS = True
21
+ except ImportError: # pragma: no cover
22
+ TAGS = False
23
+
24
+ TIME_LIMIT = 2.0
25
+ MAX_TIME_LIMIT = 10.0
26
+ MEMORY_EXTRA = 512 * 1024 * 1024
27
+ EXPR_LIMIT = 4000
28
+ # Lookups a lazy variable may still run while rendering: they read only what is already there.
29
+ LOOKUP_ALLOW = {
30
+ "vars", "varnames", "items", "list", "dict", "indexed_items", "sequence", "subelements",
31
+ "nested", "together", "cartesian",
32
+ } # fmt: skip
33
+ LOOKUP_CALLS = {"lookup", "query", "q"}
34
+ FILTER_DENY = {"vault", "unvault"}
35
+
36
+
37
+ class Blocked(Exception):
38
+ pass
39
+
40
+
41
+ def _short(name: object) -> str:
42
+ return str(name).rsplit(".", 1)[-1]
43
+
44
+
45
+ def precheck(expr: str, environment) -> str | None:
46
+ """Why `expr` is refused before anything renders it, in plain words; None when it may run."""
47
+ if not expr.strip():
48
+ return "Nothing to evaluate"
49
+ if len(expr) > EXPR_LIMIT:
50
+ return f"The expression is longer than {EXPR_LIMIT} characters"
51
+ if any(m in expr for m in ("{{", "}}", "{%", "%}", "{#", "#}")):
52
+ return "Write an expression without {{ }} or {% %}"
53
+ return check_template("{{ " + expr + " }}", environment, "Not a Jinja expression")
54
+
55
+
56
+ def check_template(text: str, environment, what: str = "Not a Jinja template") -> str | None:
57
+ """Why a template (a log message, an expression in braces) is refused; None when it may run."""
58
+ try:
59
+ from jinja2 import nodes
60
+
61
+ ast = environment.parse(text)
62
+ except Exception as ex: # noqa: BLE001
63
+ return f"{what}: {str(ex)[:300]}"
64
+ for call in ast.find_all(nodes.Call):
65
+ if isinstance(call.node, nodes.Name) and call.node.name in LOOKUP_CALLS:
66
+ return f"{call.node.name}() is not allowed while debugging: it can read or run things"
67
+ for name in ast.find_all(nodes.Name):
68
+ if name.name in LOOKUP_CALLS:
69
+ return f"{name.name} is not allowed while debugging: it can read or run things"
70
+ for f in ast.find_all(nodes.Filter):
71
+ if _short(f.name) in FILTER_DENY:
72
+ return f"The {f.name} filter is not allowed while debugging"
73
+ for attr in ast.find_all(nodes.Getattr):
74
+ if str(attr.attr).startswith("_"):
75
+ return "Attributes starting with _ are not allowed while debugging"
76
+ return None
77
+
78
+
79
+ def names_in(expr: str, environment) -> set[str]:
80
+ """The variable names an expression reads."""
81
+ try:
82
+ from jinja2 import nodes
83
+
84
+ ast = environment.parse("{{ " + expr + " }}")
85
+ except Exception: # noqa: BLE001
86
+ return set()
87
+ return {n.name for n in ast.find_all(nodes.Name)}
88
+
89
+
90
+ def block_lookups() -> None:
91
+ """Every lookup outside LOOKUP_ALLOW raises. Patches the module global the templating engine
92
+ uses (a private one: the engine suite checks it on every core): call it in the child only."""
93
+ import ansible._internal._templating._jinja_plugins as jp
94
+
95
+ real = jp.lookup_loader
96
+
97
+ class _Guard:
98
+ def get(self, name, *a, **kw):
99
+ if _short(name) not in LOOKUP_ALLOW:
100
+ raise Blocked(f"lookup {name!r} is not allowed while debugging")
101
+ return real.get(name, *a, **kw)
102
+
103
+ def __getattr__(self, attr):
104
+ return getattr(real, attr)
105
+
106
+ jp.lookup_loader = _Guard()
107
+
108
+
109
+ def trusted(text: str) -> object:
110
+ return TrustedAsTemplate().tag(text) if TAGS else text
111
+
112
+
113
+ def _vm_bytes() -> int:
114
+ try:
115
+ with open("/proc/self/statm") as f:
116
+ return int(f.read().split()[0]) * os.sysconf("SC_PAGE_SIZE")
117
+ except (OSError, ValueError):
118
+ return 0
119
+
120
+
121
+ def error_text(ex: BaseException) -> str:
122
+ text = str(ex).strip().splitlines()
123
+ first = text[0] if text else ""
124
+ if isinstance(ex, MemoryError):
125
+ return "The expression needed more memory than a debugger may use"
126
+ return f"{type(ex).__name__}: {first[:400]}" if first else type(ex).__name__
127
+
128
+
129
+ def in_child(fn: Callable[[], object], timeout: float = TIME_LIMIT) -> dict:
130
+ """Runs fn() in a forked child with a memory cap; the parent kills it at `timeout`.
131
+ Returns {"value": <JSON>} or {"error": <text>}, and the time it took in ms."""
132
+ timeout = max(0.1, min(float(timeout), MAX_TIME_LIMIT))
133
+ r, w = os.pipe()
134
+ t0 = time.perf_counter()
135
+ pid = os.fork()
136
+ if pid == 0: # the child: no display, no logging; it ends with os._exit
137
+ try:
138
+ os.close(r)
139
+ base = _vm_bytes()
140
+ if base:
141
+ limit = base + MEMORY_EXTRA
142
+ resource.setrlimit(resource.RLIMIT_AS, (limit, limit))
143
+ block_lookups()
144
+ data = json.dumps({"value": fn()}, default=str).encode()
145
+ except BaseException as ex: # noqa: BLE001
146
+ try:
147
+ data = json.dumps({"error": error_text(ex)}).encode()
148
+ except BaseException: # noqa: BLE001
149
+ data = b'{"error": "The expression failed"}'
150
+ try:
151
+ view = memoryview(data)
152
+ while view:
153
+ n = os.write(w, view)
154
+ view = view[n:]
155
+ finally:
156
+ os._exit(0)
157
+ os.close(w)
158
+ chunks: list[bytes] = []
159
+ deadline = time.monotonic() + timeout
160
+ killed = False
161
+ try:
162
+ while True:
163
+ left = deadline - time.monotonic()
164
+ if left <= 0:
165
+ os.kill(pid, signal.SIGKILL)
166
+ killed = True
167
+ break
168
+ ready, _, _ = select.select([r], [], [], left)
169
+ if ready:
170
+ chunk = os.read(r, 65536)
171
+ if not chunk:
172
+ break
173
+ chunks.append(chunk)
174
+ finally:
175
+ os.close(r)
176
+ os.waitpid(pid, 0)
177
+ ms = round((time.perf_counter() - t0) * 1000, 1)
178
+ if killed:
179
+ return {
180
+ "error": f"Stopped after the time limit of {timeout:g} s",
181
+ "ms": ms,
182
+ "timeout": True,
183
+ }
184
+ try:
185
+ out = json.loads(b"".join(chunks) or b'{"error": "No answer (the memory limit?)"}')
186
+ except ValueError:
187
+ out = {"error": "No answer (the memory limit?)"}
188
+ out["ms"] = ms
189
+ return out
@@ -7,8 +7,13 @@
7
7
  # local, WSL, SSH or container run (nothing listens on a port):
8
8
  # - run -> driver: pause, resume and stopped events, appended to events.jsonl (AFD_EVENTS);
9
9
  # - driver -> run: control.json (AFD_STEP_CONTROL), replaced whole (write a temporary file, then
10
- # rename): {"v": 1, "command": "step"|"continue"|"pause"|"stop", "points": [node ids],
11
- # "reply": "<pause id>"|null}.
10
+ # rename): {"v": 1, "command": "step"|"continue"|"pause"|"stop"|"retry", "points": [node ids or
11
+ # {node, condition?, hits?, log?}], "reply": "<pause id>"|null, "after"?, "failures"?, "hits"?}.
12
+ #
13
+ # Debug runs (AFD_DEBUG=1, ADR-0040) add, from probe/afd_lib (loaded only then):
14
+ # - requests answered while paused (request-<n>.json -> answer-<n>.json beside control.json);
15
+ # - pause points with a condition, a hit count or a log message;
16
+ # - a pause after a step's play when hosts failed it (kind failure), with Retry.
12
17
  from __future__ import annotations
13
18
 
14
19
  import json
@@ -33,6 +38,9 @@ DOCUMENTATION = """
33
38
  - AFD_STEP_TIMEOUT (seconds, default 3600) ends a pause nobody answers; the run then stops.
34
39
  - AFD_STEP_INSIDE names the step a run starts inside (an approval's later segment): no pause
35
40
  before its first play.
41
+ - AFD_DEBUG=1 makes it a debug run (ADR-0040): variables, evaluate and watch while paused,
42
+ pause points with a condition, a hit count or a log message, and a pause on failure with
43
+ Retry.
36
44
  author: Ansible Flow Designer
37
45
  """
38
46
 
@@ -46,11 +54,47 @@ def _paused_line(play: str, hosts: int) -> str:
46
54
  return f"Paused before {title}: {waits} for Step, Continue or Stop"
47
55
 
48
56
 
57
+ def _failed_line(play: str, failed: int) -> str:
58
+ title = re.sub(r"^\[[^\]]*\]\s*", "", play) or play
59
+ who = "1 host" if failed == 1 else f"{failed} hosts"
60
+ return f"{who} failed {title}: Retry, Continue or Stop"
61
+
62
+
49
63
  VERSION = 1
50
64
  POLL_S = 0.1
51
65
  DEFAULT_TIMEOUT_S = 3600.0
52
66
  # Pausing again: the driver's command until it changes; step and pause stop at the next step.
53
67
  PAUSING = ("step", "pause")
68
+ ANSWERS = ("step", "continue", "stop")
69
+ # The generator's failure facts (optionA FAILURE_FACTS) and Ansible's own in a rescue.
70
+ FAIL_FACTS = (
71
+ "afd_failed_result",
72
+ "afd_failed_task",
73
+ "afd_failed_node",
74
+ "ansible_failed_result",
75
+ "ansible_failed_task",
76
+ )
77
+ # A rolling subflow (AFD-55) is one play with serial for all its steps.
78
+ ROLLING = re.compile(r": rolling, .+ at a time$")
79
+ NO_RETRY_ROLLING = (
80
+ "Retry is not offered in a rolling subflow: its steps run as one play for each batch. "
81
+ "Rerun from this step as a new run instead."
82
+ )
83
+ NO_RETRY_HARD = (
84
+ "Retry is not offered for a host that failed outside the step's rescue (a failure "
85
+ "percentage, an include error). Rerun from this step as a new run instead."
86
+ )
87
+ _MISSING = object()
88
+
89
+
90
+ def _debug_lib():
91
+ """probe/afd_lib, beside this folder: loaded in debug runs only."""
92
+ probe = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
93
+ if probe not in sys.path:
94
+ sys.path.insert(0, probe)
95
+ from afd_lib import debug # noqa: PLC0415
96
+
97
+ return debug
54
98
 
55
99
 
56
100
  class _State:
@@ -72,6 +116,25 @@ class _State:
72
116
  self.last_node: str | None = os.environ.get("AFD_STEP_INSIDE") or None
73
117
  self.stopped = False
74
118
  self.good: dict = {}
119
+ # ADR-0040: a debug run; the library and its session, or why there is none.
120
+ self.debug_on = os.environ.get("AFD_DEBUG") == "1" and bool(self.control)
121
+ self.debug = None
122
+ self.no_debug: str | None = None
123
+ if self.debug_on:
124
+ try:
125
+ lib = _debug_lib()
126
+ self.no_debug = lib.unavailable()
127
+ if not self.no_debug:
128
+ self.debug = lib.Session()
129
+ # Hit counts carried by the driver from an approval's earlier segments.
130
+ hits = self.read().get("hits")
131
+ if isinstance(hits, dict):
132
+ for k, v in hits.items():
133
+ if isinstance(v, int) and not isinstance(v, bool):
134
+ self.debug.hits[str(k)] = v
135
+ except Exception as ex: # noqa: BLE001 - the run goes on step by step
136
+ self.no_debug = f"The debugger could not start: {type(ex).__name__}: {ex}"[:300]
137
+ self.lib = sys.modules.get("afd_lib.debug") if self.debug else None
75
138
 
76
139
  def read(self) -> dict:
77
140
  """The driver's last control.json. While it is being replaced (or a half-written one is
@@ -93,12 +156,59 @@ class _State:
93
156
  with open(self.events, "a", encoding="utf-8") as f:
94
157
  f.write(json.dumps(event, default=str) + "\n")
95
158
 
159
+ def failures(self) -> dict:
160
+ """Which failures pause a debug run: a host failed (on by default), unreachable."""
161
+ f = self.read().get("failures")
162
+ f = f if isinstance(f, dict) else {}
163
+ return {
164
+ "failed": f.get("failed", True) is not False,
165
+ "unreachable": f.get("unreachable") is True,
166
+ }
167
+
168
+
169
+ def _points(control: dict) -> dict[str, dict]:
170
+ """The pause points by node: a bare id, or {node, condition?, hits?, log?}."""
171
+ out: dict[str, dict] = {}
172
+ points = control.get("points")
173
+ for p in points if isinstance(points, list) else []:
174
+ if isinstance(p, str):
175
+ out[p] = {"node": p}
176
+ elif isinstance(p, dict) and isinstance(p.get("node"), str):
177
+ out[p["node"]] = p
178
+ return out
179
+
180
+
181
+ def _settings(point: dict) -> bool:
182
+ return any(point.get(k) not in (None, "", 0) for k in ("condition", "hits", "log"))
183
+
184
+
185
+ def _stepping(control: dict) -> bool:
186
+ command = control.get("command")
187
+ # After Retry the run goes on as the driver went before it (`after`: step or continue).
188
+ return command in PAUSING or (command == "retry" and control.get("after") in PAUSING)
189
+
96
190
 
97
191
  def _wants_pause(control: dict, node: str) -> bool:
98
- if control.get("command") in PAUSING:
192
+ """Outside a debug run: point settings are not read; a log-only point never pauses."""
193
+ if _stepping(control):
99
194
  return True
100
- points = control.get("points")
101
- return isinstance(points, list) and node in points
195
+ point = _points(control).get(node)
196
+ if point is None:
197
+ return False
198
+ return not (point.get("log") and not point.get("condition") and not point.get("hits"))
199
+
200
+
201
+ def _msg(result: object) -> str:
202
+ if not isinstance(result, dict):
203
+ return ""
204
+ parts = [str(result.get("msg") or result.get("reason") or "")]
205
+ rc = result.get("rc")
206
+ if rc not in (None, 0):
207
+ parts.append(f"rc={rc}")
208
+ err = result.get("stderr")
209
+ if err:
210
+ parts.append(str(err)[:200])
211
+ return "; ".join(p for p in parts if p)[:500]
102
212
 
103
213
 
104
214
  class StrategyModule(LinearStrategy):
@@ -116,55 +226,118 @@ class StrategyModule(LinearStrategy):
116
226
  node = str(node) if node else None
117
227
  if state.stopped:
118
228
  return self._tqm.RUN_FAILED_BREAK_PLAY
229
+ if state.debug is not None:
230
+ state.debug.note_play(play)
119
231
  # The first play of a step only: a step's arriving and route plays go on with it.
120
232
  if node and node != state.last_node and state.control:
121
233
  self._set_hosts_cache(play)
122
- hosts = [h.get_name() for h in self.get_hosts_left(iterator)]
234
+ hosts = list(self.get_hosts_left(iterator))
123
235
  # A play no host reaches is not where a step starts for anyone.
124
236
  if hosts:
125
237
  state.last_node = node
126
- if self._afd_gate(state, node, play.get_name(), hosts) == "stop":
238
+ if self._afd_gate(state, node, play, hosts) == "stop":
127
239
  state.stopped = True
128
240
  return self._tqm.RUN_FAILED_BREAK_PLAY
241
+ if node and state.debug is not None:
242
+ return self._afd_run_watching(state, node, iterator, play_context)
129
243
  return super().run(iterator, play_context)
130
244
 
131
- def _afd_gate(self, state: _State, node: str, name: str, hosts: list[str]) -> str:
245
+ # ---- the step gate ---------------------------------------------------------------------
246
+ def _afd_gate(self, state: _State, node: str, play, hosts: list) -> str:
132
247
  """Pauses before `node` when the driver wants it; returns step, continue or stop."""
248
+ name = play.get_name()
249
+ names = [h.get_name() for h in hosts]
133
250
  control = state.read()
134
251
  if control.get("command") == "stop":
135
- state.emit(event="stopped", node=node, play=name, hosts=hosts, reason="driver")
252
+ state.emit(event="stopped", node=node, play=name, hosts=names, reason="driver")
136
253
  return "stop"
137
- if not _wants_pause(control, node):
254
+ if state.debug is None:
255
+ if not _wants_pause(control, node):
256
+ return "continue"
257
+ return self._afd_pause(
258
+ state, node, play, hosts, "step" if _stepping(control) else "point"
259
+ )
260
+ kind = "step" if _stepping(control) else None
261
+ extra: dict = {}
262
+ point = _points(control).get(node)
263
+ if point is not None and _settings(point):
264
+ found = state.lib.at_point(state.debug, self, play, hosts, node, point)
265
+ for e in found["events"]:
266
+ state.emit(**e)
267
+ if found["pause"]:
268
+ kind = "condition" if point.get("condition") or point.get("hits") else "point"
269
+ if found["matched"]:
270
+ extra["matched"] = found["matched"]
271
+ elif point is not None:
272
+ kind = "point"
273
+ if kind is None:
138
274
  return "continue"
275
+ return self._afd_pause(state, node, play, hosts, kind, **extra)
276
+
277
+ def _afd_pause(self, state: _State, node: str, play, hosts: list, kind: str, **extra) -> str:
278
+ """Waits at a pause for the driver's answer, serving debugger requests meanwhile."""
279
+ name = play.get_name()
280
+ names = [h.get_name() for h in hosts]
139
281
  state.count += 1
140
282
  pause = f"{state.token}-{state.count}"
141
- state.emit(
142
- event="pause",
143
- id=pause,
144
- node=node,
145
- play=name,
146
- hosts=hosts,
147
- timeout=state.timeout,
148
- )
149
- # AFS-205: in plain words, once: "Paused before Read facts: 2 hosts wait for Step, ...".
150
- display.display(_paused_line(name, len(hosts)))
283
+ refused = extra.pop("refused", None)
284
+ event: dict = {
285
+ "event": "pause",
286
+ "id": pause,
287
+ "node": node,
288
+ "play": name,
289
+ "hosts": names,
290
+ "timeout": state.timeout,
291
+ }
292
+ if state.debug_on:
293
+ event["kind"] = kind
294
+ event.update(extra)
295
+ if refused:
296
+ event["retry"] = {"refused": refused}
297
+ if state.debug is not None:
298
+ event["debug"] = True
299
+ elif state.no_debug:
300
+ event["debug"] = False
301
+ event["why"] = state.no_debug
302
+ state.emit(**event)
303
+ if kind == "failure":
304
+ failed = extra.get("failed") or []
305
+ display.display(_failed_line(name, len(failed)))
306
+ for f in failed:
307
+ display.display(f" {f['host']}: {f.get('task') or ''}: {f.get('msg') or ''}"[:300])
308
+ else:
309
+ # AFS-205: in plain words, once: "Paused before Read facts: 2 hosts wait for Step, ...".
310
+ display.display(_paused_line(name, len(names)))
151
311
  # Out now, before anyone answers: a pipe (a server's run) holds it back otherwise, and the
152
312
  # line came after who said Step.
153
313
  sys.stdout.flush()
314
+ gate = state.debug.gate(self, play, hosts, pause) if state.debug is not None else None
315
+ folder = os.path.dirname(state.control) or "."
316
+ answers = (*ANSWERS, "retry") if kind == "failure" else ANSWERS
317
+ told = False
154
318
  deadline = time.monotonic() + state.timeout
155
319
  while True:
156
320
  control = state.read()
157
321
  command = control.get("command")
158
- if control.get("reply") == pause and command in ("step", "continue", "stop"):
159
- break
322
+ if control.get("reply") == pause and command in answers:
323
+ if command == "retry" and refused:
324
+ if not told:
325
+ state.emit(
326
+ event="refused", id=pause, node=node, command="retry", why=refused
327
+ )
328
+ told = True
329
+ else:
330
+ break
160
331
  # A stop needs no reply: it may come from a driver that missed this pause.
161
332
  if command == "stop":
162
333
  break
163
- # AFD-347 seam: while paused, requests about this pause (variables, evaluate, set) are
164
- # served here, with the play, hosts and variable manager at hand. Not built (AFD-346).
334
+ # ADR-0040: while paused, requests about this pause are answered here, with the play,
335
+ # its hosts and the variable manager at hand.
336
+ if gate is not None:
337
+ gate.serve(folder)
165
338
  if time.monotonic() > deadline:
166
339
  state.emit(
167
- event="stopped", id=pause, node=node, play=name, hosts=hosts, reason="timeout"
340
+ event="stopped", id=pause, node=node, play=name, hosts=names, reason="timeout"
168
341
  )
169
342
  display.warning(
170
343
  f"Nobody answered the pause for {int(state.timeout)} s: the run stops here"
@@ -173,8 +346,178 @@ class StrategyModule(LinearStrategy):
173
346
  time.sleep(POLL_S)
174
347
  if command == "stop":
175
348
  state.emit(
176
- event="stopped", id=pause, node=node, play=name, hosts=hosts, reason="driver"
349
+ event="stopped", id=pause, node=node, play=name, hosts=names, reason="driver"
177
350
  )
178
351
  return "stop"
179
352
  state.emit(event="resume", id=pause, node=node, command=command)
180
353
  return command
354
+
355
+ # ---- pause on failure, Retry (ADR-0040 §7) ---------------------------------------------
356
+ def _afd_snapshot(self, play) -> dict:
357
+ hosts = self._inventory.get_hosts(play.hosts, order=play.order)
358
+ facts = self._variable_manager._nonpersistent_fact_cache
359
+ stats = self._tqm._stats
360
+ return {
361
+ h.name: {
362
+ "host": h,
363
+ "groups": {g.name for g in h.groups},
364
+ "rescued": stats.rescued.get(h.name, 0),
365
+ "dark": stats.dark.get(h.name, 0),
366
+ "failures": stats.failures.get(h.name, 0),
367
+ "unreachable": h.name in self._tqm._unreachable_hosts,
368
+ "hard": h.name in self._tqm._failed_hosts,
369
+ "facts": {k: facts.get(h.name, {}).get(k, _MISSING) for k in FAIL_FACTS},
370
+ }
371
+ for h in hosts
372
+ }
373
+
374
+ def _afd_failed(self, before: dict, filters: dict) -> list[dict]:
375
+ """The hosts that failed the play just run: rescued into the fail port (the rescue set
376
+ afd_failed_node again), failed outside the rescue, or unreachable (when asked)."""
377
+ facts = self._variable_manager._nonpersistent_fact_cache
378
+ stats = self._tqm._stats
379
+ out = []
380
+ for name, snap in before.items():
381
+ hf = facts.get(name, {})
382
+ node_fact = hf.get("afd_failed_node", _MISSING)
383
+ rescued = (
384
+ stats.rescued.get(name, 0) > snap["rescued"]
385
+ and node_fact is not _MISSING
386
+ and node_fact is not snap["facts"]["afd_failed_node"]
387
+ )
388
+ hard = name in self._tqm._failed_hosts and not snap["hard"]
389
+ # A module step ignores unreachable and routes the host to its unreachable port
390
+ # (flow_<key>_unreachable); a role step leaves it unreachable in Ansible's terms.
391
+ added = {g.name for g in snap["host"].groups} - snap["groups"]
392
+ gone = (
393
+ (name in self._tqm._unreachable_hosts and not snap["unreachable"])
394
+ or stats.dark.get(name, 0) > snap["dark"]
395
+ or any(g.endswith("_unreachable") for g in added)
396
+ )
397
+ if filters["failed"] and (rescued or hard):
398
+ item = {
399
+ "host": name,
400
+ "task": str(hf.get("afd_failed_task") or ""),
401
+ "msg": _msg(hf.get("afd_failed_result")),
402
+ }
403
+ if hard and not rescued:
404
+ item["hard"] = True
405
+ out.append(item)
406
+ elif filters["unreachable"] and gone:
407
+ out.append({"host": name, "task": "", "msg": "Unreachable", "unreachable": True})
408
+ return out
409
+
410
+ def _afd_undo(self, before: dict, names: list[str]) -> dict:
411
+ """Takes back what the failed attempt did to these hosts; returns the groups undone."""
412
+ inv = self._inventory
413
+ facts = self._variable_manager._nonpersistent_fact_cache
414
+ stats = self._tqm._stats
415
+ undone = {}
416
+ for name in names:
417
+ snap = before[name]
418
+ host = snap["host"]
419
+ added = sorted({g.name for g in host.groups} - snap["groups"])
420
+ for g in added:
421
+ inv.groups[g].remove_host(host)
422
+ hf = facts.get(name, {})
423
+ for k, v in snap["facts"].items():
424
+ if v is _MISSING:
425
+ hf.pop(k, None)
426
+ else:
427
+ hf[k] = v
428
+ for stat in ("rescued", "dark", "failures"):
429
+ table = getattr(stats, stat)
430
+ if snap[stat]:
431
+ table[name] = snap[stat]
432
+ else:
433
+ table.pop(name, None)
434
+ if not snap["hard"]:
435
+ self._tqm._failed_hosts.pop(name, None)
436
+ if not snap["unreachable"]:
437
+ self._tqm._unreachable_hosts.pop(name, None)
438
+ undone[name] = added
439
+ # Group patterns (the next plays' hosts: flow_x_ok_hosts) are cached by the inventory.
440
+ inv.clear_pattern_cache()
441
+ return undone
442
+
443
+ def _afd_rerun(self, iterator, play_context, names: list[str]):
444
+ """The same play again, on a fresh iterator restricted to these hosts (linear's run: no
445
+ step pause before it)."""
446
+ from ansible.executor.play_iterator import PlayIterator
447
+
448
+ inv = self._inventory
449
+ play = iterator._play
450
+ saved = inv._restriction
451
+ try:
452
+ inv.restrict_to_hosts([inv.get_host(n) for n in names])
453
+ for n in names:
454
+ if n in play._removed_hosts:
455
+ play._removed_hosts.remove(n)
456
+ again = PlayIterator(
457
+ inventory=inv,
458
+ play=play,
459
+ play_context=play_context,
460
+ variable_manager=self._variable_manager,
461
+ all_vars=self._variable_manager.get_vars(play=play),
462
+ start_at_done=False,
463
+ )
464
+ return LinearStrategy.run(self, again, play_context)
465
+ finally:
466
+ inv._restriction = saved
467
+ inv.clear_pattern_cache()
468
+ self._set_hosts_cache(play, refresh=True)
469
+
470
+ def _afd_run_watching(self, state: _State, node: str, iterator, play_context):
471
+ """Runs the step's play; when hosts failed it, pauses (kind failure) for Retry, Continue
472
+ or Stop. A second failure pauses again."""
473
+ play = iterator._play
474
+ filters = state.failures()
475
+ if (
476
+ not (filters["failed"] or filters["unreachable"])
477
+ or state.read().get("command") == "stop"
478
+ ):
479
+ return super().run(iterator, play_context)
480
+ before = self._afd_snapshot(play)
481
+ result = super().run(iterator, play_context)
482
+ attempt = 1
483
+ while not state.stopped:
484
+ filters = state.failures()
485
+ failed = self._afd_failed(before, filters)
486
+ if not failed or state.read().get("command") == "stop":
487
+ return result
488
+ refused = None
489
+ if ROLLING.search(play.get_name()) and play.serial:
490
+ refused = NO_RETRY_ROLLING
491
+ elif any(f.get("hard") for f in failed):
492
+ refused = NO_RETRY_HARD
493
+ hosts = [s["host"] for s in before.values()]
494
+ command = self._afd_pause(
495
+ state,
496
+ node,
497
+ play,
498
+ hosts,
499
+ "failure",
500
+ failed=failed,
501
+ attempt=attempt,
502
+ refused=refused,
503
+ )
504
+ if command == "stop":
505
+ state.stopped = True
506
+ return self._tqm.RUN_FAILED_BREAK_PLAY
507
+ if command != "retry":
508
+ return result # step or continue: the failed hosts go on by their fail port
509
+ names = [f["host"] for f in failed]
510
+ undone = self._afd_undo(before, names)
511
+ attempt += 1
512
+ state.emit(
513
+ event="retry",
514
+ node=node,
515
+ play=play.get_name(),
516
+ attempt=attempt,
517
+ hosts=names,
518
+ undone=undone,
519
+ )
520
+ fresh = self._afd_snapshot(play)
521
+ before = {n: fresh.get(n, before[n]) for n in names}
522
+ result = self._afd_rerun(iterator, play_context, names)
523
+ return self._tqm.RUN_FAILED_BREAK_PLAY