@ansible-flow/assets 1.1.0 → 1.2.0-rc.2

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.
@@ -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,60 @@ 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, hosts: int, attempt: int) -> str:
58
+ title = re.sub(r"^\[[^\]]*\]\s*", "", play) or play
59
+ of = f"{failed} of {hosts} hosts" if hosts > 1 else "1 host"
60
+ return f"Paused after {title}: {of} failed (attempt {attempt}): Retry, Continue or Stop"
61
+
62
+
63
+ def _log_line(play: str, event: dict) -> str | None:
64
+ """A log point's line in the run's output (ADR-0040 §6): masked as the event is."""
65
+ title = re.sub(r"^\[[^\]]*\]\s*", "", play) or play
66
+ host = event.get("host")
67
+ where = f"{title} · {host}" if host else title
68
+ if "message" in event:
69
+ return f"Log point {where}: {event['message']}"[:2000]
70
+ if event.get("error"):
71
+ what = {"condition": "condition", "log": "log message"}.get(event.get("source"), "point")
72
+ return f"Log point {where}: the {what} failed: {event['error']}"[:2000]
73
+ return None
74
+
75
+
49
76
  VERSION = 1
50
77
  POLL_S = 0.1
51
78
  DEFAULT_TIMEOUT_S = 3600.0
52
79
  # Pausing again: the driver's command until it changes; step and pause stop at the next step.
53
80
  PAUSING = ("step", "pause")
81
+ ANSWERS = ("step", "continue", "stop")
82
+ # The generator's failure facts (optionA FAILURE_FACTS) and Ansible's own in a rescue.
83
+ FAIL_FACTS = (
84
+ "afd_failed_result",
85
+ "afd_failed_task",
86
+ "afd_failed_node",
87
+ "ansible_failed_result",
88
+ "ansible_failed_task",
89
+ )
90
+ # A rolling subflow (AFD-55) is one play with serial for all its steps.
91
+ ROLLING = re.compile(r": rolling, .+ at a time$")
92
+ NO_RETRY_ROLLING = (
93
+ "Retry is not offered in a rolling subflow: its steps run as one play for each batch. "
94
+ "Rerun from this step as a new run instead."
95
+ )
96
+ NO_RETRY_HARD = (
97
+ "Retry is not offered for a host that failed outside the step's rescue (a failure "
98
+ "percentage, an include error). Rerun from this step as a new run instead."
99
+ )
100
+ _MISSING = object()
101
+
102
+
103
+ def _debug_lib():
104
+ """probe/afd_lib, beside this folder: loaded in debug runs only."""
105
+ probe = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
106
+ if probe not in sys.path:
107
+ sys.path.insert(0, probe)
108
+ from afd_lib import debug # noqa: PLC0415
109
+
110
+ return debug
54
111
 
55
112
 
56
113
  class _State:
@@ -72,6 +129,25 @@ class _State:
72
129
  self.last_node: str | None = os.environ.get("AFD_STEP_INSIDE") or None
73
130
  self.stopped = False
74
131
  self.good: dict = {}
132
+ # ADR-0040: a debug run; the library and its session, or why there is none.
133
+ self.debug_on = os.environ.get("AFD_DEBUG") == "1" and bool(self.control)
134
+ self.debug = None
135
+ self.no_debug: str | None = None
136
+ if self.debug_on:
137
+ try:
138
+ lib = _debug_lib()
139
+ self.no_debug = lib.unavailable()
140
+ if not self.no_debug:
141
+ self.debug = lib.Session()
142
+ # Hit counts carried by the driver from an approval's earlier segments.
143
+ hits = self.read().get("hits")
144
+ if isinstance(hits, dict):
145
+ for k, v in hits.items():
146
+ if isinstance(v, int) and not isinstance(v, bool):
147
+ self.debug.hits[str(k)] = v
148
+ except Exception as ex: # noqa: BLE001 - the run goes on step by step
149
+ self.no_debug = f"The debugger could not start: {type(ex).__name__}: {ex}"[:300]
150
+ self.lib = sys.modules.get("afd_lib.debug") if self.debug else None
75
151
 
76
152
  def read(self) -> dict:
77
153
  """The driver's last control.json. While it is being replaced (or a half-written one is
@@ -93,12 +169,59 @@ class _State:
93
169
  with open(self.events, "a", encoding="utf-8") as f:
94
170
  f.write(json.dumps(event, default=str) + "\n")
95
171
 
172
+ def failures(self) -> dict:
173
+ """Which failures pause a debug run: a host failed (on by default), unreachable."""
174
+ f = self.read().get("failures")
175
+ f = f if isinstance(f, dict) else {}
176
+ return {
177
+ "failed": f.get("failed", True) is not False,
178
+ "unreachable": f.get("unreachable") is True,
179
+ }
180
+
181
+
182
+ def _points(control: dict) -> dict[str, dict]:
183
+ """The pause points by node: a bare id, or {node, condition?, hits?, log?}."""
184
+ out: dict[str, dict] = {}
185
+ points = control.get("points")
186
+ for p in points if isinstance(points, list) else []:
187
+ if isinstance(p, str):
188
+ out[p] = {"node": p}
189
+ elif isinstance(p, dict) and isinstance(p.get("node"), str):
190
+ out[p["node"]] = p
191
+ return out
192
+
193
+
194
+ def _settings(point: dict) -> bool:
195
+ return any(point.get(k) not in (None, "", 0) for k in ("condition", "hits", "log"))
196
+
197
+
198
+ def _stepping(control: dict) -> bool:
199
+ command = control.get("command")
200
+ # After Retry the run goes on as the driver went before it (`after`: step or continue).
201
+ return command in PAUSING or (command == "retry" and control.get("after") in PAUSING)
202
+
96
203
 
97
204
  def _wants_pause(control: dict, node: str) -> bool:
98
- if control.get("command") in PAUSING:
205
+ """Outside a debug run: point settings are not read; a log-only point never pauses."""
206
+ if _stepping(control):
99
207
  return True
100
- points = control.get("points")
101
- return isinstance(points, list) and node in points
208
+ point = _points(control).get(node)
209
+ if point is None:
210
+ return False
211
+ return not (point.get("log") and not point.get("condition") and not point.get("hits"))
212
+
213
+
214
+ def _msg(result: object) -> str:
215
+ if not isinstance(result, dict):
216
+ return ""
217
+ parts = [str(result.get("msg") or result.get("reason") or "")]
218
+ rc = result.get("rc")
219
+ if rc not in (None, 0):
220
+ parts.append(f"rc={rc}")
221
+ err = result.get("stderr")
222
+ if err:
223
+ parts.append(str(err)[:200])
224
+ return "; ".join(p for p in parts if p)[:500]
102
225
 
103
226
 
104
227
  class StrategyModule(LinearStrategy):
@@ -116,55 +239,124 @@ class StrategyModule(LinearStrategy):
116
239
  node = str(node) if node else None
117
240
  if state.stopped:
118
241
  return self._tqm.RUN_FAILED_BREAK_PLAY
242
+ if state.debug is not None:
243
+ state.debug.note_play(play)
119
244
  # The first play of a step only: a step's arriving and route plays go on with it.
120
245
  if node and node != state.last_node and state.control:
121
246
  self._set_hosts_cache(play)
122
- hosts = [h.get_name() for h in self.get_hosts_left(iterator)]
247
+ hosts = list(self.get_hosts_left(iterator))
123
248
  # A play no host reaches is not where a step starts for anyone.
124
249
  if hosts:
125
250
  state.last_node = node
126
- if self._afd_gate(state, node, play.get_name(), hosts) == "stop":
251
+ if self._afd_gate(state, node, play, hosts) == "stop":
127
252
  state.stopped = True
128
253
  return self._tqm.RUN_FAILED_BREAK_PLAY
254
+ if node and state.debug is not None:
255
+ return self._afd_run_watching(state, node, iterator, play_context)
129
256
  return super().run(iterator, play_context)
130
257
 
131
- def _afd_gate(self, state: _State, node: str, name: str, hosts: list[str]) -> str:
258
+ # ---- the step gate ---------------------------------------------------------------------
259
+ def _afd_gate(self, state: _State, node: str, play, hosts: list) -> str:
132
260
  """Pauses before `node` when the driver wants it; returns step, continue or stop."""
261
+ name = play.get_name()
262
+ names = [h.get_name() for h in hosts]
133
263
  control = state.read()
134
264
  if control.get("command") == "stop":
135
- state.emit(event="stopped", node=node, play=name, hosts=hosts, reason="driver")
265
+ state.emit(event="stopped", node=node, play=name, hosts=names, reason="driver")
136
266
  return "stop"
137
- if not _wants_pause(control, node):
267
+ if state.debug is None:
268
+ if not _wants_pause(control, node):
269
+ return "continue"
270
+ return self._afd_pause(
271
+ state, node, play, hosts, "step" if _stepping(control) else "point"
272
+ )
273
+ kind = "step" if _stepping(control) else None
274
+ extra: dict = {}
275
+ point = _points(control).get(node)
276
+ if point is not None and _settings(point):
277
+ found = state.lib.at_point(state.debug, self, play, hosts, node, point)
278
+ for e in found["events"]:
279
+ state.emit(**e)
280
+ if e.get("event") == "log":
281
+ line = _log_line(name, e)
282
+ if line:
283
+ display.display(line)
284
+ if found["pause"]:
285
+ kind = "condition" if point.get("condition") or point.get("hits") else "point"
286
+ if found["matched"]:
287
+ extra["matched"] = found["matched"]
288
+ if point.get("hits"):
289
+ extra["reached"] = point.get("hits")
290
+ elif point is not None:
291
+ kind = "point"
292
+ if kind is None:
138
293
  return "continue"
294
+ return self._afd_pause(state, node, play, hosts, kind, **extra)
295
+
296
+ def _afd_pause(self, state: _State, node: str, play, hosts: list, kind: str, **extra) -> str:
297
+ """Waits at a pause for the driver's answer, serving debugger requests meanwhile."""
298
+ name = play.get_name()
299
+ names = [h.get_name() for h in hosts]
139
300
  state.count += 1
140
301
  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)))
302
+ refused = extra.pop("refused", None)
303
+ event: dict = {
304
+ "event": "pause",
305
+ "id": pause,
306
+ "node": node,
307
+ "play": name,
308
+ "hosts": names,
309
+ "timeout": state.timeout,
310
+ }
311
+ if state.debug_on:
312
+ event["kind"] = kind
313
+ event.update(extra)
314
+ if refused:
315
+ event["retry"] = {"refused": refused}
316
+ if state.debug is not None:
317
+ event["debug"] = True
318
+ elif state.no_debug:
319
+ event["debug"] = False
320
+ event["why"] = state.no_debug
321
+ state.emit(**event)
322
+ if kind == "failure":
323
+ failed = extra.get("failed") or []
324
+ display.display(_failed_line(name, len(failed), len(names), extra.get("attempt", 1)))
325
+ for f in failed:
326
+ display.display(f" {f['host']}: {f.get('task') or ''}: {f.get('msg') or ''}"[:300])
327
+ else:
328
+ # AFS-205: in plain words, once: "Paused before Read facts: 2 hosts wait for Step, ...".
329
+ display.display(_paused_line(name, len(names)))
151
330
  # Out now, before anyone answers: a pipe (a server's run) holds it back otherwise, and the
152
331
  # line came after who said Step.
153
332
  sys.stdout.flush()
333
+ gate = state.debug.gate(self, play, hosts, pause) if state.debug is not None else None
334
+ folder = os.path.dirname(state.control) or "."
335
+ answers = (*ANSWERS, "retry") if kind == "failure" else ANSWERS
336
+ told = False
154
337
  deadline = time.monotonic() + state.timeout
155
338
  while True:
156
339
  control = state.read()
157
340
  command = control.get("command")
158
- if control.get("reply") == pause and command in ("step", "continue", "stop"):
159
- break
341
+ if control.get("reply") == pause and command in answers:
342
+ if command == "retry" and refused:
343
+ if not told:
344
+ state.emit(
345
+ event="refused", id=pause, node=node, command="retry", why=refused
346
+ )
347
+ told = True
348
+ else:
349
+ break
160
350
  # A stop needs no reply: it may come from a driver that missed this pause.
161
351
  if command == "stop":
162
352
  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).
353
+ # ADR-0040: while paused, requests about this pause are answered here, with the play,
354
+ # its hosts and the variable manager at hand.
355
+ if gate is not None:
356
+ gate.serve(folder)
165
357
  if time.monotonic() > deadline:
166
358
  state.emit(
167
- event="stopped", id=pause, node=node, play=name, hosts=hosts, reason="timeout"
359
+ event="stopped", id=pause, node=node, play=name, hosts=names, reason="timeout"
168
360
  )
169
361
  display.warning(
170
362
  f"Nobody answered the pause for {int(state.timeout)} s: the run stops here"
@@ -172,9 +364,188 @@ class StrategyModule(LinearStrategy):
172
364
  return "stop"
173
365
  time.sleep(POLL_S)
174
366
  if command == "stop":
175
- state.emit(
176
- event="stopped", id=pause, node=node, play=name, hosts=hosts, reason="driver"
177
- )
367
+ stopped: dict = {"hosts": names}
368
+ if kind == "failure":
369
+ # Stopped after the step: its failed hosts stay failed there, the others ran it
370
+ # and stop after it (not before it).
371
+ gone = {f["host"] for f in extra.get("failed") or []}
372
+ stopped = {
373
+ "hosts": [n for n in names if n not in gone],
374
+ "failed": [n for n in names if n in gone],
375
+ "after": True,
376
+ }
377
+ state.emit(event="stopped", id=pause, node=node, play=name, reason="driver", **stopped)
178
378
  return "stop"
179
379
  state.emit(event="resume", id=pause, node=node, command=command)
180
380
  return command
381
+
382
+ # ---- pause on failure, Retry (ADR-0040 §7) ---------------------------------------------
383
+ def _afd_snapshot(self, play) -> dict:
384
+ hosts = self._inventory.get_hosts(play.hosts, order=play.order)
385
+ facts = self._variable_manager._nonpersistent_fact_cache
386
+ stats = self._tqm._stats
387
+ return {
388
+ h.name: {
389
+ "host": h,
390
+ "groups": {g.name for g in h.groups},
391
+ "rescued": stats.rescued.get(h.name, 0),
392
+ "dark": stats.dark.get(h.name, 0),
393
+ "failures": stats.failures.get(h.name, 0),
394
+ "unreachable": h.name in self._tqm._unreachable_hosts,
395
+ "hard": h.name in self._tqm._failed_hosts,
396
+ "facts": {k: facts.get(h.name, {}).get(k, _MISSING) for k in FAIL_FACTS},
397
+ }
398
+ for h in hosts
399
+ }
400
+
401
+ def _afd_failed(self, before: dict, filters: dict) -> list[dict]:
402
+ """The hosts that failed the play just run: rescued into the fail port (the rescue set
403
+ afd_failed_node again), failed outside the rescue, or unreachable (when asked)."""
404
+ facts = self._variable_manager._nonpersistent_fact_cache
405
+ stats = self._tqm._stats
406
+ out = []
407
+ for name, snap in before.items():
408
+ hf = facts.get(name, {})
409
+ node_fact = hf.get("afd_failed_node", _MISSING)
410
+ rescued = (
411
+ stats.rescued.get(name, 0) > snap["rescued"]
412
+ and node_fact is not _MISSING
413
+ and node_fact is not snap["facts"]["afd_failed_node"]
414
+ )
415
+ hard = name in self._tqm._failed_hosts and not snap["hard"]
416
+ # A module step ignores unreachable and routes the host to its unreachable port
417
+ # (flow_<key>_unreachable); a role step leaves it unreachable in Ansible's terms.
418
+ added = {g.name for g in snap["host"].groups} - snap["groups"]
419
+ gone = (
420
+ (name in self._tqm._unreachable_hosts and not snap["unreachable"])
421
+ or stats.dark.get(name, 0) > snap["dark"]
422
+ or any(g.endswith("_unreachable") for g in added)
423
+ )
424
+ if filters["failed"] and (rescued or hard):
425
+ item = {
426
+ "host": name,
427
+ "task": str(hf.get("afd_failed_task") or ""),
428
+ "msg": _msg(hf.get("afd_failed_result")),
429
+ }
430
+ if hard and not rescued:
431
+ item["hard"] = True
432
+ out.append(item)
433
+ elif filters["unreachable"] and gone:
434
+ out.append({"host": name, "task": "", "msg": "Unreachable", "unreachable": True})
435
+ return out
436
+
437
+ def _afd_undo(self, before: dict, names: list[str]) -> dict:
438
+ """Takes back what the failed attempt did to these hosts; returns the groups undone."""
439
+ inv = self._inventory
440
+ facts = self._variable_manager._nonpersistent_fact_cache
441
+ stats = self._tqm._stats
442
+ undone = {}
443
+ for name in names:
444
+ snap = before[name]
445
+ host = snap["host"]
446
+ added = sorted({g.name for g in host.groups} - snap["groups"])
447
+ for g in added:
448
+ inv.groups[g].remove_host(host)
449
+ hf = facts.get(name, {})
450
+ for k, v in snap["facts"].items():
451
+ if v is _MISSING:
452
+ hf.pop(k, None)
453
+ else:
454
+ hf[k] = v
455
+ for stat in ("rescued", "dark", "failures"):
456
+ table = getattr(stats, stat)
457
+ if snap[stat]:
458
+ table[name] = snap[stat]
459
+ else:
460
+ table.pop(name, None)
461
+ if not snap["hard"]:
462
+ self._tqm._failed_hosts.pop(name, None)
463
+ if not snap["unreachable"]:
464
+ self._tqm._unreachable_hosts.pop(name, None)
465
+ undone[name] = added
466
+ # Group patterns (the next plays' hosts: flow_x_ok_hosts) are cached by the inventory.
467
+ inv.clear_pattern_cache()
468
+ return undone
469
+
470
+ def _afd_rerun(self, iterator, play_context, names: list[str]):
471
+ """The same play again, on a fresh iterator restricted to these hosts (linear's run: no
472
+ step pause before it)."""
473
+ from ansible.executor.play_iterator import PlayIterator
474
+
475
+ inv = self._inventory
476
+ play = iterator._play
477
+ saved = inv._restriction
478
+ try:
479
+ inv.restrict_to_hosts([inv.get_host(n) for n in names])
480
+ for n in names:
481
+ if n in play._removed_hosts:
482
+ play._removed_hosts.remove(n)
483
+ again = PlayIterator(
484
+ inventory=inv,
485
+ play=play,
486
+ play_context=play_context,
487
+ variable_manager=self._variable_manager,
488
+ all_vars=self._variable_manager.get_vars(play=play),
489
+ start_at_done=False,
490
+ )
491
+ return LinearStrategy.run(self, again, play_context)
492
+ finally:
493
+ inv._restriction = saved
494
+ inv.clear_pattern_cache()
495
+ self._set_hosts_cache(play, refresh=True)
496
+
497
+ def _afd_run_watching(self, state: _State, node: str, iterator, play_context):
498
+ """Runs the step's play; when hosts failed it, pauses (kind failure) for Retry, Continue
499
+ or Stop. A second failure pauses again."""
500
+ play = iterator._play
501
+ filters = state.failures()
502
+ if (
503
+ not (filters["failed"] or filters["unreachable"])
504
+ or state.read().get("command") == "stop"
505
+ ):
506
+ return super().run(iterator, play_context)
507
+ before = self._afd_snapshot(play)
508
+ # Every pause holds all hosts: after a Retry, those that passed still wait at it.
509
+ everyone = [s["host"] for s in before.values()]
510
+ result = super().run(iterator, play_context)
511
+ attempt = 1
512
+ while not state.stopped:
513
+ filters = state.failures()
514
+ failed = self._afd_failed(before, filters)
515
+ if not failed or state.read().get("command") == "stop":
516
+ return result
517
+ refused = None
518
+ if ROLLING.search(play.get_name()) and play.serial:
519
+ refused = NO_RETRY_ROLLING
520
+ elif any(f.get("hard") for f in failed):
521
+ refused = NO_RETRY_HARD
522
+ command = self._afd_pause(
523
+ state,
524
+ node,
525
+ play,
526
+ everyone,
527
+ "failure",
528
+ failed=failed,
529
+ attempt=attempt,
530
+ refused=refused,
531
+ )
532
+ if command == "stop":
533
+ state.stopped = True
534
+ return self._tqm.RUN_FAILED_BREAK_PLAY
535
+ if command != "retry":
536
+ return result # step or continue: the failed hosts go on by their fail port
537
+ names = [f["host"] for f in failed]
538
+ undone = self._afd_undo(before, names)
539
+ attempt += 1
540
+ state.emit(
541
+ event="retry",
542
+ node=node,
543
+ play=play.get_name(),
544
+ attempt=attempt,
545
+ hosts=names,
546
+ undone=undone,
547
+ )
548
+ fresh = self._afd_snapshot(play)
549
+ before = {n: fresh.get(n, before[n]) for n in names}
550
+ result = self._afd_rerun(iterator, play_context, names)
551
+ return self._tqm.RUN_FAILED_BREAK_PLAY