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

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.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Ansible Flow Designer files a host passes by path: the Python probe, the run events callback, the JSON schemas, the contract with Ansible Flow Server and the sample projects.
4
4
 
5
- Built from [Ansible Flow Designer](https://github.com/ChistokhinSV/ansible-flow-designer) 1.2.0-rc.2
5
+ Built from [Ansible Flow Designer](https://github.com/ChistokhinSV/ansible-flow-designer) 1.2.0-rc.3
6
6
  and released with it. The folders are found by path: `import { probeDir, schemaDir, contractDir, samplesDir } from '@ansible-flow/assets'`.
7
7
 
8
8
  What is in the package, which entry points are documented and what may change:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ansible-flow/assets",
3
- "version": "1.2.0-rc.2",
3
+ "version": "1.2.0-rc.3",
4
4
  "description": "Ansible Flow Designer files a host passes by path: the Python probe, the run events callback, the JSON schemas, the contract with Ansible Flow Server and the sample projects.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/ChistokhinSV/ansible-flow-designer/blob/main/docs/packages.md",
@@ -244,8 +244,11 @@ class HostView:
244
244
  def scope_of(self, name: str) -> str | None:
245
245
  if name in MAGIC or name in OWN_PLAY_VARS or name.startswith("ansible_facts"):
246
246
  return None
247
- if name not in self._extra and name.startswith("afd_") and name in self._all_play:
248
- return None # the generator's own play variables
247
+ if name not in self._extra and name.startswith("afd_"):
248
+ # The generator's own: its play variables and the facts its code sets on a host
249
+ # (afd_failed_node, afd_failed_result, afd_failed_task, afd_inputs). Evaluate still
250
+ # reads them.
251
+ return None
249
252
  if name in self._extra:
250
253
  return "flow"
251
254
  if name in self._play_vars:
@@ -142,11 +142,16 @@ class Gate:
142
142
  return self._views[name]
143
143
 
144
144
  def environment(self):
145
+ # Only parsed and lexed with (names read, syntax checks), never rendered with: a Jinja
146
+ # environment of our own parses as Ansible's does. Templar.environment is deprecated in
147
+ # ansible-core 2.19 (removed in 2.23), and reading it printed a warning in debug runs.
145
148
  if self._templar is None:
146
- from ansible.template import Templar
149
+ from jinja2.sandbox import ImmutableSandboxedEnvironment
147
150
 
148
- self._templar = Templar(loader=self.strategy._loader) # noqa: SLF001
149
- return self._templar.environment
151
+ self._templar = ImmutableSandboxedEnvironment(
152
+ extensions=["jinja2.ext.loopcontrols", "jinja2.ext.do"]
153
+ )
154
+ return self._templar
150
155
 
151
156
  # ---- requests --------------------------------------------------------------------------
152
157
  def serve(self, folder: str) -> int:
@@ -261,7 +266,7 @@ class Gate:
261
266
  def evaluate(self, host: str, expr: str, timeout: object = None) -> dict:
262
267
  refused = render.precheck(expr, self.environment())
263
268
  if refused:
264
- return {"host": host, "expr": expr, "error": refused, "refused": True}
269
+ return {"host": host, "expr": expr, **render.refusal(refused)}
265
270
  # The plain texts of this host's vaulted values are learned here, before the child.
266
271
  masked = self._masked_row(host, expr)
267
272
  if masked:
@@ -293,7 +298,7 @@ class Gate:
293
298
  templar = self._templar_for(target)
294
299
  for e in exprs:
295
300
  if refused[e]:
296
- rows.append({"host": h, "expr": e, "error": refused[e], "refused": True})
301
+ rows.append({"host": h, "expr": e, **render.refusal(refused[e])})
297
302
  continue
298
303
  if masked.get((h, e)):
299
304
  rows.append(masked[(h, e)])
@@ -57,6 +57,13 @@ def precheck(expr: str, environment, where: str = "Evaluate") -> str | None:
57
57
  return check_template("{{ " + expr + " }}", environment, where, expression=True)
58
58
 
59
59
 
60
+ def refusal(text: str) -> dict:
61
+ """A precheck's answer: refused (a lookup, a vault filter, a name starting with _: what
62
+ Evaluate does not allow), or an error (a bracket or quote not closed, not Jinja: the
63
+ expression is not finished, nothing was refused)."""
64
+ return {"error": text, "refused": True} if "not allowed" in text else {"error": text}
65
+
66
+
60
67
  PAIRS = {"(": ")", "[": "]", "{": "}"}
61
68
 
62
69
 
@@ -34,6 +34,24 @@ class TooMany(Exception):
34
34
  """A hostvars lookup by a host chosen at run time, in an inventory too large to check."""
35
35
 
36
36
 
37
+ def _constant(node) -> object:
38
+ """A key written as constants joined (`'db' ~ '_password'`, `'a' + 'b'`): its value; DYN for a
39
+ key chosen at run time. So `vars['db' ~ '_password']` reads that variable, with its reason."""
40
+ from jinja2 import nodes
41
+
42
+ if isinstance(node, nodes.Const):
43
+ v = node.value
44
+ return v if isinstance(v, (str, int)) and not isinstance(v, bool) else DYN
45
+ if isinstance(node, nodes.Concat):
46
+ parts = [_constant(n) for n in node.nodes]
47
+ return DYN if any(p is DYN for p in parts) else "".join(str(p) for p in parts)
48
+ if isinstance(node, nodes.Add):
49
+ left, right = _constant(node.left), _constant(node.right)
50
+ if isinstance(left, str) and isinstance(right, str):
51
+ return left + right
52
+ return DYN
53
+
54
+
37
55
  def _chain(node) -> tuple[str, list] | None:
38
56
  """(root name, keys) of a chain of names, attributes and items; None for anything else."""
39
57
  from jinja2 import nodes
@@ -44,15 +62,7 @@ def _chain(node) -> tuple[str, list] | None:
44
62
  keys.append(node.attr)
45
63
  node = node.node
46
64
  elif isinstance(node, nodes.Getitem):
47
- arg = node.arg
48
- if (
49
- isinstance(arg, nodes.Const)
50
- and isinstance(arg.value, (str, int))
51
- and not isinstance(arg.value, bool)
52
- ):
53
- keys.append(arg.value)
54
- else:
55
- keys.append(DYN)
65
+ keys.append(_constant(node.arg))
56
66
  node = node.node
57
67
  elif isinstance(node, nodes.Name):
58
68
  keys.reverse()
@@ -46,6 +46,31 @@ DOCUMENTATION = """
46
46
 
47
47
  display = Display()
48
48
 
49
+ # ansible-core 2.19+ calls every strategy outside ansible.builtin deprecated, with no replacement
50
+ # planned, on each play of a step-by-step or debug run. This plugin is the linear strategy with
51
+ # pauses, and the warning tells the person running a flow nothing they can act on, so that one
52
+ # message is dropped (Display is one object per process; the loader warns right after it imports
53
+ # this module). Every other deprecation warning still shows.
54
+ _THIRD_PARTY_STRATEGY = "Use of strategy plugins not included in ansible.builtin are deprecated"
55
+
56
+
57
+ def _quiet_strategy_deprecation() -> None:
58
+ if getattr(display, "_afd_quiet", False):
59
+ return
60
+ warn = display.deprecated
61
+
62
+ def deprecated(*args, **kwargs):
63
+ msg = kwargs.get("msg", args[0] if args else "")
64
+ if isinstance(msg, str) and msg.startswith(_THIRD_PARTY_STRATEGY):
65
+ return None
66
+ return warn(*args, **kwargs)
67
+
68
+ display.deprecated = deprecated
69
+ display._afd_quiet = True
70
+
71
+
72
+ _quiet_strategy_deprecation()
73
+
49
74
 
50
75
  def _paused_line(play: str, hosts: int) -> str:
51
76
  """The terminal's line for a pause: the step's title without its [key], the hosts waiting."""
@@ -89,13 +114,15 @@ FAIL_FACTS = (
89
114
  )
90
115
  # A rolling subflow (AFD-55) is one play with serial for all its steps.
91
116
  ROLLING = re.compile(r": rolling, .+ at a time$")
117
+ # Why Retry is not offered, as a reason: shown alone and after "Retry is not offered here: ".
92
118
  NO_RETRY_ROLLING = (
93
- "Retry is not offered in a rolling subflow: its steps run as one play for each batch. "
119
+ "A rolling subflow runs its steps as one play for each batch. "
94
120
  "Rerun from this step as a new run instead."
95
121
  )
96
122
  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."
123
+ "Ansible took the failed host out of the run (it failed outside the step's rescue, as with a "
124
+ "missing role, an include error or a failure percentage). Rerun from this step as a new run "
125
+ "instead."
99
126
  )
100
127
  _MISSING = object()
101
128
 
@@ -214,7 +241,8 @@ def _wants_pause(control: dict, node: str) -> bool:
214
241
  def _msg(result: object) -> str:
215
242
  if not isinstance(result, dict):
216
243
  return ""
217
- parts = [str(result.get("msg") or result.get("reason") or "")]
244
+ # "The command exited with a non-zero return code; rc=1", not "code.; rc=1".
245
+ parts = [str(result.get("msg") or result.get("reason") or "").strip().rstrip(".")]
218
246
  rc = result.get("rc")
219
247
  if rc not in (None, 0):
220
248
  parts.append(f"rc={rc}")
@@ -224,6 +252,37 @@ def _msg(result: object) -> str:
224
252
  return "; ".join(p for p in parts if p)[:500]
225
253
 
226
254
 
255
+ def _last_failures(path: str, offset: int) -> dict[str, dict]:
256
+ """The last failed result of each host in events.jsonl after `offset` (the afd_events
257
+ callback's lines, masked there): the task and message of a failure no rescue saw."""
258
+ out: dict[str, dict] = {}
259
+ if not path:
260
+ return out
261
+ try:
262
+ with open(path, encoding="utf-8") as f:
263
+ f.seek(offset)
264
+ lines = f.read().splitlines()
265
+ except OSError:
266
+ return out
267
+ for line in lines:
268
+ if '"result"' not in line or '"failed"' not in line:
269
+ continue
270
+ try:
271
+ e = json.loads(line)
272
+ except ValueError:
273
+ continue
274
+ if e.get("event") == "result" and e.get("status") == "failed" and not e.get("ignored"):
275
+ out[str(e.get("host"))] = e
276
+ return out
277
+
278
+
279
+ def _events_size(path: str) -> int:
280
+ try:
281
+ return os.path.getsize(path) if path else 0
282
+ except OSError:
283
+ return 0
284
+
285
+
227
286
  class StrategyModule(LinearStrategy):
228
287
  def _afd_state(self) -> _State:
229
288
  state = getattr(self._tqm, "_afd_step", None)
@@ -398,12 +457,15 @@ class StrategyModule(LinearStrategy):
398
457
  for h in hosts
399
458
  }
400
459
 
401
- def _afd_failed(self, before: dict, filters: dict) -> list[dict]:
460
+ def _afd_failed(self, before: dict, filters: dict, events: str = "", offset: int = 0):
402
461
  """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)."""
462
+ afd_failed_node again), failed outside the rescue, or unreachable (when asked). A failure
463
+ outside the rescue has no afd_failed_* facts: its task and message are the run's last
464
+ failed result for the host (events.jsonl since the play started)."""
404
465
  facts = self._variable_manager._nonpersistent_fact_cache
405
466
  stats = self._tqm._stats
406
467
  out = []
468
+ seen: dict[str, dict] | None = None
407
469
  for name, snap in before.items():
408
470
  hf = facts.get(name, {})
409
471
  node_fact = hf.get("afd_failed_node", _MISSING)
@@ -429,6 +491,12 @@ class StrategyModule(LinearStrategy):
429
491
  }
430
492
  if hard and not rescued:
431
493
  item["hard"] = True
494
+ if not item["task"] or not item["msg"]:
495
+ if seen is None:
496
+ seen = _last_failures(events, offset)
497
+ last = seen.get(name) or {}
498
+ item["task"] = item["task"] or str(last.get("task") or "")
499
+ item["msg"] = item["msg"] or str(last.get("msg") or "")[:500]
432
500
  out.append(item)
433
501
  elif filters["unreachable"] and gone:
434
502
  out.append({"host": name, "task": "", "msg": "Unreachable", "unreachable": True})
@@ -507,11 +575,12 @@ class StrategyModule(LinearStrategy):
507
575
  before = self._afd_snapshot(play)
508
576
  # Every pause holds all hosts: after a Retry, those that passed still wait at it.
509
577
  everyone = [s["host"] for s in before.values()]
578
+ offset = _events_size(state.events)
510
579
  result = super().run(iterator, play_context)
511
580
  attempt = 1
512
581
  while not state.stopped:
513
582
  filters = state.failures()
514
- failed = self._afd_failed(before, filters)
583
+ failed = self._afd_failed(before, filters, state.events, offset)
515
584
  if not failed or state.read().get("command") == "stop":
516
585
  return result
517
586
  refused = None
@@ -547,5 +616,6 @@ class StrategyModule(LinearStrategy):
547
616
  )
548
617
  fresh = self._afd_snapshot(play)
549
618
  before = {n: fresh.get(n, before[n]) for n in names}
619
+ offset = _events_size(state.events)
550
620
  result = self._afd_rerun(iterator, play_context, names)
551
621
  return self._tqm.RUN_FAILED_BREAK_PLAY