@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.
@@ -0,0 +1,459 @@
1
+ # The debugger at a pause (ADR-0040 §2, §3, §5, §6; AFD-370, AFD-371): requests served from the
2
+ # afd_step gate loop, and pause point conditions, hit counts and log points at a step gate.
3
+ #
4
+ # Channel: the driver writes request-<n>.json beside control.json (whole: a temporary file, then a
5
+ # rename): {v:1, pause, n, op, host?, hosts?, scope?, path?, start?, count?, expr?, exprs?,
6
+ # timeout?}. The gate loop answers with answer-<n>.json (whole too) on its 100 ms tick and removes
7
+ # the request. A request for a pause that is not the current one is answered {gone: true}.
8
+ # Ops: scopes, vars, facts, eval, watch.
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ import time
14
+ from collections.abc import Mapping
15
+
16
+ from . import capture, render
17
+ from .capture import HostView, entry, plain, to_json
18
+ from .mask import REDACTED, TAGS, Masker
19
+ from .taint import MAX_HOSTS, Taint, TooMany, mask_blocks
20
+
21
+ VERSION = 1
22
+ # A gate's conditions and log messages, for every host: one child, at most this long.
23
+ GATE_LIMIT = 2.0
24
+
25
+
26
+ def unavailable() -> str | None:
27
+ """Why this core cannot be debugged, in words; None when it can."""
28
+ if not TAGS:
29
+ return "Debugging needs ansible-core 2.19 or later; this run goes on step by step only"
30
+ try:
31
+ import ansible._internal._templating._jinja_plugins as jp
32
+
33
+ if not hasattr(jp, "lookup_loader"):
34
+ raise ImportError
35
+ except ImportError:
36
+ return (
37
+ "This ansible-core cannot block lookups while debugging; the run goes on step by step"
38
+ )
39
+ return None
40
+
41
+
42
+ def write_whole(path: str, data: object) -> None:
43
+ tmp = f"{path}.{os.getpid()}.tmp"
44
+ with open(tmp, "w", encoding="utf-8") as f:
45
+ f.write(json.dumps(data, ensure_ascii=False, separators=(",", ":"), default=str))
46
+ os.replace(tmp, path)
47
+
48
+
49
+ class Session:
50
+ """One per ansible-playbook process: the masker (its known values grow) and hit counts."""
51
+
52
+ def __init__(self) -> None:
53
+ self.masker = Masker()
54
+ self.hits: dict[str, int] = {}
55
+ # Registers of no_log tasks, from every play so far (ADR-0040 §4, check 4).
56
+ self.nolog: set[str] = set()
57
+
58
+ def note_play(self, play) -> None:
59
+ self.nolog |= capture.nolog_registers(play)
60
+
61
+ def gate(self, strategy, play, hosts: list, pause: str) -> Gate:
62
+ return Gate(self, strategy, play, hosts, pause)
63
+
64
+
65
+ class Gate:
66
+ """One pause: the play, its hosts and the variable manager, with each host's view cached."""
67
+
68
+ def __init__(self, session: Session, strategy, play, hosts: list, pause: str) -> None:
69
+ self.session = session
70
+ self.strategy = strategy
71
+ self.play = play
72
+ self.hosts = {h.get_name(): h for h in hosts}
73
+ self.pause = pause
74
+ self._views: dict[str, HostView] = {}
75
+ self._secret: set[str] | None = None
76
+ self._templar = None
77
+ self._raw: dict[str, Mapping | None] = {}
78
+ self._taints: dict[str, Taint] = {}
79
+
80
+ # ---- what a host has -------------------------------------------------------------------
81
+ def variables(self, host) -> Mapping:
82
+ s = self.strategy
83
+ return s._variable_manager.get_vars( # noqa: SLF001
84
+ play=self.play,
85
+ host=host,
86
+ _hosts=getattr(s, "_hosts_cache", None),
87
+ _hosts_all=getattr(s, "_hosts_cache_all", None),
88
+ )
89
+
90
+ def raw(self, name: str) -> Mapping | None:
91
+ """Any inventory host's variables (raw, nothing rendered), once per pause."""
92
+ if name not in self._raw:
93
+ host = self.hosts.get(name)
94
+ if host is None:
95
+ host = self.strategy._inventory.get_host(name) # noqa: SLF001
96
+ self._raw[name] = self.variables(host) if host is not None else None
97
+ return self._raw[name]
98
+
99
+ def inventory_hosts(self) -> list[str]:
100
+ return [h.get_name() for h in self.strategy._inventory.get_hosts("all")] # noqa: SLF001
101
+
102
+ def secret(self) -> set[str]:
103
+ if self._secret is None:
104
+ self._secret = capture.secret_inputs(self.play)
105
+ return self._secret
106
+
107
+ def taint(self, name: str) -> Taint:
108
+ """What `name`'s expressions read, checked against the masking (AFD-373)."""
109
+ if name not in self._taints:
110
+ self.view(name) # learns the plain texts of the host's vaulted values first
111
+ self._taints[name] = Taint(
112
+ self.session.masker,
113
+ self.environment(),
114
+ self.raw,
115
+ self.inventory_hosts,
116
+ name,
117
+ nolog=self.session.nolog,
118
+ secret=self.secret(),
119
+ )
120
+ return self._taints[name]
121
+
122
+ def masked_by(self, name: str, text: str, template: bool = False) -> str | None:
123
+ """Why what `text` renders for host `name` is masked whole; None when nothing it reads is
124
+ masked. Raises TooMany for hostvars by a host chosen at run time in a large inventory."""
125
+ t = self.taint(name)
126
+ return t.template(text) if template else t.expression(text)
127
+
128
+ def view(self, name: str) -> HostView:
129
+ if name not in self._views:
130
+ if self._secret is None:
131
+ self._secret = capture.secret_inputs(self.play)
132
+ vm = self.strategy._variable_manager # noqa: SLF001
133
+ self._views[name] = HostView(
134
+ self.variables(self.hosts[name]),
135
+ play_vars=set(self.play.vars or {}),
136
+ extra=set(vm.extra_vars or {}),
137
+ secret=self._secret,
138
+ masker=self.session.masker,
139
+ nolog=self.session.nolog,
140
+ inputs=capture.step_inputs(self.play),
141
+ )
142
+ return self._views[name]
143
+
144
+ def environment(self):
145
+ if self._templar is None:
146
+ from ansible.template import Templar
147
+
148
+ self._templar = Templar(loader=self.strategy._loader) # noqa: SLF001
149
+ return self._templar.environment
150
+
151
+ # ---- requests --------------------------------------------------------------------------
152
+ def serve(self, folder: str) -> int:
153
+ """Answers the request files waiting in `folder`; returns how many."""
154
+ try:
155
+ names = sorted(
156
+ n for n in os.listdir(folder) if n.startswith("request-") and n.endswith(".json")
157
+ )
158
+ except OSError:
159
+ return 0
160
+ done = 0
161
+ for fname in names:
162
+ path = os.path.join(folder, fname)
163
+ try:
164
+ with open(path, encoding="utf-8") as f:
165
+ req = json.load(f)
166
+ except (OSError, ValueError):
167
+ continue # half written (an SSH copy): the next tick reads it whole
168
+ n = fname[len("request-") : -len(".json")]
169
+ t0 = time.perf_counter()
170
+ if not isinstance(req, dict):
171
+ answer: dict = {"error": "Not a request"}
172
+ elif str(req.get("pause")) != self.pause:
173
+ answer = {"gone": True}
174
+ else:
175
+ try:
176
+ answer = self.answer(req)
177
+ except Exception as ex: # noqa: BLE001 - an answer, never a broken run
178
+ answer = {"error": render.error_text(ex)}
179
+ answer.update(
180
+ v=VERSION, pause=self.pause, n=req.get("n", n) if isinstance(req, dict) else n
181
+ )
182
+ answer["ms"] = round((time.perf_counter() - t0) * 1000, 1)
183
+ try:
184
+ write_whole(os.path.join(folder, f"answer-{n}.json"), answer)
185
+ os.remove(path)
186
+ except OSError:
187
+ pass
188
+ done += 1
189
+ return done
190
+
191
+ def _host(self, req: dict) -> str | dict:
192
+ name = str(req.get("host") or "")
193
+ if name not in self.hosts:
194
+ return {"error": f"{name or 'No host'} does not wait at this pause"}
195
+ return name
196
+
197
+ def answer(self, req: dict) -> dict:
198
+ op = req.get("op")
199
+ if op == "watch":
200
+ return self.watch(req)
201
+ host = self._host(req)
202
+ if isinstance(host, dict):
203
+ return host
204
+ if op == "scopes":
205
+ return {"host": host, "scopes": self.view(host).scopes(facts=bool(req.get("facts")))}
206
+ if op in ("vars", "facts"):
207
+ scope = "facts" if op == "facts" else str(req.get("scope") or "host")
208
+ if scope not in capture.SCOPES:
209
+ return {"error": f"No scope {scope}"}
210
+ path = req.get("path") or []
211
+ if not isinstance(path, list):
212
+ return {"error": "path is a list of names and indexes"}
213
+ out = self.view(host).page(
214
+ scope, path, int(req.get("start") or 0), int(req.get("count") or capture.PAGE)
215
+ )
216
+ out.update(host=host, scope=scope)
217
+ return out
218
+ if op == "eval":
219
+ return self.evaluate(host, str(req.get("expr") or ""), req.get("timeout"))
220
+ return {"error": f"Unknown op {op!r}"}
221
+
222
+ # ---- evaluate and watch ----------------------------------------------------------------
223
+ def _templar_for(self, host):
224
+ from ansible.template import Templar
225
+
226
+ return Templar(loader=self.strategy._loader, variables=self.variables(host)) # noqa: SLF001
227
+
228
+ def _result(self, value: object) -> dict:
229
+ """An expression's value as an answer: masked, plain, cut."""
230
+ value = plain(self.session.masker.mask("", value))
231
+ e = entry("result", value)
232
+ e.pop("name", None)
233
+ if e["type"] in ("dict", "list"):
234
+ text = to_json(value)
235
+ if len(text) > capture.VALUE_LIMIT:
236
+ e["value"] = text[: capture.VALUE_LIMIT]
237
+ e["cut"] = len(text)
238
+ else:
239
+ e["value"] = value
240
+ return e
241
+
242
+ def _masked_row(self, host: str, expr: str) -> dict | None:
243
+ """The answer for an expression that reads a masked value: masked whole, with the kind
244
+ of what it reads (a filter's result keeps it: reverse, list, length, hash, ==)."""
245
+ try:
246
+ why = self.masked_by(host, expr)
247
+ except TooMany:
248
+ return {
249
+ "host": host,
250
+ "expr": expr,
251
+ "error": (
252
+ f"hostvars with a host chosen at run time is not evaluated in an inventory "
253
+ f"of more than {MAX_HOSTS} hosts: name the host"
254
+ ),
255
+ "refused": True,
256
+ }
257
+ if why:
258
+ return {"host": host, "expr": expr, "type": "masked", "masked": why}
259
+ return None
260
+
261
+ def evaluate(self, host: str, expr: str, timeout: object = None) -> dict:
262
+ refused = render.precheck(expr, self.environment())
263
+ if refused:
264
+ return {"host": host, "expr": expr, "error": refused, "refused": True}
265
+ # The plain texts of this host's vaulted values are learned here, before the child.
266
+ masked = self._masked_row(host, expr)
267
+ if masked:
268
+ return masked
269
+ target = self.hosts[host]
270
+
271
+ def work() -> object:
272
+ value = self._templar_for(target).evaluate_expression(render.trusted(expr))
273
+ return self._result(value)
274
+
275
+ out = render.in_child(work, float(timeout or render.TIME_LIMIT))
276
+ result = out.pop("value", None)
277
+ answer: dict = {"host": host, "expr": expr, **out}
278
+ if isinstance(result, dict):
279
+ answer.update(result)
280
+ return answer
281
+
282
+ def watch(self, req: dict) -> dict:
283
+ exprs = [str(e) for e in (req.get("exprs") or []) if isinstance(e, str)][:50]
284
+ hosts = [str(h) for h in (req.get("hosts") or list(self.hosts)) if str(h) in self.hosts]
285
+ env = self.environment()
286
+ refused = {e: render.precheck(e, env) for e in exprs}
287
+ masked = {(h, e): self._masked_row(h, e) for h in hosts for e in exprs if not refused[e]}
288
+ targets = {h: self.hosts[h] for h in hosts}
289
+
290
+ def work() -> object:
291
+ rows = []
292
+ for h, target in targets.items():
293
+ templar = self._templar_for(target)
294
+ for e in exprs:
295
+ if refused[e]:
296
+ rows.append({"host": h, "expr": e, "error": refused[e], "refused": True})
297
+ continue
298
+ if masked.get((h, e)):
299
+ rows.append(masked[(h, e)])
300
+ continue
301
+ try:
302
+ value = templar.evaluate_expression(render.trusted(e))
303
+ rows.append({"host": h, "expr": e, **self._result(value)})
304
+ except Exception as ex: # noqa: BLE001
305
+ rows.append({"host": h, "expr": e, "error": render.error_text(ex)})
306
+ return rows
307
+
308
+ limit = float(req.get("timeout") or render.TIME_LIMIT) * max(1, len(exprs))
309
+ out = render.in_child(work, min(limit, render.MAX_TIME_LIMIT))
310
+ if "error" in out:
311
+ return {"error": out["error"], "ms": out.get("ms")}
312
+ return {"results": out.get("value") or [], "ms": out.get("ms")}
313
+
314
+
315
+ # ---- pause points with settings at a step gate ----------------------------------------------
316
+ def point_settings(point: Mapping) -> dict:
317
+ out: dict = {}
318
+ cond = point.get("condition")
319
+ if isinstance(cond, str) and cond.strip():
320
+ out["condition"] = cond.strip()
321
+ hits = point.get("hits")
322
+ if isinstance(hits, int) and not isinstance(hits, bool) and hits > 0:
323
+ out["hits"] = hits
324
+ log = point.get("log")
325
+ if isinstance(log, str) and log.strip():
326
+ out["log"] = log
327
+ return out
328
+
329
+
330
+ def _masked_by(gate: Gate, host: str, text: str, template: bool = False) -> str | None:
331
+ try:
332
+ return gate.masked_by(host, text, template=template)
333
+ except TooMany:
334
+ return "name" # hostvars by a host chosen at run time in a large inventory: not shown
335
+
336
+
337
+ def at_point(session: Session, strategy, play, hosts: list, node: str, point: Mapping) -> dict:
338
+ """A pause point's settings at its gate, for every host:
339
+ - condition: Jinja per host; all hosts pause if any matches (the matched hosts are named);
340
+ an error is reported and does not pause;
341
+ - hits: hosts arriving here (matching the condition, if any) are counted; it pauses where
342
+ the count reaches N;
343
+ - log: rendered per host (where the condition holds), masked; never pauses.
344
+ Returns {pause, matched, events}: events to append (log lines, errors, the hit count)."""
345
+ settings = point_settings(point)
346
+ cond, hits, log = settings.get("condition"), settings.get("hits"), settings.get("log")
347
+ events: list[dict] = []
348
+ names = [h.get_name() for h in hosts]
349
+ matched = names
350
+ if cond or log:
351
+ gate = Gate(session, strategy, play, hosts, "")
352
+ env = gate.environment()
353
+ bad_cond = render.precheck(cond, env, "a condition") if cond else None
354
+ bad_log = render.check_template(log, env, "a log message") if log else None
355
+ # Before the child: the vaulted plain texts are learned, and what each host's condition
356
+ # and message read is checked (AFD-373). A condition that reads a masked value is not
357
+ # checked (true or false would tell its value); in a message, each {{ }} that reads one
358
+ # is masked (a {% %} that reads one masks the whole message).
359
+ taint: dict[str, dict] = {}
360
+ for h in names:
361
+ gate.view(h)
362
+ row: dict = {}
363
+ if cond and not bad_cond:
364
+ why = _masked_by(gate, h, cond)
365
+ if why:
366
+ row["cond"] = why
367
+ if log and not bad_log:
368
+ whole = _masked_by(gate, h, log, template=True)
369
+ if whole:
370
+ text, kinds = mask_blocks(
371
+ env,
372
+ log,
373
+ lambda e, h=h, whole=whole: _masked_by(gate, h, e) if e else whole,
374
+ )
375
+ row["log"] = text
376
+ row["kinds"] = sorted(kinds or {whole})
377
+ taint[h] = row
378
+ masker = session.masker
379
+
380
+ def work() -> object:
381
+ rows = {}
382
+ for h in hosts:
383
+ templar = gate._templar_for(h)
384
+ row: dict = {}
385
+ masked = taint.get(h.get_name(), {})
386
+ if cond and not bad_cond and masked.get("cond"):
387
+ row["cond"] = (
388
+ f"The condition reads a masked value ({masked['cond']}): it is not checked"
389
+ )
390
+ elif cond and not bad_cond:
391
+ try:
392
+ row["cond"] = bool(templar.evaluate_conditional(render.trusted(cond)))
393
+ except Exception as ex: # noqa: BLE001
394
+ row["cond"] = render.error_text(ex)
395
+ if log and not bad_log and row.get("cond", True) is True:
396
+ try:
397
+ # A message that reads masked values renders with those parts masked
398
+ # (None: masked whole).
399
+ source = masked.get("log", log)
400
+ if source is None:
401
+ value: object = REDACTED
402
+ else:
403
+ value = templar.template(render.trusted(source))
404
+ text, kinds = masker.scrub(str(value), value)
405
+ kinds |= set(masked.get("kinds") or [])
406
+ row["log"] = text
407
+ if kinds:
408
+ row["masked"] = sorted(kinds)
409
+ except Exception as ex: # noqa: BLE001
410
+ row["logError"] = render.error_text(ex)
411
+ rows[h.get_name()] = row
412
+ return rows
413
+
414
+ out = render.in_child(work, GATE_LIMIT) if not (bad_cond and (bad_log or not log)) else {}
415
+ rows: dict = out.get("value") or {}
416
+ if "error" in out:
417
+ events.append({"event": "log", "node": node, "source": "point", "error": out["error"]})
418
+ if bad_cond:
419
+ events.append({"event": "log", "node": node, "source": "condition", "error": bad_cond})
420
+ if bad_log:
421
+ events.append({"event": "log", "node": node, "source": "log", "error": bad_log})
422
+ if cond:
423
+ matched = []
424
+ for h in names:
425
+ c = rows.get(h, {}).get("cond")
426
+ if c is True:
427
+ matched.append(h)
428
+ elif isinstance(c, str):
429
+ events.append(
430
+ {"event": "log", "node": node, "host": h, "source": "condition", "error": c}
431
+ )
432
+ if bad_cond or "error" in out:
433
+ matched = []
434
+ if log:
435
+ for h in names:
436
+ row = rows.get(h, {})
437
+ if "log" in row:
438
+ e = {"event": "log", "node": node, "host": h, "message": row["log"]}
439
+ if row.get("masked"):
440
+ e["masked"] = row["masked"]
441
+ events.append(e)
442
+ elif "logError" in row:
443
+ events.append(
444
+ {
445
+ "event": "log",
446
+ "node": node,
447
+ "host": h,
448
+ "source": "log",
449
+ "error": row["logError"],
450
+ }
451
+ )
452
+ pause = bool(matched) and not log
453
+ if hits:
454
+ before = session.hits.get(node, 0)
455
+ now = before + len(matched)
456
+ session.hits[node] = now
457
+ events.append({"event": "hits", "node": node, "count": now, "hits": hits})
458
+ pause = pause and before < hits <= now
459
+ return {"pause": pause, "matched": matched if cond else [], "events": events}