@ansible-flow/assets 1.0.3 → 1.1.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.
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.0.3
5
+ Built from [Ansible Flow Designer](https://github.com/ChistokhinSV/ansible-flow-designer) 1.1.0-rc.2
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.0.3",
3
+ "version": "1.1.0-rc.2",
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",
@@ -48,6 +48,8 @@ def run_config(root: str) -> dict[str, Any]:
48
48
  "lookup_plugins": paths("DEFAULT_LOOKUP_PLUGIN_PATH"),
49
49
  "test_plugins": paths("DEFAULT_TEST_PLUGIN_PATH"),
50
50
  "vars_plugins": paths("DEFAULT_VARS_PLUGIN_PATH"),
51
+ # AFD-346: a step-by-step run sets ANSIBLE_STRATEGY_PLUGINS; these stay in it.
52
+ "strategy_plugins": paths("DEFAULT_STRATEGY_PLUGIN_PATH"),
51
53
  },
52
54
  "vars_enabled": [str(v) for v in (getattr(C, "VARIABLE_PLUGINS_ENABLED", None) or [])],
53
55
  }
@@ -0,0 +1,180 @@
1
+ # Ansible Flow Designer step-by-step runs (AFD-346, ADR-0039): the linear strategy that, before the
2
+ # first task of a flow step, asks the run's driver whether to go on. Stdlib only; enabled for a
3
+ # step-by-step run only, with ANSIBLE_STRATEGY=afd_step and ANSIBLE_STRATEGY_PLUGINS naming this
4
+ # folder. With it off, nothing here is loaded and a run is what it always was.
5
+ #
6
+ # The channel is two files in the run folder, the same way events.jsonl already comes back from a
7
+ # local, WSL, SSH or container run (nothing listens on a port):
8
+ # - run -> driver: pause, resume and stopped events, appended to events.jsonl (AFD_EVENTS);
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}.
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import os
16
+ import re
17
+ import secrets
18
+ import sys
19
+ import time
20
+
21
+ from ansible.plugins.strategy.linear import StrategyModule as LinearStrategy
22
+ from ansible.utils.display import Display
23
+
24
+ DOCUMENTATION = """
25
+ name: afd_step
26
+ short_description: Ansible Flow Designer step-by-step runs (linear, pausing before each step)
27
+ description:
28
+ - The linear strategy, pausing before the first task of a flow step (a play with
29
+ vars.flow_node_id) until the driver of the run says step, continue or stop in the file
30
+ named by AFD_STEP_CONTROL. Pause, resume and stopped events go to the file named by
31
+ AFD_EVENTS, beside the afd_events callback's.
32
+ - A step's several plays (arriving hosts, the step, its route) pause once, before the first.
33
+ - AFD_STEP_TIMEOUT (seconds, default 3600) ends a pause nobody answers; the run then stops.
34
+ - AFD_STEP_INSIDE names the step a run starts inside (an approval's later segment): no pause
35
+ before its first play.
36
+ author: Ansible Flow Designer
37
+ """
38
+
39
+ display = Display()
40
+
41
+
42
+ def _paused_line(play: str, hosts: int) -> str:
43
+ """The terminal's line for a pause: the step's title without its [key], the hosts waiting."""
44
+ title = re.sub(r"^\[[^\]]*\]\s*", "", play) or play
45
+ waits = "1 host waits" if hosts == 1 else f"{hosts} hosts wait"
46
+ return f"Paused before {title}: {waits} for Step, Continue or Stop"
47
+
48
+
49
+ VERSION = 1
50
+ POLL_S = 0.1
51
+ DEFAULT_TIMEOUT_S = 3600.0
52
+ # Pausing again: the driver's command until it changes; step and pause stop at the next step.
53
+ PAUSING = ("step", "pause")
54
+
55
+
56
+ class _State:
57
+ """One per ansible-playbook process (kept on the task queue manager, which outlives plays)."""
58
+
59
+ def __init__(self) -> None:
60
+ self.control = os.environ.get("AFD_STEP_CONTROL") or ""
61
+ events = os.environ.get("AFD_EVENTS")
62
+ self.events = events or ""
63
+ try:
64
+ self.timeout = float(os.environ.get("AFD_STEP_TIMEOUT") or DEFAULT_TIMEOUT_S)
65
+ except ValueError:
66
+ self.timeout = DEFAULT_TIMEOUT_S
67
+ # Pause ids name this process too: a run of approval segments is several processes.
68
+ self.token = secrets.token_hex(4)
69
+ self.count = 0
70
+ # An approval's later segment starts inside the approval step (its route play): that step
71
+ # paused already, in the segment before (AFD_STEP_INSIDE names it).
72
+ self.last_node: str | None = os.environ.get("AFD_STEP_INSIDE") or None
73
+ self.stopped = False
74
+ self.good: dict = {}
75
+
76
+ def read(self) -> dict:
77
+ """The driver's last control.json. While it is being replaced (or a half-written one is
78
+ read over SSH) the last whole one stands: a step boundary never runs on by mistake."""
79
+ try:
80
+ with open(self.control, encoding="utf-8") as f:
81
+ data = json.load(f)
82
+ except (OSError, ValueError):
83
+ return self.good
84
+ if isinstance(data, dict) and data.get("v") == VERSION:
85
+ self.good = data
86
+ return self.good
87
+
88
+ def emit(self, **event: object) -> None:
89
+ if not self.events:
90
+ return
91
+ event["ts"] = round(time.time(), 3)
92
+ # Appended as one line, as the afd_events callback does (same process, same thread).
93
+ with open(self.events, "a", encoding="utf-8") as f:
94
+ f.write(json.dumps(event, default=str) + "\n")
95
+
96
+
97
+ def _wants_pause(control: dict, node: str) -> bool:
98
+ if control.get("command") in PAUSING:
99
+ return True
100
+ points = control.get("points")
101
+ return isinstance(points, list) and node in points
102
+
103
+
104
+ class StrategyModule(LinearStrategy):
105
+ def _afd_state(self) -> _State:
106
+ state = getattr(self._tqm, "_afd_step", None)
107
+ if state is None:
108
+ state = _State()
109
+ self._tqm._afd_step = state
110
+ return state
111
+
112
+ def run(self, iterator, play_context): # type: ignore[override]
113
+ state = self._afd_state()
114
+ play = iterator._play
115
+ node = (play.vars or {}).get("flow_node_id")
116
+ node = str(node) if node else None
117
+ if state.stopped:
118
+ return self._tqm.RUN_FAILED_BREAK_PLAY
119
+ # The first play of a step only: a step's arriving and route plays go on with it.
120
+ if node and node != state.last_node and state.control:
121
+ self._set_hosts_cache(play)
122
+ hosts = [h.get_name() for h in self.get_hosts_left(iterator)]
123
+ # A play no host reaches is not where a step starts for anyone.
124
+ if hosts:
125
+ state.last_node = node
126
+ if self._afd_gate(state, node, play.get_name(), hosts) == "stop":
127
+ state.stopped = True
128
+ return self._tqm.RUN_FAILED_BREAK_PLAY
129
+ return super().run(iterator, play_context)
130
+
131
+ def _afd_gate(self, state: _State, node: str, name: str, hosts: list[str]) -> str:
132
+ """Pauses before `node` when the driver wants it; returns step, continue or stop."""
133
+ control = state.read()
134
+ if control.get("command") == "stop":
135
+ state.emit(event="stopped", node=node, play=name, hosts=hosts, reason="driver")
136
+ return "stop"
137
+ if not _wants_pause(control, node):
138
+ return "continue"
139
+ state.count += 1
140
+ 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)))
151
+ # Out now, before anyone answers: a pipe (a server's run) holds it back otherwise, and the
152
+ # line came after who said Step.
153
+ sys.stdout.flush()
154
+ deadline = time.monotonic() + state.timeout
155
+ while True:
156
+ control = state.read()
157
+ command = control.get("command")
158
+ if control.get("reply") == pause and command in ("step", "continue", "stop"):
159
+ break
160
+ # A stop needs no reply: it may come from a driver that missed this pause.
161
+ if command == "stop":
162
+ 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).
165
+ if time.monotonic() > deadline:
166
+ state.emit(
167
+ event="stopped", id=pause, node=node, play=name, hosts=hosts, reason="timeout"
168
+ )
169
+ display.warning(
170
+ f"Nobody answered the pause for {int(state.timeout)} s: the run stops here"
171
+ )
172
+ return "stop"
173
+ time.sleep(POLL_S)
174
+ if command == "stop":
175
+ state.emit(
176
+ event="stopped", id=pause, node=node, play=name, hosts=hosts, reason="driver"
177
+ )
178
+ return "stop"
179
+ state.emit(event="resume", id=pause, node=node, command=command)
180
+ return command