From 8a4f72185e6fd3f144e85b5153e75a778adc9311 Mon Sep 17 00:00:00 2001 From: Blai Peidro Date: Wed, 2 Dec 2026 23:51:51 +0100 Subject: [PATCH 1/5] feat: the plugins hold a paused playbook and keep its checkpoints The af_events callback plugin and the af_facts cache plugin of the controller's 7.10.0, a job's own key that seals its checkpoints, and the controls that come on a job's stdin after it. --- internal/jobstream/jobstream.go | 85 +++- internal/jobstream/jobstream_test.go | 25 ++ internal/plugins/cache_plugins/af_facts.py | 87 +++++ .../plugins/callback_plugins/af_events.py | 367 +++++++++++++++++- internal/plugins/plugins.go | 48 ++- internal/plugins/plugins_test.go | 9 +- internal/socket/sealed.go | 49 ++- internal/socket/sealed_test.go | 23 ++ 8 files changed, 674 insertions(+), 19 deletions(-) create mode 100644 internal/plugins/cache_plugins/af_facts.py diff --git a/internal/jobstream/jobstream.go b/internal/jobstream/jobstream.go index 4fa130f..df91595 100644 --- a/internal/jobstream/jobstream.go +++ b/internal/jobstream/jobstream.go @@ -1,8 +1,10 @@ // Package jobstream is what goes between the Runner and a job's container: the job in, on the -// container's stdin, once ; its items out, on its stdout, one numbered JSON line each. +// container's stdin, once, then its controls (a pause, a resume) as they come ; its items out, on +// its stdout, one numbered JSON line each. // // in one JSON line: the job (Header), its secrets among it // then a tar of its folders: / for each folder the job names +// then a JSON line per control: {"t":"pause","paused":true,"by":"admin"} // out {"seq":1,"item":{"kind":"started",...}} // {"seq":2,"item":{"kind":"output","record":{...}}} // ... {"seq":n,"item":{"kind":"end",...}} @@ -39,6 +41,12 @@ type Header struct { Playbook string `json:"playbook"` // Inventories are its inventories' folders: their repository, and their folder of the stream. Inventories []Inventory `json:"inventories"` + // Key is the job's own key (socket.JobKey), which seals its checkpoints for the controller ; + // none when it records none. + Key []byte `json:"key,omitempty"` + // Resume is what a playbook that starts again from its checkpoints restores (the run + // message's resume, opened): { startAt, failed, facts, vars } ; none for a first run. + Resume json.RawMessage `json:"resume,omitempty"` } // Inventory is a folder of a job's inventories. @@ -150,8 +158,38 @@ func addFolder(tw *tar.Writer, name, dir string) error { // // When it cannot be read, or its tar holds an entry outside its folder or a link. func ReadJob(r io.Reader, into string) (Header, error) { + return ReadJobFrom(NewReader(r), into) +} + +// NewReader is the buffered reader of a job's stdin: ReadJobFrom reads the job from it, and +// ReadControls what comes after it. +// +// Args: +// +// r: the stdin. +// +// Returns: +// +// The reader. +func NewReader(r io.Reader) *bufio.Reader { return bufio.NewReaderSize(r, 64*1024) } + +// ReadJobFrom reads a job as ReadJob does, from a buffered reader: it stops at the end of the +// tar, what comes after it (the controls) left in the reader. +// +// Args: +// +// br: where it comes from (NewReader). +// into: the folder its folders go in. +// +// Returns: +// +// The job. +// +// Errors: +// +// When it cannot be read, or its tar holds an entry outside its folder or a link. +func ReadJobFrom(br *bufio.Reader, into string) (Header, error) { var h Header - br := bufio.NewReaderSize(r, 64*1024) line, err := readLine(br) if err != nil { return h, fmt.Errorf("the job's header cannot be read: %v", err) @@ -244,6 +282,49 @@ func writeFile(target string, r io.Reader, mode os.FileMode) error { return err } +// ─── the controls in ────────────────────────────────────────────────────────── + +// Control is what the Runner asks of a running job after its start: hold its playbook before its +// next task (Paused), or let it go on ; By is who asked. +type Control struct { + T string `json:"t"` + Paused bool `json:"paused"` + By string `json:"by"` +} + +// ControlLine is a pause or a resume as it goes on a job's stdin. +// +// Args: +// +// paused: true to hold the playbook, false to let it go on. +// by: who asked. +// +// Returns: +// +// The line, its end included. +func ControlLine(paused bool, by string) []byte { + line, _ := json.Marshal(Control{T: "pause", Paused: paused, By: by}) + return append(line, '\n') +} + +// ReadControls reads the controls that come on a job's stdin after the job, each handed on ; a +// line that is not one skipped. It returns once the stdin ends. +// +// Args: +// +// r: the rest of the stdin (ReadJobFrom's reader). +// each: what takes each control. +func ReadControls(r io.Reader, each func(Control)) { + scan := bufio.NewScanner(r) + scan.Buffer(make([]byte, 4096), 64*1024) + for scan.Scan() { + var c Control + if json.Unmarshal(scan.Bytes(), &c) == nil && c.T == "pause" { + each(c) + } + } +} + // ─── the items out ──────────────────────────────────────────────────────────── // Line is an item of the job, numbered. diff --git a/internal/jobstream/jobstream_test.go b/internal/jobstream/jobstream_test.go index 5baedad..2f505ad 100644 --- a/internal/jobstream/jobstream_test.go +++ b/internal/jobstream/jobstream_test.go @@ -5,6 +5,7 @@ import ( "bytes" "encoding/json" "errors" + "io" "os" "path/filepath" "strings" @@ -167,3 +168,27 @@ func TestLines(t *testing.T) { t.Error("a line too long breaks the stream") } } + +// TestControlsAfterTheJob checks the controls that come on the stdin after the job: read once the +// job's tar ended, without waiting for the stdin's end, a line that is not one skipped ; the key +// and the resume of the header kept. +func TestControlsAfterTheJob(t *testing.T) { + pr, pw := io.Pipe() + go func() { + _ = WriteJob(pw, Header{ID: 8, Key: []byte{1, 2}, Resume: json.RawMessage(`{"startAt":"t2"}`)}, map[string]string{}) + _, _ = pw.Write(ControlLine(true, "admin")) + _, _ = pw.Write([]byte("not json\n{\"t\":\"other\"}\n")) + _, _ = pw.Write(ControlLine(false, "bob")) + pw.Close() + }() + br := NewReader(pr) + h, err := ReadJobFrom(br, t.TempDir()) + if err != nil || h.ID != 8 || len(h.Key) != 2 || string(h.Resume) != `{"startAt":"t2"}` { + t.Fatalf("header %+v, %v", h, err) + } + var got []Control + ReadControls(br, func(c Control) { got = append(got, c) }) + if len(got) != 2 || !got[0].Paused || got[0].By != "admin" || got[1].Paused || got[1].By != "bob" { + t.Errorf("controls %+v", got) + } +} diff --git a/internal/plugins/cache_plugins/af_facts.py b/internal/plugins/cache_plugins/af_facts.py new file mode 100644 index 0000000..eb2c9e1 --- /dev/null +++ b/internal/plugins/cache_plugins/af_facts.py @@ -0,0 +1,87 @@ +# AnsibleForms : the fact cache of a resumable playbook (a form with resumable: true, 7.10.0). Each +# host's facts - gathered, and set by set_fact or include_vars with cacheable - are kept in memory as +# ansible's own memory cache does, and each change is written as a JSON line to the checkpoints file +# AF_CHECKPOINT_FILE names : the RTE reads it as it grows and sends it to the controller, which keeps +# it in its database, encrypted (job_checkpoints). When the playbook starts again after its runner +# restarted, the facts it had come back from AF_RESUME_FILE, which the RTE writes from the controller's +# checkpoints before the playbook starts. +# +# The RTE sets it (ANSIBLE_CACHE_PLUGIN=af_facts, its folder in ANSIBLE_CACHE_PLUGINS) for a resumable +# playbook only : a fact cache the playbook's own ansible.cfg names is not used then. +from __future__ import annotations + +import json +import os + +from ansible.plugins.cache import BaseCacheModule + +DOCUMENTATION = """ +name: af_facts +short_description: AnsibleForms checkpoints of the facts of a resumable playbook +description: + - Keeps each host's facts in memory, writes every change to the file AF_CHECKPOINT_FILE names, and + starts with the facts AF_RESUME_FILE holds, when it names one. +""" + + +class CacheModule(BaseCacheModule): + # a cache in memory, as ansible's own : no key munging, no JSON wrapping + _persistent = False + + def __init__(self, *args, **kwargs): + """Starts with the facts a resume restores, and opens the checkpoints file.""" + super().__init__(*args, **kwargs) + self._cache = {} + self._out = None + resume = os.environ.get("AF_RESUME_FILE") + if resume: + try: + with open(resume, "r", encoding="utf-8") as handle: + facts = (json.load(handle) or {}).get("facts") or {} + if isinstance(facts, dict): + self._cache = {str(h): v for h, v in facts.items() if isinstance(v, dict)} + except (OSError, ValueError): + pass + path = os.environ.get("AF_CHECKPOINT_FILE") + if path: + try: + self._out = open(path, "a", encoding="utf-8") + except OSError: + self._out = None + + def _write(self, host, value): + """Writes one host's facts as a checkpoint line (none : removed). + + Args: + host: the host. + value: its facts, or None. + """ + if not self._out: + return + try: + self._out.write(json.dumps({"type": "facts", "host": host, "value": value}, default=str, ensure_ascii=False) + "\n") + self._out.flush() + except (OSError, TypeError, ValueError): + pass + + def get(self, key): + return self._cache[key] + + def set(self, key, value): + self._cache[key] = value + self._write(key, value) + + def keys(self): + return list(self._cache.keys()) + + def contains(self, key): + return key in self._cache + + def delete(self, key): + del self._cache[key] + self._write(key, None) + + def flush(self): + for key in list(self._cache.keys()): + self._write(key, None) + self._cache = {} diff --git a/internal/plugins/callback_plugins/af_events.py b/internal/plugins/callback_plugins/af_events.py index 90df561..2c5f84d 100644 --- a/internal/plugins/callback_plugins/af_events.py +++ b/internal/plugins/callback_plugins/af_events.py @@ -12,11 +12,29 @@ # (_ansible_*) are left out, the values of keys that look like a secret (password, secret, token, # key...) are masked, and it is cut when it is too large. A task with no_log has its result censored # by Ansible before it comes here, and the controller masks the job's own secret values when it stores it. +# +# It also holds the playbook between two tasks while the job is paused (7.10.0) : the RTE creates the +# file AF_PAUSE_FILE names when the controller asks for a pause, and removes it on a resume. The task +# running then finishes ; before the next one starts, the playbook waits here, its process alive (never +# a SIGSTOP : ssh and remote commands would time out underneath), says so in the output and in a +# "paused" event, and goes on once the file is gone. An abort stops it while it waits, as any time. +# +# A resumable playbook (a form with resumable: true) gets more : when AF_CHECKPOINT_FILE is set, it +# writes there, as JSON lines, per host the variables a resume needs (registered results, set_fact, +# include_vars) and, before each task, the playbook's progress : that task is its first unfinished +# one, and what would keep a resume from starting there (a pending handler, an add_host, a dynamic +# include before it, a duplicate or unnamed task, a block with rescue, serial batches, run_once, +# vars_prompt). The RTE sends them to the controller, which keeps them encrypted. When the playbook +# starts again after its runner restarted (--start-at-task, AF_RESUME_FILE), it sets the variables +# back at the first play's start, at the precedence they had (set_fact, register) ; the facts come +# back through the af_facts cache plugin. from __future__ import annotations +import fnmatch import json import os import re +import sys import time from ansible.plugins.callback import CallbackBase @@ -42,6 +60,15 @@ # the keys a result never keeps, at any depth : the module's arguments as the task passed them # (a password, a token, a request's body and headers) DROPPED_KEYS = ("invocation",) +# how often a paused playbook looks whether it may go on, in seconds +PAUSE_POLL = 0.5 +# the task ansible adds to a play to gather its facts : a pause holds before the task after it +GATHER_ACTIONS = ("gather_facts", "ansible.builtin.gather_facts") +# what a resume cannot restore once it ran before the resume point (a resumable playbook) +DYNAMIC_INCLUDES = ("include_tasks", "include_role", "include", "ansible.builtin.include_tasks", "ansible.builtin.include_role", "ansible.builtin.include") +INVENTORY_CHANGES = ("add_host", "group_by", "ansible.builtin.add_host", "ansible.builtin.group_by") +SET_FACT_ACTIONS = ("set_fact", "ansible.builtin.set_fact", "ansible.legacy.set_fact") +INCLUDE_VARS_ACTIONS = ("include_vars", "ansible.builtin.include_vars", "ansible.legacy.include_vars") # the keys whose values are masked, at any depth : those that look like a secret, as the controller's # MASK_EXTRAVARS_REGEX (password|secret|token by default), with a request's own (authorization, # cookie) and keys ; the controller's own pattern added when the RTE passes it (AF_EVENTS_MASK_REGEX) @@ -167,6 +194,28 @@ def __init__(self, *args, **kwargs): self._task_uuid = "" # when each host started the current task : a result's duration self._started = {} + # the file whose presence holds the playbook before its next task (a pause), and the last + # task that started : the one it paused after + self._pause_path = os.environ.get("AF_PAUSE_FILE") + self._last_task = "" + # a resumable playbook : its checkpoints, and the variables a resume restores + self._ck = None + self._ck_path = os.environ.get("AF_CHECKPOINT_FILE") + self._resume_path = os.environ.get("AF_RESUME_FILE") + self._restored = False + # the task names started so far (a resume point's name must be its own), what keeps a resume + # from any later point (blocked), what keeps it within the current play (play_blockers), the + # handlers notified and not run, the hosts failed (a resume leaves them out) + self._names = [] + self._blocked = [] + self._play_blockers = [] + self._pending_handlers = set() + self._failed_hosts = set() + if self._ck_path: + try: + self._ck = open(self._ck_path, "a", encoding="utf-8") + except OSError as error: + self._display.warning(f"AnsibleForms could not write the playbook's checkpoints : {error}") if self._path: try: self._handle = open(self._path, "a", encoding="utf-8") @@ -199,7 +248,8 @@ def _emit(self, kind, **fields): self._handle = None def v2_playbook_on_play_start(self, play): - """A play starts. + """A play starts : a resumed playbook gets its variables back at the first one ; a resumable + one notes what of this play a resume could not restore. Args: play: the play. @@ -207,26 +257,331 @@ def v2_playbook_on_play_start(self, play): self._play = play.get_name().strip() self._task = "" self._emit("play") + if self._resume_path and not self._restored: + self._restored = True + self._restore(play) + if self._ck: + self._play_blockers = self._blockers_of_play(play) + self._pending_handlers = set() + + # ─── a resumable playbook's checkpoints ────────────────────────────────── + + def _ck_write(self, kind, **fields): + """Writes one checkpoint as a JSON line, at once (the RTE reads the file as it grows). + + Args: + kind: facts, vars or progress. + fields: its fields (host, value). + """ + if not self._ck: + return + try: + self._ck.write(json.dumps({"type": kind, **fields}, default=str, ensure_ascii=False) + "\n") + self._ck.flush() + except (OSError, TypeError, ValueError): + pass + + @staticmethod + def _blockers_of_play(play): + """What of a play a resume cannot restore : its serial batches, its vars_prompt, a strategy + other than linear (its tasks do not end together). + + Args: + play: the play. + + Returns: + The reasons, as texts. + """ + out = [] + serial = getattr(play, "serial", None) or [] + if serial and [str(s) for s in serial] not in (["0"], ["100%"]): + out.append("its play runs in serial batches") + if getattr(play, "vars_prompt", None): + out.append("its play has vars_prompt") + strategy = getattr(play, "strategy", None) + if strategy and strategy not in ("linear", "ansible.builtin.linear"): + out.append(f"its play's strategy is {strategy}") + return out + + @staticmethod + def _in_rescue_block(task): + """Whether a task is in a block with rescue or always : its state cannot be restored. + + Args: + task: the task. + + Returns: + True when one of its blocks has a rescue or an always. + """ + parent = getattr(task, "_parent", None) + seen = 0 + while parent is not None and seen < 50: + if getattr(parent, "rescue", None) or getattr(parent, "always", None): + return True + parent = getattr(parent, "_parent", None) + seen += 1 + return False + + def _progress(self, task): + """Writes the playbook's progress before a task : it is the first unfinished one, a resume + starts there (--start-at-task) unless something before it cannot be restored. + + Args: + task: the task about to start. + """ + name = getattr(task, "name", "") or "" + reasons = list(self._blocked) + list(self._play_blockers) + restart = False + if self._pending_handlers: + reasons.append("a handler was notified and has not run yet") + if getattr(task, "action", "") in GATHER_ACTIONS and name == "Gathering Facts": + # a play gathers its facts : a resume can only start the playbook again from its start + if self._names: + reasons.append("it stopped while a play gathered its facts") + else: + restart = True + name = "" + elif not name: + reasons.append(f"its next task ({task.get_name()}) has no name") + elif "{{" in name or "{%" in name: + reasons.append(f"the name of its next task ({name}) is templated") + elif any(n == name or fnmatch.fnmatch(n, name) for n in self._names): + reasons.append(f"the name of its next task ({name}) is used twice") + if name and self._in_rescue_block(task): + reasons.append(f"its next task ({name}) is in a block with rescue or always") + self._ck_write( + "progress", + value={"next": name, "play": self._play, "blockers": reasons, "failed": sorted(self._failed_hosts), "restart": restart}, + ) + + def _note_task(self, task): + """Notes what a task that starts means for a later resume point : its name, and what of it + could not be restored (an add_host or group_by, a dynamic include, a run_once). + + Args: + task: the task. + """ + name = getattr(task, "name", "") or "" + if name: + self._names.append(name) + action = getattr(task, "action", "") + label = name or task.get_name() + if action in INVENTORY_CHANGES: + self._blocked.append(f"task {label} changes the inventory ({action})") + elif action in DYNAMIC_INCLUDES: + self._blocked.append(f"task {label} includes tasks dynamically ({action})") + if getattr(task, "run_once", False): + self._blocked.append(f"task {label} runs once (run_once)") + + @staticmethod + def _layers(result): + """The variables a result sets on its host, as ansible applies them : registered values, + set_fact and include_vars (not the cacheable facts : the af_facts cache plugin keeps those). + + Args: + result: a host's result. + + Returns: + A dictionary of the variables, empty when it sets none. + """ + out = {} + utr = getattr(result, "_CallbackTaskResult__utr", None) + if utr is not None: + # ansible-core 2.19 and later : what the task registers, layer by layer + pending = getattr(getattr(utr, "pending_changes", None), "register_host_variables", None) or {} + for layer, values in sorted(pending.items()): + if getattr(layer, "name", "") in ("INCLUDE_VARS", "EPHEMERAL_FACT", "REGISTER_VARS") and values: + out.update(dict(values)) + out.update(dict(getattr(utr, "registered_values", None) or {})) + return out + # before : the result's own facts for set_fact and include_vars, and its register + task = getattr(result, "_task", None) + data = getattr(result, "_result", None) or {} + if getattr(task, "action", "") in SET_FACT_ACTIONS + INCLUDE_VARS_ACTIONS and isinstance(data.get("ansible_facts"), dict): + out.update(data["ansible_facts"]) + register = getattr(task, "register", None) + if isinstance(register, str) and register: + out[register] = {k: v for k, v in data.items() if not str(k).startswith("_ansible")} + return out + + def _record(self, result, failed=False): + """Records what a host's result sets on it (a resumable playbook), and a host that failed. + + Args: + result: the host's result. + failed: it failed, and the play goes on without it. + """ + if not self._ck: + return + host = result._host.get_name() + if failed: + self._failed_hosts.add(host) + return + # a host that goes on (a rescue, a retry) is no longer one a resume leaves out + self._failed_hosts.discard(host) + # a change notifies its handlers : pending until they ran (ansible says nothing of it to a + # callback outside the handlers' own run) + task = getattr(result, "_task", None) + if (getattr(result, "_result", None) or {}).get("changed") and getattr(task, "notify", None): + notify = task.notify if isinstance(task.notify, list) else [task.notify] + self._pending_handlers.update(str(n) for n in notify if n) + try: + values = self._layers(result) + except Exception: # noqa: BLE001 - a checkpoint is never a reason to stop the playbook + values = {} + if values: + self._ck_write("vars", host=host, value=values) + + def _restore(self, play): + """Sets back the variables of a resumed playbook (AF_RESUME_FILE), per host, at the precedence + they had : what set_fact and register set. + + Args: + play: the first play. + """ + try: + with open(self._resume_path, "r", encoding="utf-8") as handle: + saved = (json.load(handle) or {}).get("vars") or {} + except (OSError, ValueError): + return + manager = play.get_variable_manager() if hasattr(play, "get_variable_manager") else None + if manager is None or not isinstance(saved, dict): + return + restored = 0 + for host, values in saved.items(): + if isinstance(values, dict) and values: + manager.set_nonpersistent_facts(str(host), values) + restored += 1 + self._display.display(f"changed: [Restored the variables of {restored} host(s) from the checkpoints]") + + def _pause_wanted(self): + """Whether the job is paused : the RTE created the pause file. + + Returns: + The pause file's content (who paused it, as JSON) when it is there, else None. + """ + if not self._pause_path: + return None + try: + with open(self._pause_path, "r", encoding="utf-8") as handle: + return handle.read() + except OSError: + return None + + @staticmethod + def _who(text): + """Who a pause file names (its by field), when it names someone. + + Args: + text: the file's content, JSON. + + Returns: + The name, or an empty text. + """ + try: + return str((json.loads(text or "{}") or {}).get("by") or "") + except (ValueError, AttributeError): + return "" + + @staticmethod + def _flush_output(): + """Flushes the playbook's stdout and stderr : a pipe holds what was written until a block + is full, and a paused playbook writes nothing more for a while.""" + for stream in (sys.stdout, sys.stderr): + try: + stream.flush() + except (OSError, ValueError): + pass + + def _hold(self, task): + """Waits before a task while the job is paused : says it once, in the output and as a paused + event, then looks every PAUSE_POLL seconds whether the pause file is gone, and says it goes on. + + Args: + task: the task that waits to start. + """ + text = self._pause_wanted() + if text is None: + return + # the implicit fact gathering of a play : it runs, the pause holds before the task after it + if getattr(task, "action", "") in GATHER_ACTIONS and getattr(task, "name", "") == "Gathering Facts": + return + by = self._who(text) + # who paused it, as Resumed by says who resumed it ; the event below carries where too + self._display.display(f"changed: [Paused{' by ' + by if by else ''}]") + self._emit("paused", data={"after": self._last_task, "next": (task.get_name() or "").strip(), "by": by or None}) + # what the playbook wrote so far reaches the job's output now, not when it goes on (its + # stdout is a pipe, written in blocks) + self._flush_output() + while self._pause_wanted() is not None: + time.sleep(PAUSE_POLL) + # who resumed it, when the RTE said (a file beside the pause file) + resumed = "" + try: + with open(self._pause_path + ".resumed", "r", encoding="utf-8") as handle: + resumed = self._who(handle.read()) + os.unlink(self._pause_path + ".resumed") + except OSError: + pass + self._display.display(f"changed: [Resumed{' by ' + resumed if resumed else ''}]") + self._flush_output() + self._emit("resumed", data={"by": resumed or None}) def v2_playbook_on_task_start(self, task, is_conditional): - """A task starts on the play's hosts. + """A task starts on the play's hosts : first held there while the job is paused. Args: task: the task. is_conditional: whether it runs only on some hosts. """ + if self._ck: + self._progress(task) + self._hold(task) + if self._ck: + self._note_task(task) + self._last_task = task.get_name().strip() self._task = task.get_name().strip() self._task_uuid = task._uuid self._started = {} self._emit("task", action=task.action) def v2_playbook_on_handler_task_start(self, task): - """A handler starts : a task like the others. + """A handler starts : a task like the others ; no resume point while it runs. Args: task: the handler. """ - self.v2_playbook_on_task_start(task, False) + self._hold(task) + if self._ck: + # the handler, by its name or a topic it listens to + listen = getattr(task, "listen", None) or [] + for name in [task.get_name(), getattr(task, "name", ""), *(listen if isinstance(listen, list) else [listen])]: + self._pending_handlers.discard(str(name)) + self._ck_write("progress", value={"next": "", "play": self._play, "blockers": ["it stopped while a handler ran"], "failed": sorted(self._failed_hosts), "restart": False}) + self._last_task = task.get_name().strip() + self._task = task.get_name().strip() + self._task_uuid = task._uuid + self._started = {} + self._emit("task", action=task.action) + + def v2_playbook_on_notify(self, handler, host): + """A handler is notified : a resume point before it runs would lose it. + + Args: + handler: the handler. + host: the host that notified it. + """ + if self._ck: + self._pending_handlers.add(handler.get_name()) + + def v2_playbook_on_include(self, included_file): + """Tasks included dynamically : a resume point after them cannot find them. + + Args: + included_file: the included file. + """ + if self._ck: + self._blocked.append(f"tasks were included dynamically ({os.path.basename(str(getattr(included_file, '_filename', '')))})") def v2_runner_on_start(self, host, task): """A host starts the task : its duration counts from here. @@ -315,6 +670,7 @@ def v2_runner_on_ok(self, result): result: the result. """ self._result("changed" if (result._result or {}).get("changed") else "ok", result) + self._record(result) def v2_runner_on_failed(self, result, ignore_errors=False): """A host's task failed. @@ -326,6 +682,7 @@ def v2_runner_on_failed(self, result, ignore_errors=False): self._result("failed", result) if ignore_errors: self._emit("ignored", host=result._host.get_name()) + self._record(result, failed=not ignore_errors) def v2_runner_on_skipped(self, result): """A host skipped the task. @@ -334,6 +691,7 @@ def v2_runner_on_skipped(self, result): result: the result. """ self._result("skipped", result) + self._record(result) def v2_runner_on_unreachable(self, result): """A host could not be reached. @@ -342,6 +700,7 @@ def v2_runner_on_unreachable(self, result): result: the result. """ self._result("unreachable", result) + self._record(result, failed=True) def v2_playbook_on_stats(self, stats): """The recap : per host, how many tasks were ok, changed, failed... diff --git a/internal/plugins/plugins.go b/internal/plugins/plugins.go index e208285..75567d8 100644 --- a/internal/plugins/plugins.go +++ b/internal/plugins/plugins.go @@ -1,8 +1,11 @@ -// Package plugins holds the two ansible callback plugins of a job, as the controller's own Runner -// ships them (server/src/rte/callback_plugins in the application), unchanged: af_events writes -// the playbook's events as JSON lines (AF_EVENTS_FILE), af_artifacts its set_stats data -// (AF_ARTIFACTS_FILE). They are built into the binary and written to a folder at the start, the -// folder ansible's callback plugins path then begins with. +// Package plugins holds the ansible plugins of a job, as the controller's own Runner ships them +// (server/src/rte/callback_plugins and server/src/rte/cache_plugins in the application), +// unchanged: af_events writes the playbook's events as JSON lines (AF_EVENTS_FILE), holds it +// before its next task while the job is paused (AF_PAUSE_FILE) and writes its checkpoints +// (AF_CHECKPOINT_FILE) ; af_artifacts writes its set_stats data (AF_ARTIFACTS_FILE) ; the af_facts +// fact cache keeps its facts as checkpoints, and gives a resumed playbook its facts back +// (AF_RESUME_FILE). They are built into the binary and written to folders at the start, the +// folders ansible's callback and cache plugins paths then begin with. package plugins import ( @@ -11,10 +14,10 @@ import ( "path/filepath" ) -//go:embed callback_plugins/*.py +//go:embed callback_plugins/*.py cache_plugins/*.py var files embed.FS -// Write writes the plugins to a folder, made when it is not there. +// Write writes the callback plugins to a folder, made when it is not there. // // Args: // @@ -24,12 +27,39 @@ var files embed.FS // // When the folder cannot be made or a plugin cannot be written. func Write(dir string) error { + return write("callback_plugins", dir) +} + +// WriteCache writes the cache plugin (af_facts) to a folder, made when it is not there. +// +// Args: +// +// dir: the folder. +// +// Errors: +// +// When the folder cannot be made or the plugin cannot be written. +func WriteCache(dir string) error { + return write("cache_plugins", dir) +} + +// write writes the plugins of one embedded folder to a folder, made when it is not there. +// +// Args: +// +// from: the embedded folder (callback_plugins, cache_plugins). +// dir: the folder. +// +// Errors: +// +// When the folder cannot be made or a plugin cannot be written. +func write(from, dir string) error { if err := os.MkdirAll(dir, 0o755); err != nil { return err } - entries, _ := files.ReadDir("callback_plugins") + entries, _ := files.ReadDir(from) for _, e := range entries { - data, _ := files.ReadFile("callback_plugins/" + e.Name()) + data, _ := files.ReadFile(from + "/" + e.Name()) if err := os.WriteFile(filepath.Join(dir, e.Name()), data, 0o644); err != nil { return err } diff --git a/internal/plugins/plugins_test.go b/internal/plugins/plugins_test.go index dfc05d6..569a0e7 100644 --- a/internal/plugins/plugins_test.go +++ b/internal/plugins/plugins_test.go @@ -7,7 +7,7 @@ import ( "testing" ) -// TestWrite checks both plugins are written, as they are shipped. +// TestWrite checks the callback plugins and the cache plugin are written, as they are shipped. func TestWrite(t *testing.T) { dir := filepath.Join(t.TempDir(), "callback_plugins") if err := Write(dir); err != nil { @@ -19,6 +19,13 @@ func TestWrite(t *testing.T) { t.Errorf("%s: %v", name, err) } } + cache := filepath.Join(t.TempDir(), "cache_plugins") + if err := WriteCache(cache); err != nil { + t.Fatal(err) + } + if data, err := os.ReadFile(filepath.Join(cache, "af_facts.py")); err != nil || !strings.Contains(string(data), "BaseCacheModule") { + t.Errorf("af_facts.py: %v", err) + } } // TestWriteFails checks a folder that cannot be made, and a plugin that cannot be written. diff --git a/internal/socket/sealed.go b/internal/socket/sealed.go index 327e627..e86cb18 100644 --- a/internal/socket/sealed.go +++ b/internal/socket/sealed.go @@ -74,11 +74,54 @@ func sealKey(token string, jobID int64) ([]byte, []byte, error) { // // When there is no token, or the secrets are no JSON. func SealJobSecrets(secrets any, token string, jobID int64) (*Sealed, error) { - key, aad, err := sealKey(token, jobID) + key, err := JobKey(token, jobID) if err != nil { return nil, err } - plain, err := json.Marshal(secrets) + return SealWithKey(secrets, key, jobID) +} + +// JobKey is the key one job's bundles are sealed with: a job's container gets it, never the +// Runner's token, so it seals the job's checkpoints for the controller as the controller's own +// Runner seals them. +// +// Args: +// +// token: the Runner's token. +// jobID: the job. +// +// Returns: +// +// The AES-256 key. +// +// Errors: +// +// When there is no token. +func JobKey(token string, jobID int64) ([]byte, error) { + key, _, err := sealKey(token, jobID) + return key, err +} + +// SealWithKey seals a value with a job's key (JobKey), in the bundle the controller opens. +// +// Args: +// +// value: the value, any JSON value. +// key: the job's key. +// jobID: the job. +// +// Returns: +// +// The sealed bundle. +// +// Errors: +// +// When the key is not a key of AES-256, or the value is no JSON. +func SealWithKey(value any, key []byte, jobID int64) (*Sealed, error) { + if len(key) != 32 { + return nil, errors.New("the job's key is not a key of AES-256") + } + plain, err := json.Marshal(value) if err != nil { return nil, err } @@ -87,7 +130,7 @@ func SealJobSecrets(secrets any, token string, jobID int64) (*Sealed, error) { gcm, _ := cipher.NewGCM(block) iv := make([]byte, gcm.NonceSize()) _, _ = rand.Read(iv) - out := gcm.Seal(nil, iv, plain, aad) + out := gcm.Seal(nil, iv, plain, []byte(fmt.Sprintf("job:%d", jobID))) data, tag := out[:len(out)-gcm.Overhead()], out[len(out)-gcm.Overhead():] enc := base64.StdEncoding.EncodeToString return &Sealed{V: sealVersion, IV: enc(iv), Tag: enc(tag), Data: enc(data)}, nil diff --git a/internal/socket/sealed_test.go b/internal/socket/sealed_test.go index cc0a41a..2ec29e1 100644 --- a/internal/socket/sealed_test.go +++ b/internal/socket/sealed_test.go @@ -85,3 +85,26 @@ func TestSealFailures(t *testing.T) { t.Error("an object read into a number") } } + +// TestSealWithKey checks that a job's key (what its container gets) seals what the token opens, +// and that a key of another length is refused. +func TestSealWithKey(t *testing.T) { + key, err := JobKey("token-0123456789abcdef", 9) + if err != nil || len(key) != 32 { + t.Fatalf("key %d, %v", len(key), err) + } + if _, err := JobKey("", 9); err == nil { + t.Error("a key without a token") + } + s, err := SealWithKey([]any{"x"}, key, 9) + if err != nil { + t.Fatal(err) + } + var got []string + if err := OpenJobSecrets(map[string]any{"v": float64(1), "iv": s.IV, "tag": s.Tag, "data": s.Data}, "token-0123456789abcdef", 9, &got); err != nil || got[0] != "x" { + t.Errorf("opened %v, %v", got, err) + } + if _, err := SealWithKey("x", key[:16], 9); err == nil { + t.Error("sealed with a short key") + } +} From 41343aa63cc819c647679e5bfff380977239151f Mon Sep 17 00:00:00 2001 From: Blai Peidro Date: Wed, 2 Dec 2026 23:51:51 +0100 Subject: [PATCH 2/5] feat: a job's agent pauses, resumes and starts again from checkpoints The agent makes or removes the playbook's pause file as the pauses and resumes come on its stdin, says the plugin's pause and resume as items, sends its checkpoints sealed, and starts a playbook again at its first unfinished task with what its checkpoints restore. --- internal/agent/agent.go | 126 +++++++++++++++++++++++- internal/agent/agent_test.go | 126 ++++++++++++++++++++++++ internal/ansible/prepare.go | 2 +- internal/ansible/resume.go | 163 ++++++++++++++++++++++++++++++++ internal/ansible/resume_test.go | 67 +++++++++++++ internal/ansible/run.go | 71 +++++++++++++- internal/ansible/run_test.go | 75 +++++++++++++++ 7 files changed, 622 insertions(+), 8 deletions(-) create mode 100644 internal/ansible/resume.go create mode 100644 internal/ansible/resume_test.go diff --git a/internal/agent/agent.go b/internal/agent/agent.go index a8d09f5..1b0eb22 100644 --- a/internal/agent/agent.go +++ b/internal/agent/agent.go @@ -3,6 +3,9 @@ // would run it (internal/ansible), and writes its items, their secrets masked, as numbered lines // on its stdout, which the Runner reads as the container's logs. A SIGTERM (the container // stopped: the job aborted) stops the playbook's process group, the job then ended as aborted. +// What comes on its stdin after the job are its pauses and resumes: a pause makes the playbook's +// pause file, which holds it before its next task, a resume removes it. Its checkpoints go out +// sealed with the job's own key, as the controller's own Runner seals them. package agent import ( @@ -21,6 +24,7 @@ import ( "github.com/ansibleforms/runner/internal/mask" "github.com/ansibleforms/runner/internal/output" "github.com/ansibleforms/runner/internal/plugins" + "github.com/ansibleforms/runner/internal/socket" ) // What the tests replace: how the playbook runs, where the job's folder is made, and how its @@ -30,15 +34,25 @@ var ( tempDir = os.TempDir kill = syscall.Kill pluginsWrite = plugins.Write + cacheWrite = plugins.WriteCache ) -// lines is a job's IO: each item a numbered line, its secrets masked ; an abort its flag. +// lines is a job's IO: each item a numbered line, its secrets masked ; an abort its flag ; a +// pause its file. type lines struct { w *jobstream.Writer mask *mask.Job mu sync.Mutex pid int abort bool + // id is the job, key its own key that seals its checkpoints (none: it records none) + id int64 + key []byte + // paused tells a pause is wanted, by who asked it ; pauseFile is the playbook's pause file + // while it runs + paused bool + by string + pauseFile string } // Output sends an output record. @@ -99,6 +113,93 @@ func (l *lines) ResetAbort() { l.abort = false } +// PauseFile follows the playbook's pause file: a pause wanted before it started made at once ; +// none once it ended, its pause forgotten. +func (l *lines) PauseFile(file string) { + l.mu.Lock() + defer l.mu.Unlock() + l.pauseFile = file + if file == "" { + l.paused = false + return + } + if l.paused { + writeWho(file, l.by) + } +} + +// Paused says the playbook holds before its next task. +func (l *lines) Paused(after, next string) { + l.w.Write(map[string]any{"kind": "paused", "after": l.mask.Text(after), "next": l.mask.Text(next)}) +} + +// Resumed says the playbook goes on. +func (l *lines) Resumed() { + l.w.Write(map[string]any{"kind": "resumed"}) +} + +// Checkpoints sends a batch of checkpoints, sealed with the job's key: the controller opens them, +// nothing of them is read on the way. +func (l *lines) Checkpoints(batch []map[string]any) { + sealed, err := socket.SealWithKey(batch, l.key, l.id) + if err != nil { + logger.Error("[Job %d] Its checkpoints cannot be sealed: %v", l.id, err) + return + } + l.w.Write(map[string]any{"kind": "checkpoints", "sealed": sealed}) +} + +// setPaused holds the playbook before its next task, or lets it go on, as the controller's own +// Runner does: its pause file made (who asked it in it) or removed (who resumed it written beside +// it, for the line the plugin prints) ; kept until the playbook starts when it has not yet. +// +// Args: +// +// paused: true to hold it, false to let it go on. +// by: who asked the pause, or resumes it. +func (l *lines) setPaused(paused bool, by string) { + l.mu.Lock() + defer l.mu.Unlock() + was := l.paused + if paused { + if by != "" { + l.by = by + } + l.paused = true + if l.pauseFile != "" && !was { + logger.Notice("[Job %d] Pauses before its next task", l.id) + writeWho(l.pauseFile, l.by) + } + return + } + l.paused = false + if l.pauseFile != "" && was { + logger.Notice("[Job %d] Goes on", l.id) + writeWho(l.pauseFile+".resumed", by) + if err := os.Remove(l.pauseFile); err != nil { + logger.Error("[Job %d] The resume could not be set: %v", l.id, err) + } + } +} + +// writeWho writes a pause file, or the file of who resumed: who, as JSON, readable by its owner +// only. +// +// Args: +// +// file: the file. +// by: who ; none for null. +func writeWho(file, by string) { + var who any + if by != "" { + who = by + } + data, _ := json.Marshal(map[string]any{"by": who}) + if err := os.WriteFile(file, data, 0o600); err != nil { + logger.Error("The pause could not be set: %v", err) + } +} + // stop aborts the job: its flag set, its playbook's process group signalled when it runs. func (l *lines) stop() { l.mu.Lock() @@ -135,10 +236,19 @@ func Run(stdin io.Reader, stdout io.Writer, signals <-chan os.Signal) int { return fail(1, err) } defer os.RemoveAll(work) - h, err := jobstream.ReadJob(stdin, work) + br := jobstream.NewReader(stdin) + h, err := jobstream.ReadJobFrom(br, work) if err != nil { return fail(h.LastOrder+1, err) } + io.id, io.key = h.ID, h.Key + var resume *ansible.Resume + if len(h.Resume) > 0 { + resume = &ansible.Resume{} + if err := json.Unmarshal(h.Resume, resume); err != nil { + return fail(h.LastOrder+1, fmt.Errorf("the job's checkpoints cannot be read: %v", err)) + } + } var sec ansible.Secrets if len(h.Secrets) > 0 { if err := json.Unmarshal(h.Secrets, &sec); err != nil { @@ -152,8 +262,17 @@ func Run(stdin io.Reader, stdout io.Writer, signals <-chan os.Signal) int { return fail(h.LastOrder+1, err) } ansible.PluginsDir = pluginsDir + // and the fact cache of a playbook that records checkpoints + if len(h.Key) > 0 { + cacheDir := filepath.Join(work, ".cache_plugins") + if err := cacheWrite(cacheDir); err != nil { + return fail(h.LastOrder+1, err) + } + ansible.CachePluginsDir = cacheDir + } - // step 3 : an abort while it runs + // step 3 : an abort while it runs ; a pause or a resume, as they come after the job + go jobstream.ReadControls(br, func(c jobstream.Control) { io.setPaused(c.Paused, c.By) }) done := make(chan struct{}) defer close(done) go func() { @@ -170,6 +289,7 @@ func Run(stdin io.Reader, stdout io.Writer, signals <-chan os.Signal) int { roots = append(roots, ansible.Root{Repository: inv.Repository, Dir: filepath.Join(work, inv.Folder)}) } job := ansible.Job{ID: h.ID, Extravars: h.Extravars, LastOrder: h.LastOrder, Mask: io.mask, InventoryRoots: roots, + Checkpoints: len(h.Key) > 0, Resume: resume, PlaybookDir: func(sub string) (string, error) { if h.Playbook == "" { return "", fmt.Errorf("the job came without its playbooks") diff --git a/internal/agent/agent_test.go b/internal/agent/agent_test.go index 33cee9f..401e177 100644 --- a/internal/agent/agent_test.go +++ b/internal/agent/agent_test.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/json" "errors" + "io" "os" "path/filepath" "strings" @@ -15,7 +16,9 @@ import ( "github.com/ansibleforms/runner/internal/ansible" "github.com/ansibleforms/runner/internal/jobstream" "github.com/ansibleforms/runner/internal/logger" + "github.com/ansibleforms/runner/internal/mask" "github.com/ansibleforms/runner/internal/output" + "github.com/ansibleforms/runner/internal/socket" ) // items reads an agent's lines. @@ -249,3 +252,126 @@ func TestMainLogs(t *testing.T) { t.Errorf("off: out %q errs %q", out, errs) } } + +// TestPauseResume checks a job's pauses and resumes as they come after it on its stdin: a pause +// that came before the playbook started made with its pause file, who asked it in it ; a resume +// removes it, who resumed beside it ; its checkpoints recorded with its key and restored from its +// resume, their fact cache written ; the plugin's pause and resume said as items, its checkpoints +// sealed for the controller. +func TestPauseResume(t *testing.T) { + key, _ := socket.JobKey("token-0123456789abcdef", 14) + pr, pw := io.Pipe() + resume := make(chan struct{}) + go func() { + _ = jobstream.WriteJob(pw, jobstream.Header{ID: 14, Playbook: "p", Key: key, Resume: json.RawMessage(`{"startAt":"t2","failed":["web2"]}`)}, nil) + _, _ = pw.Write(jobstream.ControlLine(true, "admin")) + <-resume + _, _ = pw.Write(jobstream.ControlLine(false, "bob")) + pw.Close() + }() + was := runPlaybook + defer func() { runPlaybook = was }() + file := filepath.Join(t.TempDir(), "pause") + runPlaybook = func(j ansible.Job, sec ansible.Secrets, jio ansible.IO) { + if !j.Checkpoints || j.Resume == nil || j.Resume.StartAt != "t2" || j.Resume.Failed[0] != "web2" { + t.Errorf("job %+v", j) + } + if _, err := os.Stat(filepath.Join(ansible.CachePluginsDir, "af_facts.py")); err != nil { + t.Error("the fact cache is written") + } + jio.PauseFile(file) + waitFor(t, func() bool { data, _ := os.ReadFile(file); return string(data) == `{"by":"admin"}` }) + close(resume) + waitFor(t, func() bool { _, err := os.Stat(file); return os.IsNotExist(err) }) + if data, _ := os.ReadFile(file + ".resumed"); string(data) != `{"by":"bob"}` { + t.Errorf("resumed %q", data) + } + jio.Paused("t1", "t2") + jio.Resumed() + jio.Checkpoints([]map[string]any{{"type": "progress", "value": map[string]any{"next": "t3"}}}) + jio.PauseFile("") + jio.End(1, "stdout", "success", "", map[string]any{}) + } + var out bytes.Buffer + if code := Run(pr, &out, make(chan os.Signal)); code != 0 { + t.Errorf("exit %d", code) + } + got := items(t, &out) + if len(got) != 4 || got[0]["kind"] != "paused" || got[0]["after"] != "t1" || got[0]["next"] != "t2" || got[1]["kind"] != "resumed" || got[2]["kind"] != "checkpoints" { + t.Fatalf("items %v", got) + } + var opened []map[string]any + if err := socket.OpenJobSecrets(got[2]["sealed"], "token-0123456789abcdef", 14, &opened); err != nil || opened[0]["type"] != "progress" { + t.Errorf("checkpoints %v, %v", opened, err) + } +} + +// waitFor waits until a condition holds, 5 seconds at most. +// +// Args: +// +// t: the test. +// ok: the condition. +func waitFor(t *testing.T, ok func() bool) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for !ok() { + if time.Now().After(deadline) { + t.Fatal("it did not happen in 5 seconds") + } + time.Sleep(2 * time.Millisecond) + } +} + +// TestSetPaused checks a pause's edges: asked again (its file left as it is, who asked kept when +// none is said), a resume of a job not paused, a pause file that cannot be written or was removed +// already, checkpoints without a key. +func TestSetPaused(t *testing.T) { + var out bytes.Buffer + l := &lines{w: jobstream.NewWriter(&out), mask: &mask.Job{}, id: 3} + l.setPaused(false, "x") + l.setPaused(true, "admin") + l.setPaused(true, "") + if !l.paused || l.by != "admin" { + t.Errorf("paused %v by %q", l.paused, l.by) + } + dir := t.TempDir() + l.PauseFile(filepath.Join(dir, "pause")) + if err := os.Remove(filepath.Join(dir, "pause")); err != nil { + t.Fatal(err) + } + l.setPaused(true, "other") + if _, err := os.Stat(filepath.Join(dir, "pause")); !os.IsNotExist(err) { + t.Error("a pause asked again wrote its file again") + } + l.setPaused(false, "") + if data, _ := os.ReadFile(filepath.Join(dir, "pause.resumed")); string(data) != `{"by":null}` { + t.Errorf("resumed %q", data) + } + l.PauseFile(filepath.Join(dir, "missing", "pause")) + l.setPaused(true, "admin") + l.PauseFile("") + if l.paused { + t.Error("a pause outlives its playbook") + } + l.Checkpoints([]map[string]any{{"type": "vars"}}) + if out.Len() != 0 { + t.Errorf("lines %q", out.String()) + } +} + +// TestRunResumeFails checks a job whose checkpoints cannot be read, and one whose fact cache +// cannot be written: each said as its end. +func TestRunResumeFails(t *testing.T) { + var out bytes.Buffer + if Run(stream(t, jobstream.Header{Resume: json.RawMessage(`[1]`)}, nil), &out, nil) != 1 || !strings.Contains(out.String(), "checkpoints cannot be read") { + t.Errorf("checkpoints that are not: %s", out.String()) + } + was := cacheWrite + defer func() { cacheWrite = was }() + cacheWrite = func(string) error { return errors.New("no room for the cache") } + out.Reset() + if Run(stream(t, jobstream.Header{Key: []byte{1}}, nil), &out, nil) != 1 || !strings.Contains(out.String(), "no room for the cache") { + t.Errorf("no fact cache: %s", out.String()) + } +} diff --git a/internal/ansible/prepare.go b/internal/ansible/prepare.go index f49d95d..7716385 100644 --- a/internal/ansible/prepare.go +++ b/internal/ansible/prepare.go @@ -537,7 +537,7 @@ ENCRYPTION_SECRET ENCRYPTION_SECRET_PREVIOUS ENTRA_AUTHORITY_URI ENTRA_GRAPH_URI FORMS_FOLDER_PATH FORMS_STAGING_PATH GIT_CLONE_COMMAND GIT_PULL_COMMAND GIT_PUSH_COMMAND HOME_PATH HTTPS HTTPS_CERT HTTPS_KEY JOBS_LIST_SIZE JQ_TIMEOUT_SECONDS JOB_RETENTION_DAYS LAUNCH_VALIDATION STORED_JOB_UNUSED_DAYS ABANDONED_JOBS_CRON AUDIT_CLEANUP_CRON CONFIG_SEED_RELOAD_CRON DEAD_NODES_CRON JOB_CLEANUP_CRON NIGHTLY_BACKUP_CRON -SCHEDULE_ENDS_CRON SCHEDULE_RESYNC_CRON STORED_JOB_CLEANUP_CRON TOKEN_CLEANUP_CRON +SCHEDULE_ENDS_CRON SCHEDULE_RESYNC_CRON STORED_JOB_CLEANUP_CRON TOKEN_CLEANUP_CRON PAUSED_JOBS_CRON JOB_PAUSE_MAX_HOURS AUDIT_CLEANUP_ENABLED CONFIG_SEED_RELOAD_ENABLED JOB_CLEANUP_ENABLED NIGHTLY_BACKUP_ENABLED STORED_JOB_CLEANUP_ENABLED TOKEN_CLEANUP_ENABLED RUNNER_DIAL_SECONDS RUNNER_DISPATCH_SECONDS RUNNER_PRUNE_SECONDS diff --git a/internal/ansible/resume.go b/internal/ansible/resume.go new file mode 100644 index 0000000..8587dc2 --- /dev/null +++ b/internal/ansible/resume.go @@ -0,0 +1,163 @@ +package ansible + +// This file holds a paused playbook and one that starts again from its checkpoints, as the +// controller's own Runner does (server/src/rte/ansible-core.js in the application): the af_events +// plugin holds the playbook before its next task while the pause file is there and says it as a +// paused and a resumed event, which become the job's paused and resumed items ; it and the af_facts +// fact cache write the playbook's checkpoints, which the controller keeps ; a playbook that starts +// again from them begins at its first unfinished task, without its failed hosts, its facts and +// variables restored. + +import ( + "path/filepath" + "strings" + + "github.com/ansibleforms/runner/internal/logger" +) + +// CachePluginsDir is the folder of the af_facts cache plugin, written at the start. +var CachePluginsDir = "" + +// defaultCachePaths are ansible's own cache plugins paths, when nothing names others. +var defaultCachePaths = []string{"~/.ansible/plugins/cache", "/usr/share/ansible/plugins/cache"} + +// Resume is what a playbook that starts again from its checkpoints restores, as the controller +// sends it (sealed in the run message's resume). +type Resume struct { + // StartAt is its first unfinished task ; empty to start it again from its start. + StartAt string `json:"startAt"` + // Failed are the hosts that had failed: left out of its limit, as ansible had left them out. + Failed []string `json:"failed"` + // Facts are each host's facts, the af_facts cache's ; Vars each host's variables (registered, + // set_fact, include_vars), which the af_events plugin sets back. + Facts map[string]any `json:"facts"` + Vars map[string]any `json:"vars"` +} + +// ResumeArgs are the arguments of a playbook that starts again from its checkpoints: at its first +// unfinished task (--start-at-task), without the hosts that had failed (left out of its limit). A +// resume that starts it again from its start keeps the arguments as they are. +// +// Args: +// +// args: its arguments (Args), its playbook last. +// r: what it restores ; nil for a first run. +// +// Returns: +// +// The arguments. +func ResumeArgs(args []string, r *Resume) []string { + if r == nil { + return args + } + out := append([]string(nil), args[:len(args)-1]...) + playbook := args[len(args)-1] + var exclude []string + for _, h := range r.Failed { + if IsLiteralHost(h) { + exclude = append(exclude, "!"+h) + } + } + if len(exclude) > 0 { + at := -1 + for i, a := range out { + if a == "--limit" { + at = i + } + } + // a limit from a file (a re-run on the failed hosts) is kept: its hosts were literal already + if at < 0 { + out = append(out, "--limit", "all,"+strings.Join(exclude, ",")) + } else if !strings.HasPrefix(out[at+1], "@") { + out[at+1] += "," + strings.Join(exclude, ",") + } + } + if r.StartAt != "" { + out = append(out, "--start-at-task", r.StartAt) + } + return append(out, playbook) +} + +// CheckpointEnv sets the environment of a playbook that records checkpoints: the af_facts fact +// cache (its folder first in the cache plugins path, then the ones named before, else ansible's +// own), the file the plugins write its checkpoints to, and, when it starts again from them, the +// file they restore from. +// +// Args: +// +// env: the playbook's environment, changed. +// cacheDir: the cache plugin's folder. +// checkpointFile: the checkpoints file (AF_CHECKPOINT_FILE). +// resumeFile: what a resume restores (AF_RESUME_FILE) ; empty when it starts afresh. +func CheckpointEnv(env map[string]string, cacheDir, checkpointFile, resumeFile string) { + named := defaultCachePaths + if v := env["ANSIBLE_CACHE_PLUGINS"]; v != "" { + named = nil + for _, p := range filepath.SplitList(v) { + if p != "" { + named = append(named, p) + } + } + } + seen := map[string]bool{} + var paths []string + for _, p := range append([]string{cacheDir}, named...) { + if !seen[p] { + seen[p] = true + paths = append(paths, p) + } + } + env["ANSIBLE_CACHE_PLUGINS"] = strings.Join(paths, string(filepath.ListSeparator)) + env["ANSIBLE_CACHE_PLUGIN"] = "af_facts" + env["AF_CHECKPOINT_FILE"] = checkpointFile + if resumeFile != "" { + env["AF_RESUME_FILE"] = resumeFile + } +} + +// EventsAndPauses hands a batch of events on, with the plugin's pause and resume taken out of it: +// they become the job's paused and resumed items, in their place among the others. +// +// Args: +// +// io: the job's IO. +// batch: the events, in order. +func EventsAndPauses(io IO, batch []map[string]any) { + var kept []map[string]any + flush := func() { + if len(kept) > 0 { + io.Events(kept) + } + kept = nil + } + for _, e := range batch { + switch e["type"] { + case "paused": + flush() + data, _ := e["data"].(map[string]any) + after, _ := data["after"].(string) + next, _ := data["next"].(string) + io.Paused(after, next) + case "resumed": + flush() + io.Resumed() + default: + kept = append(kept, e) + } + } + flush() +} + +// resumeNotice says in the log that a playbook starts again from its checkpoints. +// +// Args: +// +// jobID: the job. +// r: what it restores. +func resumeNotice(jobID int64, r *Resume) { + at := "" + if r.StartAt != "" { + at = " at task " + r.StartAt + } + logger.Notice("[Job %d] Resuming from its checkpoints%s", jobID, at) +} diff --git a/internal/ansible/resume_test.go b/internal/ansible/resume_test.go new file mode 100644 index 0000000..d512d33 --- /dev/null +++ b/internal/ansible/resume_test.go @@ -0,0 +1,67 @@ +package ansible + +import ( + "reflect" + "testing" +) + +// TestResumeArgs checks the arguments of a playbook started again: at its first unfinished task, +// its failed hosts left out of its limit (one that is a pattern kept out of it), a limit from a +// file kept ; a first run and a resume from its start unchanged. +func TestResumeArgs(t *testing.T) { + base := []string{"-e", "@x.json", "site.yml"} + if got := ResumeArgs(base, nil); !reflect.DeepEqual(got, base) { + t.Errorf("first run %v", got) + } + if got := ResumeArgs(base, &Resume{}); !reflect.DeepEqual(got, base) { + t.Errorf("from its start %v", got) + } + for _, c := range []struct { + args []string + r Resume + want []string + }{ + {base, Resume{StartAt: "t2", Failed: []string{"web1", "web*", "db1"}}, []string{"-e", "@x.json", "--limit", "all,!web1,!db1", "--start-at-task", "t2", "site.yml"}}, + {[]string{"--limit", "prod", "site.yml"}, Resume{Failed: []string{"web1"}}, []string{"--limit", "prod,!web1", "site.yml"}}, + {[]string{"--limit", "@limit.txt", "site.yml"}, Resume{StartAt: "t3", Failed: []string{"web1"}}, []string{"--limit", "@limit.txt", "--start-at-task", "t3", "site.yml"}}, + } { + if got := ResumeArgs(c.args, &c.r); !reflect.DeepEqual(got, c.want) { + t.Errorf("%v %+v: %v", c.args, c.r, got) + } + } + if base[2] != "site.yml" || len(base) != 3 { + t.Errorf("the arguments given changed: %v", base) + } +} + +// TestCheckpointEnv checks a playbook's fact cache and checkpoint files: its cache folder first, +// the paths named before kept once, else ansible's own ; the resume file only when it resumes. +func TestCheckpointEnv(t *testing.T) { + env := map[string]string{"ANSIBLE_CACHE_PLUGINS": "/mine::/cache"} + CheckpointEnv(env, "/cache", "/ck.jsonl", "") + if env["ANSIBLE_CACHE_PLUGINS"] != "/cache:/mine" || env["ANSIBLE_CACHE_PLUGIN"] != "af_facts" || env["AF_CHECKPOINT_FILE"] != "/ck.jsonl" || env["AF_RESUME_FILE"] != "" { + t.Errorf("env %v", env) + } + env = map[string]string{} + CheckpointEnv(env, "/cache", "/ck.jsonl", "/resume.json") + if env["ANSIBLE_CACHE_PLUGINS"] != "/cache:~/.ansible/plugins/cache:/usr/share/ansible/plugins/cache" || env["AF_RESUME_FILE"] != "/resume.json" { + t.Errorf("env %v", env) + } +} + +// TestEventsAndPauses checks a batch's pause and resume said in their place, the events around +// them sent in order, none sent when nothing is left. +func TestEventsAndPauses(t *testing.T) { + io := &fakeIO{} + EventsAndPauses(io, []map[string]any{ + {"type": "task"}, {"type": "paused", "data": map[string]any{"after": "a", "next": "b"}}, {"type": "resumed"}, {"type": "ok"}, + }) + if len(io.events) != 2 || io.events[0][0]["type"] != "task" || io.events[1][0]["type"] != "ok" || len(io.paused) != 1 || io.paused[0] != "a>b" || io.resumed != 1 { + t.Errorf("events %v paused %v resumed %d", io.events, io.paused, io.resumed) + } + io = &fakeIO{} + EventsAndPauses(io, []map[string]any{{"type": "paused"}}) + if len(io.events) != 0 || io.paused[0] != ">" { + t.Errorf("events %v paused %v", io.events, io.paused) + } +} diff --git a/internal/ansible/run.go b/internal/ansible/run.go index 45be94a..d2ba36a 100644 --- a/internal/ansible/run.go +++ b/internal/ansible/run.go @@ -1,7 +1,8 @@ package ansible -// This file runs the playbook: its files written, ansible-playbook started, its output, events -// and log sent as they come, an abort stopping it, and its end said. +// This file runs the playbook: its files written, ansible-playbook started, its output, events, +// checkpoints and log sent as they come, a pause holding it before its next task, an abort +// stopping it, and its end said. import ( "encoding/json" @@ -96,6 +97,15 @@ type IO interface { // AbortRequested tells whether the job was cancelled ; ResetAbort clears it. AbortRequested() bool ResetAbort() + // PauseFile names the file whose presence holds the playbook before its next task, once it + // starts ; empty once it ended. A pause wanted then makes it at once. + PauseFile(file string) + // Paused says the playbook holds before its next task: after the task it paused after, next + // the one it waits to start ; Resumed says it goes on. + Paused(after, next string) + Resumed() + // Checkpoints sends a batch of the playbook's checkpoints. + Checkpoints([]map[string]any) } // Job is a job to run. @@ -112,6 +122,10 @@ type Job struct { PlaybookDir func(sub string) (string, error) // InventoryRoots are the folders its inventories are in. InventoryRoots []Root + // Checkpoints tells its playbook records checkpoints (the job has a key to seal them with). + Checkpoints bool + // Resume is what it restores when it starts again from its checkpoints ; nil for a first run. + Resume *Resume } // ─── the run ────────────────────────────────────────────────────────────────── @@ -278,11 +292,17 @@ func Run(job Job, sec Secrets, io IO) { } extravarsJSON, _ := json.Marshal(merged) hiddenJSON, _ := json.Marshal(MarkUnsafe(hidden)) + // started again from its checkpoints: at its first unfinished task, without its failed hosts + args := Args(extravars, files) + if job.Checkpoints && job.Resume != nil { + args = ResumeArgs(args, job.Resume) + resumeNotice(job.ID, job.Resume) + } logger.Notice("Running from directory: %s", directory) logger.Notice("Running playbook: %s", text(extravars["__playbook__"])) execute(job, io, run{ directory: directory, - args: Args(extravars, files), + args: args, stdin: vaultPassword, files: files, keep: truthy(extravars["__keepExtravars__"]), @@ -433,6 +453,19 @@ func execute(job Job, io IO, r run, counter int64) { defer os.RemoveAll(eventsDir) eventsFile := filepath.Join(eventsDir, "events.jsonl") _ = writePrivate(eventsFile, nil) + // the pause file, in the same private folder (made only while the job is paused) ; and a + // playbook that records checkpoints: their file, and what a resume restores + pauseFile := filepath.Join(eventsDir, "pause") + checkpointFile, resumeFile := "", "" + if job.Checkpoints { + checkpointFile = filepath.Join(eventsDir, "checkpoints.jsonl") + _ = writePrivate(checkpointFile, nil) + if job.Resume != nil { + resumeFile = filepath.Join(eventsDir, "resume.json") + restored, _ := json.Marshal(map[string]any{"facts": orEmpty(job.Resume.Facts), "vars": orEmpty(job.Resume.Vars)}) + _ = writePrivate(resumeFile, restored) + } + } artifactsDir, err := privateDir("af_artifacts", job.ID) if err != nil { fail(err) @@ -444,6 +477,10 @@ func execute(job Job, io IO, r run, counter int64) { // step 2 : ansible-playbook, in a process group of its own, its streams read env := PlaybookEnv(os.Environ()) CallbackEnv(env, PluginsDir, r.directory, artifactsFile, eventsFile, settings.MaskRegex()) + env["AF_PAUSE_FILE"] = pauseFile + if checkpointFile != "" { + CheckpointEnv(env, CachePluginsDir, checkpointFile, resumeFile) + } for k, v := range r.env { env[k] = v } @@ -477,7 +514,14 @@ func execute(job Job, io IO, r run, counter int64) { pid := cmd.Process.Pid logger.Info("[Job %d] Process started with PID: %d on host: %s", job.ID, pid, settings.NodeID()) io.Started(pid) - tail := events.Start(eventsFile, "", io.Events) + // a pause wanted before it started holds it before its first task ; none once it ended + io.PauseFile(pauseFile) + defer io.PauseFile("") + tail := events.Start(eventsFile, "", func(batch []map[string]any) { EventsAndPauses(io, batch) }) + var checkpoints *events.Tail + if checkpointFile != "" { + checkpoints = events.Start(checkpointFile, "", io.Checkpoints) + } var readers sync.WaitGroup for stream, pipe := range map[string]*os.File{"stdout": outR, "stderr": errR} { readers.Add(1) @@ -541,6 +585,9 @@ func execute(job Job, io IO, r run, counter int64) { outR.Close() errR.Close() batcher.Flush() + if checkpoints != nil { + checkpoints.Stop() + } tail.Stop() removeFiles() artifacts := TakeArtifacts(artifactsFile) @@ -554,6 +601,22 @@ func execute(job Job, io IO, r run, counter int64) { finish(io, state, batcher, artifacts) } +// orEmpty is a map, an empty one for none (an empty object in JSON). +// +// Args: +// +// m: the map. +// +// Returns: +// +// The map. +func orEmpty(m map[string]any) map[string]any { + if m == nil { + return map[string]any{} + } + return m +} + // orNone says a folder, "(none)" when it is empty. // // Args: diff --git a/internal/ansible/run_test.go b/internal/ansible/run_test.go index 14eb1fe..8723465 100644 --- a/internal/ansible/run_test.go +++ b/internal/ansible/run_test.go @@ -36,6 +36,12 @@ type fakeIO struct { ended bool // abortAfterStart sets abort once the playbook started. abortAfterStart bool + // pauseFiles are the pause files named, paused and resumed what was said, checkpoints the + // checkpoints sent + pauseFiles []string + paused []string + resumed int + checkpoints []map[string]any } func (f *fakeIO) Output(r output.Record) { f.mu.Lock(); f.out = append(f.out, r); f.mu.Unlock() } @@ -62,6 +68,22 @@ func (f *fakeIO) End(order int64, stream, status, message string, artifacts map[ } func (f *fakeIO) AbortRequested() bool { f.mu.Lock(); defer f.mu.Unlock(); return f.abort } func (f *fakeIO) ResetAbort() { f.mu.Lock(); f.abort = false; f.resets++; f.mu.Unlock() } +func (f *fakeIO) PauseFile(file string) { + f.mu.Lock() + f.pauseFiles = append(f.pauseFiles, file) + f.mu.Unlock() +} +func (f *fakeIO) Paused(after, next string) { + f.mu.Lock() + f.paused = append(f.paused, after+">"+next) + f.mu.Unlock() +} +func (f *fakeIO) Resumed() { f.mu.Lock(); f.resumed++; f.mu.Unlock() } +func (f *fakeIO) Checkpoints(c []map[string]any) { + f.mu.Lock() + f.checkpoints = append(f.checkpoints, c...) + f.mu.Unlock() +} // output joins the output records. func (f *fakeIO) text() string { @@ -102,6 +124,16 @@ kill) kill -KILL $$ ;; behind) (sleep 3; echo late) & echo "left one behind" ;; badstatus) mkdir -p .joblogs; echo "a: [x" > ".joblogs/job_status_$JOB.yml" ;; agent) echo "agent: $SSH_AUTH_SOCK" ;; +checkpoints) + echo "args: $*" + echo "pause: $AF_PAUSE_FILE cache: $ANSIBLE_CACHE_PLUGIN $ANSIBLE_CACHE_PLUGINS" + echo "resume: $(cat "$AF_RESUME_FILE" 2>/dev/null)" + echo '{"type":"task"}' >> "$AF_EVENTS_FILE" + echo '{"type":"paused","data":{"after":"t1","next":"t2","by":"admin"}}' >> "$AF_EVENTS_FILE" + echo '{"type":"resumed","data":{"by":"bob"}}' >> "$AF_EVENTS_FILE" + echo '{"type":"progress","value":{"next":"t2"}}' >> "$AF_CHECKPOINT_FILE" + sleep 0.1 + ;; esac ` @@ -394,3 +426,46 @@ func TestRunPrivateFolders(t *testing.T) { t.Error("helpers") } } + +// TestRunCheckpoints checks a playbook that records checkpoints and starts again from them: its +// arguments from its first unfinished task, its fact cache and its files in its environment, what +// it restores written, its pause file named while it runs ; its pause and resume said as items, +// out of its events, and its checkpoints sent. +func TestRunCheckpoints(t *testing.T) { + dir := setup(t, "checkpoints") + t.Setenv("ANSIBLE_CACHE_PLUGINS", "") + was := CachePluginsDir + CachePluginsDir = "/cache" + defer func() { CachePluginsDir = was }() + io := &fakeIO{} + j := job(dir, map[string]any{"__playbook__": "site.yml"}) + j.Checkpoints = true + j.Resume = &Resume{StartAt: "t2", Failed: []string{"web2"}, Vars: map[string]any{"web1": map[string]any{"a": 1.0}}} + Run(j, Secrets{}, io) + out := io.text() + for _, want := range []string{ + "args: -e @extravars_42.json -e @he_extravars_42.json --limit all,!web2 --start-at-task t2 site.yml", + "cache: af_facts /cache:~/.ansible/plugins/cache:/usr/share/ansible/plugins/cache", + `resume: {"facts":{},"vars":{"web1":{"a":1}}}`, + } { + if !strings.Contains(out, want) { + t.Errorf("no %q in\n%s", want, out) + } + } + if len(io.pauseFiles) != 2 || !strings.HasSuffix(io.pauseFiles[0], "/pause") || !strings.Contains(out, "pause: "+io.pauseFiles[0]) || io.pauseFiles[1] != "" { + t.Errorf("pause files %v", io.pauseFiles) + } + if len(io.paused) != 1 || io.paused[0] != "t1>t2" || io.resumed != 1 { + t.Errorf("paused %v resumed %d", io.paused, io.resumed) + } + for _, batch := range io.events { + for _, e := range batch { + if e["type"] == "paused" || e["type"] == "resumed" { + t.Errorf("a pause left in the events: %v", e) + } + } + } + if len(io.checkpoints) != 1 || io.checkpoints[0]["type"] != "progress" { + t.Errorf("checkpoints %v", io.checkpoints) + } +} From da04817066eec5a964ca7e5f831aa7a0465cf81b Mon Sep 17 00:00:00 2001 From: Blai Peidro Date: Wed, 2 Dec 2026 23:51:51 +0100 Subject: [PATCH 3/5] feat: a job's container keeps its stdin open for its pauses Docker, Podman and Kubernetes start a job's container with its stdin left open after the job (StdinOnce false), and Send writes a pause or a resume on it through an attach of its own. --- internal/engine/docker/docker.go | 29 +++- .../engine/docker/docker_integration_test.go | 126 ++++++++++++++++++ internal/engine/docker/docker_test.go | 35 ++++- internal/engine/engine.go | 7 +- internal/engine/kubernetes/kubernetes.go | 17 ++- .../kubernetes/kubernetes_integration_test.go | 85 ++++++++++++ internal/engine/kubernetes/kubernetes_test.go | 14 +- 7 files changed, 300 insertions(+), 13 deletions(-) diff --git a/internal/engine/docker/docker.go b/internal/engine/docker/docker.go index 10f3bb0..743cbc8 100644 --- a/internal/engine/docker/docker.go +++ b/internal/engine/docker/docker.go @@ -2,7 +2,8 @@ // speaks) on their unix socket, without their SDK. A job's container is created from RTE_IMAGE // (pulled when the host does not have it), the Runner's own binary copied into it as its // entrypoint, its stdin attached before it starts so the whole job goes in, and labelled with its -// job and its Runner. +// job and its Runner. Its stdin stays open after the job (StdinOnce false): a pause or a resume is +// written on it later through an attach of its own. package docker import ( @@ -24,6 +25,7 @@ import ( "strconv" "strings" "sync" + "time" "github.com/ansibleforms/runner/internal/engine" ) @@ -288,7 +290,7 @@ func (e *Engine) Start(ctx context.Context, spec engine.Spec, stdin io.Reader) ( err = e.callJSON(ctx, http.MethodPost, "/containers/create", map[string]any{ "Image": spec.Image, "Entrypoint": []string{AgentPath}, "Cmd": []string{"job"}, "Env": e.env, "Labels": map[string]string{LabelJob: strconv.FormatInt(spec.JobID, 10), LabelRunner: e.runner}, - "OpenStdin": true, "StdinOnce": true, "AttachStdin": true, "Tty": false, + "OpenStdin": true, "StdinOnce": false, "AttachStdin": true, "Tty": false, "HostConfig": map[string]any{"Binds": e.Binds}, }, &created) if err != nil { @@ -332,10 +334,31 @@ func (e *Engine) begin(ctx context.Context, id string, agent io.Reader, stdin io if _, err := io.Copy(conn, stdin); err != nil { return fmt.Errorf("the job cannot be written to its container: %v", err) } - // its stdin closed: the job read whole + // this attach's end: the job read whole, the container's stdin left open (StdinOnce false) return conn.(*net.UnixConn).CloseWrite() } +// Send writes on a running container's stdin through an attach of its own, which ends once it is +// written: the container's stdin stays open (StdinOnce false). +func (e *Engine) Send(ctx context.Context, id string, data []byte) error { + conn, err := e.attach(ctx, id) + if err != nil { + return err + } + defer conn.Close() + _, err = conn.Write(data) + if err == nil { + // the attach's end: the host has taken what was written once it closes its side + _ = conn.(*net.UnixConn).CloseWrite() + _ = conn.SetReadDeadline(time.Now().Add(sendWait)) + _, _ = io.Copy(io.Discard, conn) + } + return err +} + +// sendWait is how long Send waits for the host to close its side of an attach. +var sendWait = 5 * time.Second + // attach attaches a container's stdin: the HTTP connection the host takes over as its stream. // // Args: diff --git a/internal/engine/docker/docker_integration_test.go b/internal/engine/docker/docker_integration_test.go index 8ae7295..3985415 100644 --- a/internal/engine/docker/docker_integration_test.go +++ b/internal/engine/docker/docker_integration_test.go @@ -13,6 +13,7 @@ import ( "github.com/ansibleforms/runner/internal/engine" "github.com/ansibleforms/runner/internal/jobstream" + "github.com/ansibleforms/runner/internal/socket" ) // TestRealPlaybook runs a real playbook in a container of a real host: the Runner's binary @@ -92,3 +93,128 @@ func TestRealPlaybook(t *testing.T) { t.Errorf("a job stopped: %s\n%s", status, out) } } + +// TestRealPause pauses a real playbook and resumes it, as the Runner does on a pause message: the +// pause written on the container's stdin after its job, the playbook held before its next task +// (a paused item, "Paused by" in its output), then let go on by a resume ("Resumed by"), its later +// tasks run and its end a success. Its checkpoints come sealed with the job's key, and open with +// the Runner's token. A second run started again from checkpoints begins at its task two, with +// the variable they restore. +func TestRealPause(t *testing.T) { + binary, image := os.Getenv("AF_RUNNER_BINARY"), os.Getenv("RTE_IMAGE") + if binary == "" || image == "" { + t.Fatal("set AF_RUNNER_BINARY and RTE_IMAGE") + } + sock := os.Getenv("RTE_ENGINE_SOCKET") + if sock == "" { + sock = "/var/run/docker.sock" + } + e := New(sock, "rte-integration", binary, []string{"LOG_LEVEL=info"}) + e.StopSeconds = 10 + dir := t.TempDir() + _ = os.WriteFile(filepath.Join(dir, "site.yml"), []byte(`- hosts: localhost + gather_facts: false + tasks: + - name: one + ansible.builtin.set_fact: + kept: "from task one" + - name: two + ansible.builtin.debug: + msg: "task two sees {{ kept }}" +`), 0o644) + const id, token = 4, "token-0123456789abcdef" + key, _ := socket.JobKey(token, id) + var in bytes.Buffer + h := jobstream.Header{ID: id, Playbook: "playbook", Key: key, Extravars: map[string]any{"__playbook__": "site.yml"}} + if err := jobstream.WriteJob(&in, h, map[string]string{"playbook": dir}); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) + defer cancel() + cid, err := e.Start(ctx, engine.Spec{JobID: id, Image: image}, &in) + if err != nil { + t.Fatal(err) + } + defer e.Remove(context.Background(), cid) + // paused at once: held before its first task + if err := e.Send(ctx, cid, jobstream.ControlLine(true, "admin")); err != nil { + t.Fatal(err) + } + logs, err := e.Logs(ctx, cid) + if err != nil { + t.Fatal(err) + } + defer logs.Close() + var out strings.Builder + var kinds []string + status, opened := "", 0 + rd := &jobstream.Reader{} + _ = rd.Read(logs, func(item map[string]any) { + kind, _ := item["kind"].(string) + switch kind { + case "output": + out.WriteString(item["record"].(map[string]any)["output"].(string)) + case "paused": + // held: let go on a moment later + go func() { time.Sleep(2 * time.Second); _ = e.Send(ctx, cid, jobstream.ControlLine(false, "bob")) }() + case "checkpoints": + var entries []map[string]any + if err := socket.OpenJobSecrets(asMap(item["sealed"]), token, id, &entries); err != nil { + t.Errorf("checkpoints: %v", err) + } + opened += len(entries) + case "end": + status, _ = item["status"].(string) + out.WriteString(item["message"].(string)) + } + if kind != "output" && kind != "events" && kind != "checkpoints" { + kinds = append(kinds, kind) + } + }) + text := out.String() + if status != "success" || !strings.Contains(text, "Paused by admin") || !strings.Contains(text, "Resumed by bob") || !strings.Contains(text, "task two sees from task one") { + t.Errorf("a job paused and resumed: %s\n%s", status, text) + } + if strings.Join(kinds, ",") != "started,paused,resumed,exited,end" || opened == 0 { + t.Errorf("items %v, %d checkpoints", kinds, opened) + } + + // started again from its checkpoints: at task two, with the variable task one had set + var again bytes.Buffer + h = jobstream.Header{ID: id + 1, Playbook: "playbook", Key: key, Extravars: map[string]any{"__playbook__": "site.yml"}, + Resume: []byte(`{"startAt":"two","failed":[],"facts":{},"vars":{"localhost":{"kept":"restored"}}}`)} + if err := jobstream.WriteJob(&again, h, map[string]string{"playbook": dir}); err != nil { + t.Fatal(err) + } + cid, err = e.Start(ctx, engine.Spec{JobID: id + 1, Image: image}, &again) + if err != nil { + t.Fatal(err) + } + defer e.Remove(context.Background(), cid) + logs2, err := e.Logs(ctx, cid) + if err != nil { + t.Fatal(err) + } + defer logs2.Close() + out.Reset() + status = "" + rd = &jobstream.Reader{} + _ = rd.Read(logs2, func(item map[string]any) { + switch item["kind"] { + case "output": + out.WriteString(item["record"].(map[string]any)["output"].(string)) + case "end": + status, _ = item["status"].(string) + } + }) + text = out.String() + if status != "success" || !strings.Contains(text, "task two sees restored") || strings.Contains(text, "TASK [one]") { + t.Errorf("a job resumed from its checkpoints: %s\n%s", status, text) + } +} + +// asMap reads a JSON object. +func asMap(v any) map[string]any { + m, _ := v.(map[string]any) + return m +} diff --git a/internal/engine/docker/docker_test.go b/internal/engine/docker/docker_test.go index f39e589..77820e3 100644 --- a/internal/engine/docker/docker_test.go +++ b/internal/engine/docker/docker_test.go @@ -170,7 +170,7 @@ func (h *host) ServeHTTP(w http.ResponseWriter, r *http.Request) { buf.Flush() data, _ := io.ReadAll(buf) h.mu.Lock() - b.stdin = data + b.stdin = append(b.stdin, data...) h.mu.Unlock() }() case len(parts) == 2 && parts[1] == "start": @@ -235,7 +235,7 @@ func TestStart(t *testing.T) { defer h.mu.Unlock() c := b.create if c["Image"] != "ghcr.io/x/rte:7" || c["Entrypoint"].([]any)[0] != AgentPath || c["Cmd"].([]any)[0] != "job" || c["Env"].([]any)[0] != "LOG_LEVEL=debug" || - c["Labels"].(map[string]any)[LabelJob] != "7" || c["Labels"].(map[string]any)[LabelRunner] != "rte-test-8000" || c["OpenStdin"] != true || c["StdinOnce"] != true || + c["Labels"].(map[string]any)[LabelJob] != "7" || c["Labels"].(map[string]any)[LabelRunner] != "rte-test-8000" || c["OpenStdin"] != true || c["StdinOnce"] != false || c["HostConfig"].(map[string]any)["Binds"].([]any)[0] != "/srv/roles:/etc/ansible/roles:ro" { t.Errorf("created %v", c) } @@ -250,6 +250,37 @@ func TestStart(t *testing.T) { } } +// TestSend checks a control written on a running container's stdin, after its job, through an +// attach of its own ; an attach refused said. +func TestSend(t *testing.T) { + h := newHost(t) + e := engineOn(t, h) + ctx := context.Background() + id, err := e.Start(ctx, engine.Spec{JobID: 7, Image: "rte:7"}, strings.NewReader("the job")) + if err != nil { + t.Fatal(err) + } + stdin := func() string { h.mu.Lock(); defer h.mu.Unlock(); return string(h.boxes[id].stdin) } + for i := 0; i < 200 && stdin() != "the job"; i++ { + time.Sleep(5 * time.Millisecond) + } + if err := e.Send(ctx, id, []byte("pause\n")); err != nil { + t.Fatal(err) + } + for i := 0; i < 200 && stdin() != "the jobpause\n"; i++ { + time.Sleep(5 * time.Millisecond) + } + if got := stdin(); got != "the jobpause\n" { + t.Errorf("stdin %q", got) + } + h.mu.Lock() + h.fail["POST /containers/"+id+"/attach"] = answer(409, "container is not running") + h.mu.Unlock() + if err := e.Send(ctx, id, []byte("x")); err == nil || !strings.Contains(err.Error(), "not running") { + t.Errorf("refused: %v", err) + } +} + // TestStartPrivate checks an image of a private registry: pulled with the job's registry login, // sent as the engine's X-Registry-Auth (JSON, base64url). func TestStartPrivate(t *testing.T) { diff --git a/internal/engine/engine.go b/internal/engine/engine.go index f47ab6b..16ac9c1 100644 --- a/internal/engine/engine.go +++ b/internal/engine/engine.go @@ -47,9 +47,12 @@ type Found struct { // Engine starts and follows the jobs' containers. type Engine interface { - // Start starts a job's container, the job written on its stdin (closed after it), and the - // Runner's binary its entrypoint (ansibleforms-rte-runner job). + // Start starts a job's container, the job written on its stdin, and the Runner's binary its + // entrypoint (ansibleforms-rte-runner job). Its stdin stays open for what Send writes. Start(ctx context.Context, spec Spec, stdin io.Reader) (string, error) + // Send writes on a running container's stdin, after its job: a control (a pause, a resume). + // A Runner that restarted sends on a container an earlier start made. + Send(ctx context.Context, id string, data []byte) error // Logs reads its stdout from its start, followed to its end. Logs(ctx context.Context, id string) (io.ReadCloser, error) // State says how it is. diff --git a/internal/engine/kubernetes/kubernetes.go b/internal/engine/kubernetes/kubernetes.go index f81ce8b..07731ac 100644 --- a/internal/engine/kubernetes/kubernetes.go +++ b/internal/engine/kubernetes/kubernetes.go @@ -1,7 +1,8 @@ // Package kubernetes is the engine of Kubernetes: its API, without client-go. A job's container // is a pod of its own in the Runner's namespace: an init container of the Runner's image copies // its binary into an emptyDir, and the job's container (RTE_IMAGE) runs it, its stdin attached -// through the API once it runs. A stop lowers the pod's activeDeadlineSeconds, so the kubelet +// through the API once it runs. Its stdin stays open after the job (stdinOnce false): a pause or a +// resume is written on it later through an attach of its own. A stop lowers the pod's activeDeadlineSeconds, so the kubelet // sends a SIGTERM and keeps the pod and its logs until the Runner removes it. // // With RTE_JOB_MOUNTS, each job's pod also mounts the volumes of the Runner's own pod those paths @@ -340,7 +341,7 @@ func (e *Engine) pod(spec engine.Spec, sh *shared) map[string]any { }}, "containers": []map[string]any{{ "name": "job", "image": spec.Image, "command": []string{AgentPath, "job"}, "env": env, - "stdin": true, "stdinOnce": true, "tty": false, + "stdin": true, "stdinOnce": false, "tty": false, "volumeMounts": mounts, "securityContext": containerSecurity, }}, @@ -667,9 +668,15 @@ func (e *Engine) Start(ctx context.Context, spec engine.Spec, stdin io.Reader) ( return name, nil } -// attach writes the job on a pod's stdin, through the API's attach websocket: each message its -// channel first (0 for stdin) ; the stdin closed after it (a v5 close, else the socket's end, -// which ends a stdinOnce stdin). +// Send writes on a running pod's stdin through an attach of its own: the pod's stdin stays open +// after it (stdinOnce false). +func (e *Engine) Send(ctx context.Context, name string, data []byte) error { + return e.attach(ctx, name, bytes.NewReader(data)) +} + +// attach writes on a pod's stdin, through the API's attach websocket: each message its channel +// first (0 for stdin) ; this attach's stdin closed after it (a v5 close, else the socket's end), +// the pod's own left open (stdinOnce false). // // Args: // diff --git a/internal/engine/kubernetes/kubernetes_integration_test.go b/internal/engine/kubernetes/kubernetes_integration_test.go index 9199fc7..ca32bdb 100644 --- a/internal/engine/kubernetes/kubernetes_integration_test.go +++ b/internal/engine/kubernetes/kubernetes_integration_test.go @@ -13,6 +13,7 @@ import ( "github.com/ansibleforms/runner/internal/engine" "github.com/ansibleforms/runner/internal/jobstream" + "github.com/ansibleforms/runner/internal/socket" ) // realEngine is an engine on the real cluster, as the Runner's service account (AF_K8S_API, @@ -181,3 +182,87 @@ func TestRealMounts(t *testing.T) { t.Errorf("a job with the runner's volumes: %s\n%s", status, out) } } + +// TestRealPause pauses a real playbook in a real pod and resumes it, as the Runner does on a pause +// message: the pause written on the pod's stdin after its job through an attach of its own, the +// playbook held before its next task (a paused item, "Paused by" in its output), then let go on +// by a resume ("Resumed by"), its later tasks run and its end a success. Its checkpoints come +// sealed with the job's key, and open with the Runner's token. +func TestRealPause(t *testing.T) { + e := realEngine(t, "") + dir := t.TempDir() + _ = os.WriteFile(filepath.Join(dir, "site.yml"), []byte(`- hosts: localhost + gather_facts: false + tasks: + - name: one + ansible.builtin.set_fact: + kept: "from task one" + - name: two + ansible.builtin.debug: + msg: "task two sees {{ kept }}" +`), 0o644) + const id, token = 5, "token-0123456789abcdef" + key, _ := socket.JobKey(token, id) + var in bytes.Buffer + h := jobstream.Header{ID: id, Playbook: "playbook", Key: key, Extravars: map[string]any{"__playbook__": "site.yml"}} + if err := jobstream.WriteJob(&in, h, map[string]string{"playbook": dir}); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) + defer cancel() + name, err := e.Start(ctx, engine.Spec{JobID: id, Image: os.Getenv("RTE_IMAGE")}, &in) + if err != nil { + t.Fatal(err) + } + defer e.Remove(context.Background(), name) + // paused at once: held before its first task + if err := e.Send(ctx, name, jobstream.ControlLine(true, "admin")); err != nil { + t.Fatal(err) + } + var out strings.Builder + var kinds []string + status, opened, resumed := "", 0, false + rd := &jobstream.Reader{} + // the logs read again until the job's end, as the Runner reads them + for status == "" && ctx.Err() == nil { + if logs, err := e.Logs(ctx, name); err == nil { + _ = rd.Read(logs, func(item map[string]any) { + kind, _ := item["kind"].(string) + switch kind { + case "output": + out.WriteString(item["record"].(map[string]any)["output"].(string)) + case "paused": + // held: let go on a moment later + if !resumed { + resumed = true + go func() { time.Sleep(2 * time.Second); _ = e.Send(ctx, name, jobstream.ControlLine(false, "bob")) }() + } + case "checkpoints": + var entries []map[string]any + sealed, _ := item["sealed"].(map[string]any) + if err := socket.OpenJobSecrets(sealed, token, id, &entries); err != nil { + t.Errorf("checkpoints: %v", err) + } + opened += len(entries) + case "end": + status, _ = item["status"].(string) + out.WriteString(item["message"].(string)) + } + if kind != "output" && kind != "events" && kind != "checkpoints" { + kinds = append(kinds, kind) + } + }) + logs.Close() + } + if status == "" { + time.Sleep(time.Second) + } + } + text := out.String() + if status != "success" || !strings.Contains(text, "Paused by admin") || !strings.Contains(text, "Resumed by bob") || !strings.Contains(text, "task two sees from task one") { + t.Errorf("a job paused and resumed: %s\n%s", status, text) + } + if strings.Join(kinds, ",") != "started,paused,resumed,exited,end" || opened == 0 { + t.Errorf("items %v, %d checkpoints", kinds, opened) + } +} diff --git a/internal/engine/kubernetes/kubernetes_test.go b/internal/engine/kubernetes/kubernetes_test.go index 6bc80a3..cdf4e2b 100644 --- a/internal/engine/kubernetes/kubernetes_test.go +++ b/internal/engine/kubernetes/kubernetes_test.go @@ -277,7 +277,7 @@ func TestStart(t *testing.T) { raw, _ := json.Marshal(p.spec) for _, want := range []string{`"restartPolicy":"Never"`, `"terminationGracePeriodSeconds":60`, `"automountServiceAccountToken":false`, `"imagePullSecrets":[{"name":"regcred"}]`, `"command":["cp","/usr/local/bin/ansibleforms-rte-runner","/.ansibleforms/ansibleforms-rte-runner"]`, - `"image":"my/runner:1"`, `"image":"rte:1"`, `"command":["/.ansibleforms/ansibleforms-rte-runner","job"]`, `"stdin":true`, `"stdinOnce":true`, + `"image":"my/runner:1"`, `"image":"rte:1"`, `"command":["/.ansibleforms/ansibleforms-rte-runner","job"]`, `"stdin":true`, `"stdinOnce":false`, `{"name":"AF_JOB_LOGS","value":"off"}`, `"runAsNonRoot":true`, `"runAsUser":1000`, `"seccompProfile":{"type":"RuntimeDefault"}`, `"allowPrivilegeEscalation":false`, `"capabilities":{"drop":["ALL"]}`, `{"name":"LOG_LEVEL","value":"debug"}`, `{"name":"ODD","value":""}`, `"readOnly":true`, `"volumes":[{"emptyDir":{},"name":"agent"}]`} { @@ -295,6 +295,18 @@ func TestStart(t *testing.T) { t.Errorf("labels %v", p.labels) } a.mu.Unlock() + // a control after the job, through an attach of its own + if err := e.Send(context.Background(), name, []byte("pause\n")); err != nil { + t.Fatal(err) + } + if protocol == "v4.channel.k8s.io" { + time.Sleep(50 * time.Millisecond) + } + a.mu.Lock() + if !strings.HasSuffix(string(p.stdin), job+"pause\n") { + t.Errorf("%s: no control after the job: %q", protocol, string(p.stdin)[len(p.stdin)-20:]) + } + a.mu.Unlock() } } From dfc7987c6f17571801e06657ad1a20b46819d204 Mon Sep 17 00:00:00 2001 From: Blai Peidro Date: Wed, 2 Dec 2026 23:51:51 +0100 Subject: [PATCH 4/5] feat: the runner pauses and resumes playbook jobs It handles the controller's pause message, says the jobs it holds paused in its hello, keeps them on disk across a restart, and opens a run message's resume for a playbook that starts again from its checkpoints. --- .github/workflows/ci.yml | 10 +- CHANGELOG.md | 1 + CONTRIBUTING.md | 4 +- README.md | 3 +- internal/runner/runner.go | 170 +++++++++++++++++++++++++++- internal/runner/runner_test.go | 200 ++++++++++++++++++++++++++++++++- internal/socket/protocol.go | 13 ++- 7 files changed, 383 insertions(+), 18 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 63e16c8..5f6a026 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -102,7 +102,8 @@ jobs: # A real playbook in a real job's container, on Docker and on Podman: the Runner's static # binary copied into the RTE image, the job streamed in, its lines read back as the container's - # logs ; one job ends successfully, one stopped ends as aborted (the integration tag). + # logs ; one job ends successfully, one stopped ends as aborted, one is paused before its next + # task and resumed through its stdin (the integration tag). playbook: name: Playbook (${{ matrix.engine }}) runs-on: ubuntu-latest @@ -133,12 +134,13 @@ jobs: run: | set -euo pipefail CGO_ENABLED=0 go build -trimpath -o "$AF_RUNNER_BINARY" . - go test -tags integration -count=1 -v -run TestRealPlaybook ./internal/engine/docker + go test -tags integration -count=1 -v -run 'TestRealPlaybook|TestRealPause' ./internal/engine/docker # A real playbook in a real job's pod on a kind cluster, as the Runner's service account with # the Role of deploy/kubernetes-rbac.yaml: the Runner's image built and loaded, its binary # copied into the pod by the init container, the job written on the pod's stdin through the - # API ; one job ends successfully, one stopped ends as aborted, and one reads the volumes of a + # API ; one job ends successfully, one stopped ends as aborted, one is paused before its next + # task and resumed through attaches of their own, and one reads the volumes of a # pod that stands for the Runner's (RTE_JOB_MOUNTS): a file on its ReadWriteOnce claim and its # secret's key (the integration tag). kubernetes: @@ -230,7 +232,7 @@ jobs: AF_K8S_CA: ${{ runner.temp }}/ca.crt AF_RUNNER_IMAGE: af-ci/ansibleforms-rte-runner:ci RTE_IMAGE: ghcr.io/ansibleforms/ansibleforms-rte-core:7 - run: go test -tags integration -count=1 -v -run 'TestRealPlaybook|TestRealMounts' ./internal/engine/kubernetes + run: go test -tags integration -count=1 -v -run 'TestRealPlaybook|TestRealPause|TestRealMounts' ./internal/engine/kubernetes - name: The pods, when it failed if: failure() diff --git a/CHANGELOG.md b/CHANGELOG.md index 2101e74..16f7b92 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ The changes made to the Runner between two releases wait under Unreleased and go ### Added - **A repository's folder:** a repository's own checkout is read from the folder the controller names as its root +- **Pause and resume:** a playbook job pauses before its next task, and resumes there or from its checkpoints ## 7.9.0 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8a2ad40..e2d82be 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -22,12 +22,12 @@ The Runner is one small Go program; each package under `internal/` holds one par | `main.go` | the start: its settings, its engine, its probes, its dial; the `job`, `health` and `version` commands | | `internal/runner/` | the Runner's peer: the jobs the controller hands over, each one's container followed, its items | | `internal/engine/` | the engines of the jobs' containers: `docker` (Docker and Podman) and `kubernetes` | -| `internal/jobstream/` | what goes between the Runner and a job's container: the job on stdin, numbered lines out | +| `internal/jobstream/` | what goes between the Runner and a job's container: the job and its pauses on stdin, numbered lines out | | `internal/agent/` | the `job` command, inside a job's container: reads the job, runs it, writes its lines | | `internal/ansible/` | a playbook's run, as the controller's own Runner runs it: its arguments, environment, end | | `internal/files/` | the cache of the playbooks and inventories the controller sends | | `internal/mask/`, `internal/output/`, `internal/events/` | a job's secrets masked, its output batched, its events read | -| `internal/plugins/` | the callback plugins every run loads | +| `internal/plugins/` | the callback and cache plugins every run loads | | `internal/sshkey/` | a credential's SSH key, with its passphrase, for a run | | `internal/settings/` | its environment variables | | `internal/socket/` | the controller's socket, as the controller speaks it: protocol, session, spool, dial, listen | diff --git a/README.md b/README.md index 2c3877a..a8154fe 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ The controller decides what runs and where; the Runner runs it, each job apart, - **Docker, Podman or Kubernetes:** through their API, a pod per job on Kubernetes - **Runs ansible-core:** every playbook, with its inventory, credentials, limit and extra vars - **Live output:** every line reaches the controller's job as it runs, its secrets masked +- **Pause and resume:** a playbook holds before its next task, or starts again from its checkpoints - **Survives a restart:** a restarted Runner finds its jobs' containers and reads on where it stopped - **Survives a drop:** what the controller did not store yet is sent again after a reconnect - **One small binary:** no Node.js, no Python: the jobs' image brings ansible-core @@ -31,7 +32,7 @@ The controller decides what runs and where; the Runner runs it, each job apart, The controller hands each job to a Runner, its files and credentials sealed for it, and the Runner runs it in a container of its own. It writes the job on the container's stdin and reads its output from the container's logs: nothing is shared on the network or a disk, -and aborting a job just stops its container. +and aborting a job just stops its container. A pause or a resume goes on the same stdin, on Docker, Podman and Kubernetes alike. A Runner joins its controller in one of two modes (`RTE_MODE`): diff --git a/internal/runner/runner.go b/internal/runner/runner.go index ab94d3b..2faadcf 100644 --- a/internal/runner/runner.go +++ b/internal/runner/runner.go @@ -68,6 +68,11 @@ type job struct { // abort tells it was cancelled ; container is its container once started. abort bool container string + // paused tells its pause is wanted: its playbook held before its next task ; by is who asked + // the pause or, once it is let go on, who resumed it. ctl orders what goes to its container. + paused bool + by string + ctl sync.Mutex } // Runner is the Runner's state: its socket to the controller, the jobs it holds, and the settings @@ -464,6 +469,8 @@ func (r *Runner) Attach(s *socket.Session) { "capacity": r.capacity(), "running": r.running(), "spooled": r.spooled(), + // the jobs it holds paused: the controller resumes the ones it no longer wants paused + "paused": r.pausedJobs(), "settings": now, "env": r.env, // a job may name the image it runs in, and the one it runs in when it names none @@ -490,6 +497,8 @@ func (r *Runner) Handle(s *socket.Session, msg socket.Message) { r.onRun(s, msg) case "cancel": r.onCancel(msg) + case "pause": + r.onPause(msg) case "file": if r.cache != nil { r.cache.Deliver(msg) @@ -529,7 +538,7 @@ func (r *Runner) onWelcome(msg socket.Message) { // Args: // // s: the socket it came on. -// msg: { jobId, contract, sealed, job, paths, files }. +// msg: { jobId, contract, sealed, job, paths, files, image, resume }. func (r *Runner) onRun(s *socket.Session, msg socket.Message) { id := asInt(msg["jobId"]) refuse := func(why string, busy bool) { @@ -552,11 +561,19 @@ func (r *Runner) onRun(s *socket.Session, msg socket.Message) { refuse(err.Error(), false) return } + // a playbook that starts again from its checkpoints: what it restores, sealed as its secrets + var resume json.RawMessage + if msg["resume"] != nil { + if err := socket.OpenJobSecrets(msg["resume"], settings.Token(), id, &resume); err != nil { + refuse(err.Error(), false) + return + } + } if image, _ := msg["image"].(string); image != "" && !settings.ImageAllowed(image) { refuse("the image "+image+" is not one this runner runs its jobs in (RTE_IMAGES_ALLOWED)", false) return } - r.start(s, id, msg, sec) + r.start(s, id, msg, sec, resume) } } @@ -569,13 +586,14 @@ func (r *Runner) onRun(s *socket.Session, msg socket.Message) { // id: the job. // msg: the run message. // sec: its secrets. -func (r *Runner) start(s *socket.Session, id int64, msg socket.Message, sec json.RawMessage) { +// resume: what it restores when it starts again from its checkpoints ; none for a first run. +func (r *Runner) start(s *socket.Session, id int64, msg socket.Message, sec json.RawMessage, resume json.RawMessage) { j := r.jobs[id] if j == nil { j = &job{spool: socket.OpenSpool(settings.SpoolDir(), id)} r.jobs[id] = j } - j.running, j.abort, j.container = true, false, "" + j.running, j.abort, j.container, j.paused, j.by = true, false, "", false, "" if until, ok := r.cancels[id]; ok { delete(r.cancels, id) if time.Now().Before(until) { @@ -598,7 +616,9 @@ func (r *Runner) start(s *socket.Session, id int64, msg socket.Message, sec json if auth != nil && auth.ServerAddress == "" { auth.ServerAddress = registryOf(image) } - h := jobstream.Header{ID: id, Extravars: extravarsOf(spec["extravars"]), LastOrder: asInt(spec["lastOrder"]), Secrets: sec} + // its own key, which seals its checkpoints in its container (never the Runner's token) + key, _ := socket.JobKey(settings.Token(), id) + h := jobstream.Header{ID: id, Extravars: extravarsOf(spec["extravars"]), LastOrder: asInt(spec["lastOrder"]), Secrets: sec, Key: key, Resume: resume} transfer := r.effective()["files"] == "transfer" && (given["playbooks"] != nil || len(asList(given["inventories"])) > 0) cache, eng := r.cache, r.engine box := engine.Spec{JobID: id, Image: image, Auth: auth} @@ -668,6 +688,11 @@ func (r *Runner) finish(j *job, id int64) { r.mu.Lock() defer r.mu.Unlock() j.running = false + if j.paused { + // its pause goes with it + j.paused = false + r.savePauses() + } if j.spool.Done() { j.spool.Remove() delete(r.jobs, id) @@ -770,6 +795,10 @@ func (r *Runner) run(j *job, h jobstream.Header, paths, given map[string]any, tr r.mu.Lock() j.container = id abort := j.abort + // a pause that came while its container started + if j.paused { + r.sendPause(j, h.ID) + } r.mu.Unlock() if abort { go func() { _ = eng.Stop(ctx, id) }() @@ -1067,6 +1096,129 @@ func (r *Runner) onCancel(msg socket.Message) { } } +// ─── a pause ────────────────────────────────────────────────────────────────── + +// onPause holds a job's playbook before its next task, or lets it go on, as the controller's own +// Runner does: the job's pause wanted or no longer, kept on disk for a Runner that restarts, and +// written on its container's stdin (its agent makes or removes the playbook's pause file). A job +// it does not run is left. The caller holds the lock. +// +// Args: +// +// msg: { jobId, paused, by }. +func (r *Runner) onPause(msg socket.Message) { + id := asInt(msg["jobId"]) + j := r.jobs[id] + if j == nil || !j.running { + return + } + paused, _ := msg["paused"].(bool) + by, _ := msg["by"].(string) + if len(by) > 250 { + by = by[:250] + } + if paused == j.paused { + return + } + j.paused = paused + if by != "" || !paused { + j.by = by + } + r.savePauses() + if paused { + logger.Notice("Runner: job %d pauses before its next task", id) + } else { + logger.Notice("Runner: job %d goes on", id) + } + r.sendPause(j, id) +} + +// sendPause writes a job's pause as it is wanted now on its container's stdin, in the +// background: one write at a time per job, each the latest wanted, so the last one is right +// whatever order they ran in. Nothing goes before its container started (run sends it then). The +// caller holds the lock. +// +// Args: +// +// j: the job. +// id: its id. +func (r *Runner) sendPause(j *job, id int64) { + eng := r.engine + if j.container == "" || eng == nil { + return + } + go func() { + j.ctl.Lock() + defer j.ctl.Unlock() + r.mu.Lock() + cid, line := j.container, jobstream.ControlLine(j.paused, j.by) + r.mu.Unlock() + if err := eng.Send(context.Background(), cid, line); err != nil { + logger.Warning("Runner: the pause of job %d did not reach its container: %v", id, err) + } + }() +} + +// pausedJobs lists the jobs it holds paused, in order. The caller holds the lock. +// +// Returns: +// +// Their ids. +func (r *Runner) pausedJobs() []int64 { + ids := []int64{} + for _, id := range r.running() { + if r.jobs[id].paused { + ids = append(ids, id) + } + } + return ids +} + +// pausesFile is where the jobs' pauses are kept, beside their spools. +// +// Returns: +// +// The file. +func pausesFile() string { return filepath.Join(settings.SpoolDir(), "pauses.json") } + +// savePauses keeps the jobs' pauses on disk: who paused each job held paused, by its id. A Runner +// that restarts holds them again, says them in its hello, and the controller resumes the ones it +// no longer wants paused. The caller holds the lock. +func (r *Runner) savePauses() { + kept := map[string]string{} + for _, id := range r.pausedJobs() { + kept[strconv.FormatInt(id, 10)] = r.jobs[id].by + } + data, _ := json.Marshal(kept) + tmp := pausesFile() + ".tmp" + if err := os.WriteFile(tmp, data, 0o600); err != nil { + logger.Warning("Runner: the jobs' pauses cannot be kept: %v", err) + return + } + _ = os.Rename(tmp, pausesFile()) +} + +// loadPauses reads the jobs' pauses an earlier start kept. +// +// Returns: +// +// Who paused each job, by its id ; none when none were kept. +func loadPauses() map[int64]string { + out := map[int64]string{} + data, err := os.ReadFile(pausesFile()) + if err != nil { + return out + } + var kept map[string]string + _ = json.Unmarshal(data, &kept) + for k, by := range kept { + if id, err := strconv.ParseInt(k, 10, 64); err == nil && id > 0 { + out[id] = by + } + } + return out +} + // toNumberText says a JSON value that should be a number. // // Args: @@ -1145,6 +1297,7 @@ func (r *Runner) ResumeSpools() error { return err } found := r.containers() + pauses := loadPauses() r.mu.Lock() defer r.mu.Unlock() for _, e := range entries { @@ -1163,6 +1316,11 @@ func (r *Runner) ResumeSpools() error { delete(found, id) j.running, j.container = true, cid logger.Notice("Runner: job %d's container is still there: following it again", id) + // its pause held again, and written again on its container (one that did not reach it) + if by, ok := pauses[id]; ok { + j.paused, j.by = true, by + r.sendPause(j, id) + } last, order, eng := sp.Seq, sp.LastOrder(), r.engine go func() { r.follow(j, id, eng, cid, last, order) @@ -1172,6 +1330,8 @@ func (r *Runner) ResumeSpools() error { } sp.Append(socket.Item{"kind": "abandon", "message": "the runner restarted while the playbook ran"}) } + // the pauses of the jobs it no longer runs: forgotten + r.savePauses() // the containers of jobs it holds no more: removed for id, cid := range found { logger.Notice("Runner: removing the container of job %d, a job it no longer holds", id) diff --git a/internal/runner/runner_test.go b/internal/runner/runner_test.go index e53dd55..cedd241 100644 --- a/internal/runner/runner_test.go +++ b/internal/runner/runner_test.go @@ -485,6 +485,9 @@ type fakeEngine struct { script func(c *container, w *jobstream.Writer) // specs are the containers asked for, in order specs []engine.Spec + // sent is what was written on each container's stdin after its job ; sendErr fails it + sent map[string][]string + sendErr error } // newEngine makes a fake engine. @@ -527,6 +530,31 @@ func (e *fakeEngine) Start(_ context.Context, spec engine.Spec, stdin io.Reader) return id, nil } +func (e *fakeEngine) Send(_ context.Context, id string, data []byte) error { + e.mu.Lock() + defer e.mu.Unlock() + if e.sent == nil { + e.sent = map[string][]string{} + } + e.sent[id] = append(e.sent[id], string(data)) + return e.sendErr +} + +// sentTo waits until a container got a number of controls, and gives them. +func (e *fakeEngine) sentTo(t *testing.T, id string, n int) []string { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for { + e.mu.Lock() + got := append([]string(nil), e.sent[id]...) + e.mu.Unlock() + if len(got) >= n || time.Now().After(deadline) { + return got + } + time.Sleep(2 * time.Millisecond) + } +} + func (e *fakeEngine) Logs(_ context.Context, id string) (io.ReadCloser, error) { e.mu.Lock() defer e.mu.Unlock() @@ -941,7 +969,7 @@ func TestCancel(t *testing.T) { } r.cancels[5000] = time.Now().Add(-time.Second) r.mu.Lock() - r.start(&socket.Session{}, 5000, socket.Message{}, nil) + r.start(&socket.Session{}, 5000, socket.Message{}, nil, nil) stale := r.jobs[5000].abort r.mu.Unlock() if stale { @@ -1170,3 +1198,173 @@ func TestRegistryLogin(t *testing.T) { } } } + +// ─── pause and resume ───────────────────────────────────────────────────────── + +// slowStart holds a container's start until it is released. +type slowStart struct { + *fakeEngine + release chan struct{} +} + +func (s *slowStart) Start(ctx context.Context, spec engine.Spec, stdin io.Reader) (string, error) { + <-s.release + return s.fakeEngine.Start(ctx, spec, stdin) +} + +// TestPause checks a job's pause and resume as the controller sends them: a pause that came while +// its container started written on it once it runs, a resume written after it, who asked each said +// ; the job held paused said in the hello, kept on disk, and forgotten once it ended ; its key and +// what a resume restores in its header. +func TestPause(t *testing.T) { + env(t) + t.Setenv("RTE_FILES", "local") + t.Setenv("ANSIBLE_PATH", t.TempDir()) + done := make(chan struct{}) + eng := newEngine(func(c *container, w *jobstream.Writer) { + w.Write(map[string]any{"kind": "started", "pid": 9}) + <-done + w.Write(map[string]any{"kind": "end", "status": "success"}) + }) + slow := &slowStart{fakeEngine: eng, release: make(chan struct{})} + r, c, conn, _ := connected(t) + r.SetEngine(slow) + send(t, conn, socket.Message{"t": "welcome"}) + send(t, conn, socket.Message{"t": "run", "jobId": 71, "contract": socket.SocketContract, "sealed": sealed(t, 71, map[string]any{}), + "resume": sealed(t, 71, map[string]any{"startAt": "t2"})}) + c.next(t, "claimed") + send(t, conn, socket.Message{"t": "pause", "jobId": 71, "paused": true, "by": "admin"}) + for func() bool { r.mu.Lock(); defer r.mu.Unlock(); return !r.jobs[71].paused }() { + time.Sleep(2 * time.Millisecond) + } + close(slow.release) + if got := eng.sentTo(t, "c1", 1); len(got) != 1 || got[0] != string(jobstream.ControlLine(true, "admin")) { + t.Errorf("pause %q", got) + } + eng.mu.Lock() + h := eng.containers["c1"].header + eng.mu.Unlock() + key, _ := socket.JobKey("token-0123456789abcdef", 71) + if !bytes.Equal(h.Key, key) || string(h.Resume) != `{"startAt":"t2"}` { + t.Errorf("header key %x resume %s", h.Key, h.Resume) + } + if data, _ := os.ReadFile(pausesFile()); string(data) != `{"71":"admin"}` { + t.Errorf("kept %s", data) + } + r.mu.Lock() + sess := r.session + r.mu.Unlock() + r.Attach(sess) + if p := c.next(t, "hello")["paused"].([]any); len(p) != 1 || p[0] != 71.0 { + t.Errorf("hello paused %v", p) + } + send(t, conn, socket.Message{"t": "welcome"}) + send(t, conn, socket.Message{"t": "pause", "jobId": 71, "paused": true, "by": "again"}) + send(t, conn, socket.Message{"t": "pause", "jobId": 71, "paused": false, "by": "bob"}) + if got := eng.sentTo(t, "c1", 2); len(got) != 2 || got[1] != string(jobstream.ControlLine(false, "bob")) { + t.Errorf("resume %q", got) + } + send(t, conn, socket.Message{"t": "pause", "jobId": 71, "paused": true, "by": strings.Repeat("x", 300)}) + for func() bool { r.mu.Lock(); defer r.mu.Unlock(); return !r.jobs[71].paused }() { + time.Sleep(2 * time.Millisecond) + } + if r.jobs[71].by != strings.Repeat("x", 250) { + t.Errorf("by %d long", len(r.jobs[71].by)) + } + close(done) + for func() bool { r.mu.Lock(); defer r.mu.Unlock(); return r.jobs[71].running }() { + time.Sleep(2 * time.Millisecond) + } + if data, _ := os.ReadFile(pausesFile()); string(data) != `{}` { + t.Errorf("kept once ended %s", data) + } +} + +// TestPauseEdges checks the pauses left: a job it does not hold or no longer runs ; a pause that does not reach its container, pauses that +// cannot be kept on disk, and what an earlier start kept that is no job's. +func TestPauseEdges(t *testing.T) { + env(t) + r := New() + eng := newEngine(nil) + eng.sendErr = errors.New("its stdin is closed") + r.SetEngine(eng) + r.jobs[2] = &job{spool: socket.OpenSpool(os.Getenv("RTE_SPOOL_PATH"), 2), running: true, container: "k2", paused: true, by: "admin"} + r.jobs[3] = &job{spool: socket.OpenSpool(os.Getenv("RTE_SPOOL_PATH"), 3)} + r.mu.Lock() + r.onPause(socket.Message{"jobId": 3.0, "paused": true}) + r.onPause(socket.Message{"jobId": 4.0, "paused": true}) + r.onPause(socket.Message{"jobId": 2.0, "paused": false}) + r.onPause(socket.Message{"jobId": 2.0, "paused": true}) + paused, by := r.jobs[2].paused, r.jobs[2].by + r.mu.Unlock() + if r.jobs[3].paused || !paused || by != "" { + t.Errorf("paused %v by %q", paused, by) + } + if got := eng.sentTo(t, "k2", 2); len(got) != 2 { + t.Errorf("sent %q", got) + } + t.Setenv("RTE_SPOOL_PATH", filepath.Join(t.TempDir(), "missing")) + r.mu.Lock() + r.savePauses() + r.mu.Unlock() + if len(loadPauses()) != 0 { + t.Error("pauses where none were kept") + } + dir := t.TempDir() + t.Setenv("RTE_SPOOL_PATH", dir) + _ = os.WriteFile(pausesFile(), []byte(`{"x":"a","0":"b","5":"c"}`), 0o600) + if got := loadPauses(); len(got) != 1 || got[5] != "c" { + t.Errorf("loaded %v", got) + } +} + +// TestResumeContainersPaused checks a restart with a job held paused: held again, said in its +// hello, its pause written again on its container ; a pause kept for a job no longer there +// forgotten. +func TestResumeContainersPaused(t *testing.T) { + env(t) + dir := os.Getenv("RTE_SPOOL_PATH") + wasRetry := retryLogs + retryLogs = 5 * time.Millisecond + defer func() { retryLogs = wasRetry }() + socket.OpenSpool(dir, 81).Append(socket.Item{"kind": "started"}) + _ = os.WriteFile(filepath.Join(dir, "pauses.json"), []byte(`{"81":"admin","82":"gone"}`), 0o600) + eng := newEngine(nil) + logs := &lockedBuffer{} + jobstream.NewWriter(logs).Write(map[string]any{"kind": "started"}) + eng.containers["k81"] = &container{logs: logs, state: engine.State{Running: true}, stopped: make(chan struct{})} + eng.listed = []engine.Found{{ID: "k81", JobID: 81}} + r := New() + r.SetEngine(eng) + if err := r.ResumeSpools(); err != nil { + t.Fatal(err) + } + if got := eng.sentTo(t, "k81", 1); len(got) != 1 || got[0] != string(jobstream.ControlLine(true, "admin")) { + t.Errorf("sent %q", got) + } + r.mu.Lock() + ids := r.pausedJobs() + r.mu.Unlock() + if len(ids) != 1 || ids[0] != 81 { + t.Errorf("paused %v", ids) + } + if data, _ := os.ReadFile(pausesFile()); string(data) != `{"81":"admin"}` { + t.Errorf("kept %s", data) + } + eng.set(func() { eng.containers["k81"].state = engine.State{} }) + for func() bool { r.mu.Lock(); defer r.mu.Unlock(); return r.jobs[81].running }() { + time.Sleep(2 * time.Millisecond) + } +} + +// TestRunResumeRefused checks a resume that does not open for this Runner: the job refused. +func TestRunResumeRefused(t *testing.T) { + env(t) + _, c, conn, _ := connected(t) + send(t, conn, socket.Message{"t": "welcome"}) + send(t, conn, socket.Message{"t": "run", "jobId": 72, "contract": socket.SocketContract, "sealed": sealed(t, 72, map[string]any{}), + "resume": sealed(t, 73, map[string]any{"startAt": "t2"})}) + if m := c.next(t, "refused"); !strings.Contains(m["error"].(string), "do not open") { + t.Errorf("refused %v", m) + } +} diff --git a/internal/socket/protocol.go b/internal/socket/protocol.go index 9d4cf8c..0845afa 100644 --- a/internal/socket/protocol.go +++ b/internal/socket/protocol.go @@ -10,19 +10,22 @@ // text frames, { t: , ... }. // // RTE -> controller -// hello who it is: id, version, contract, capacity, ansible, the jobs it runs and the -// ones it still has items for, its settings +// hello who it is: id, version, contract, capacity, ansible, the jobs it runs, the +// ones it still has items for and the ones it holds paused, its settings // health every 20 s, and after a settings message: the jobs it runs, its free slots // claimed it took a job ; refused : it did not (busy, ...) -// item one numbered item of a job: output, events, log, started, exited, end, -// abandon ; kept on its disk until the controller acks it, resent after a reconnect +// item one numbered item of a job: output, events, log, started, exited, paused, +// resumed, checkpoints, end, abandon ; kept on its disk until the controller acks +// it, resent after a reconnect // fetch the files of a job, by their hash // // controller -> RTE // welcome the hello accepted // settings what the controller's Runner page sets over the Runner's environment -// run a job: its secrets sealed for it, its paths or its files' hashes +// run a job: its secrets sealed for it, its paths or its files' hashes ; a playbook's +// checkpoints too when it starts again from them (resume) // cancel stop a job +// pause hold a job before its next task, or let it go on (paused: true / false, by) // ack the items of a job stored, up to a number // file a part of the files fetched package socket From be9b79229309aa70927320635f643fc2c880605b Mon Sep 17 00:00:00 2001 From: Blai Peidro Date: Thu, 3 Dec 2026 00:01:12 +0100 Subject: [PATCH 5/5] fix: a pause reaches a job on Docker and Podman by an exec Podman closes a container's stdin once its first attach ends, whatever StdinOnce says. On Docker and Podman a pause or a resume is now handed to the job by an exec of the Runner's control command, which writes it on the job's control pipe; the containers keep StdinOnce true. Kubernetes keeps writing it on the pod's stdin. --- .github/workflows/ci.yml | 2 +- CONTRIBUTING.md | 2 +- README.md | 2 +- internal/agent/agent.go | 95 ++++++++++++++++++- internal/agent/agent_test.go | 68 +++++++++++++ internal/engine/docker/docker.go | 49 ++++++---- .../engine/docker/docker_integration_test.go | 10 +- internal/engine/docker/docker_test.go | 66 +++++++++---- internal/engine/engine.go | 7 +- main.go | 3 + main_test.go | 7 ++ 11 files changed, 259 insertions(+), 52 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5f6a026..a81e0d2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -103,7 +103,7 @@ jobs: # A real playbook in a real job's container, on Docker and on Podman: the Runner's static # binary copied into the RTE image, the job streamed in, its lines read back as the container's # logs ; one job ends successfully, one stopped ends as aborted, one is paused before its next - # task and resumed through its stdin (the integration tag). + # task and resumed by the Runner's control command, run by an exec (the integration tag). playbook: name: Playbook (${{ matrix.engine }}) runs-on: ubuntu-latest diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e2d82be..660b6ac 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -19,7 +19,7 @@ The Runner is one small Go program; each package under `internal/` holds one par | Path | Holds | |---|---| -| `main.go` | the start: its settings, its engine, its probes, its dial; the `job`, `health` and `version` commands | +| `main.go` | the start: its settings, its engine, its probes, its dial; the `job`, `control`, `health` and `version` commands | | `internal/runner/` | the Runner's peer: the jobs the controller hands over, each one's container followed, its items | | `internal/engine/` | the engines of the jobs' containers: `docker` (Docker and Podman) and `kubernetes` | | `internal/jobstream/` | what goes between the Runner and a job's container: the job and its pauses on stdin, numbered lines out | diff --git a/README.md b/README.md index a8154fe..d275081 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ The controller decides what runs and where; the Runner runs it, each job apart, The controller hands each job to a Runner, its files and credentials sealed for it, and the Runner runs it in a container of its own. It writes the job on the container's stdin and reads its output from the container's logs: nothing is shared on the network or a disk, -and aborting a job just stops its container. A pause or a resume goes on the same stdin, on Docker, Podman and Kubernetes alike. +and aborting a job just stops its container. A pause or a resume reaches the job on its stdin on Kubernetes, and through an exec of the Runner's control command on Docker and Podman. A Runner joins its controller in one of two modes (`RTE_MODE`): diff --git a/internal/agent/agent.go b/internal/agent/agent.go index 1b0eb22..970e51c 100644 --- a/internal/agent/agent.go +++ b/internal/agent/agent.go @@ -3,13 +3,15 @@ // would run it (internal/ansible), and writes its items, their secrets masked, as numbered lines // on its stdout, which the Runner reads as the container's logs. A SIGTERM (the container // stopped: the job aborted) stops the playbook's process group, the job then ended as aborted. -// What comes on its stdin after the job are its pauses and resumes: a pause makes the playbook's -// pause file, which holds it before its next task, a resume removes it. Its checkpoints go out -// sealed with the job's own key, as the controller's own Runner seals them. +// Its pauses and resumes come after the job on its stdin (Kubernetes), or through its control +// pipe, which the control command writes (Docker and Podman run it in the container): a pause +// makes the playbook's pause file, which holds it before its next task, a resume removes it. Its +// checkpoints go out sealed with the job's own key, as the controller's own Runner seals them. package agent import ( "encoding/json" + "errors" "fmt" "io" "os" @@ -17,6 +19,7 @@ import ( "path/filepath" "sync" "syscall" + "time" "github.com/ansibleforms/runner/internal/ansible" "github.com/ansibleforms/runner/internal/jobstream" @@ -35,8 +38,89 @@ var ( kill = syscall.Kill pluginsWrite = plugins.Write cacheWrite = plugins.WriteCache + // controlWait is how long the control command waits for the job to read its control pipe. + controlWait = 30 * time.Second ) +// controlPipe is the job's control pipe: a named pipe the job reads its pauses and resumes from, +// one JSON line each, at a path the control command knows. +// +// Returns: +// +// The path. +func controlPipe() string { return filepath.Join(tempDir(), "ansibleforms-control") } + +// openControls makes the job's control pipe and reads it in the background: each pause or resume +// handed to the job. Opened for reading and writing, it never ends when a writer goes. +// +// Args: +// +// l: the job's IO. +// +// Returns: +// +// What closes it ; nothing when it cannot be made (a pause then reaches the job on its stdin +// only). +func openControls(l *lines) func() { + pipe := controlPipe() + if err := syscall.Mkfifo(pipe, 0o600); err != nil && !errors.Is(err, os.ErrExist) { + logger.Warning("The job's control pipe cannot be made: %v", err) + return func() {} + } + f, err := os.OpenFile(pipe, os.O_RDWR, 0) + if err != nil { + logger.Warning("The job's control pipe cannot be read: %v", err) + return func() {} + } + go jobstream.ReadControls(f, func(c jobstream.Control) { l.setPaused(c.Paused, c.By) }) + return func() { + _ = f.Close() + _ = os.Remove(pipe) + } +} + +// Control is the control command (ansibleforms-rte-runner control ), which the Runner runs +// in a job's container: it writes a pause or a resume on the job's control pipe, made when the job +// did not make it yet, waiting up to controlWait for the job to read it. +// +// Args: +// +// args: the control's line (jobstream.ControlLine), without its end. +// out: where it says why it failed. +// +// Returns: +// +// The exit code: 0 once written, 1 when it could not be. +func Control(args []string, out io.Writer) int { + if len(args) != 1 { + fmt.Fprintln(out, "the control command takes one control line") + return 1 + } + pipe := controlPipe() + if err := syscall.Mkfifo(pipe, 0o600); err != nil && !errors.Is(err, os.ErrExist) { + fmt.Fprintf(out, "the job's control pipe cannot be made: %v\n", err) + return 1 + } + // without a reader a write-only open fails at once (ENXIO): tried again until the job reads it + deadline := time.Now().Add(controlWait) + for { + f, err := os.OpenFile(pipe, os.O_WRONLY|syscall.O_NONBLOCK, 0) + if err == nil { + // a line shorter than a pipe's atomic write: written whole or not at all + _, err = f.Write([]byte(args[0] + "\n")) + f.Close() + } + if err == nil { + return 0 + } + if time.Now().After(deadline) { + fmt.Fprintf(out, "the job does not read its control pipe: %v\n", err) + return 1 + } + time.Sleep(100 * time.Millisecond) + } +} + // lines is a job's IO: each item a numbered line, its secrets masked ; an abort its flag ; a // pause its file. type lines struct { @@ -225,6 +309,8 @@ func (l *lines) stop() { func Run(stdin io.Reader, stdout io.Writer, signals <-chan os.Signal) int { w := jobstream.NewWriter(stdout) io := &lines{w: w, mask: &mask.Job{}} + // its pauses and resumes, as they come, from its start (Docker and Podman) + defer openControls(io)() fail := func(order int64, err error) int { io.End(order, "stderr", "failed", "[ERROR]: "+err.Error(), map[string]any{}) return 1 @@ -271,7 +357,8 @@ func Run(stdin io.Reader, stdout io.Writer, signals <-chan os.Signal) int { ansible.CachePluginsDir = cacheDir } - // step 3 : an abort while it runs ; a pause or a resume, as they come after the job + // step 3 : an abort while it runs ; a pause or a resume, as they come after the job on its stdin + // (Kubernetes) go jobstream.ReadControls(br, func(c jobstream.Control) { io.setPaused(c.Paused, c.By) }) done := make(chan struct{}) defer close(done) diff --git a/internal/agent/agent_test.go b/internal/agent/agent_test.go index 401e177..777c75f 100644 --- a/internal/agent/agent_test.go +++ b/internal/agent/agent_test.go @@ -375,3 +375,71 @@ func TestRunResumeFails(t *testing.T) { t.Errorf("no fact cache: %s", out.String()) } } + +// TestControlPipe checks the pauses that come through the job's control pipe, as the control +// command writes them (Docker and Podman): read while the job runs, the pipe removed once it +// ended ; a control command that comes before the job made the pipe waits for it. +func TestControlPipe(t *testing.T) { + wasTemp, wasRun := tempDir, runPlaybook + defer func() { tempDir, runPlaybook = wasTemp, wasRun }() + dir := t.TempDir() + tempDir = func() string { return dir } + file := filepath.Join(t.TempDir(), "pause") + early := make(chan int) + go func() { + var b bytes.Buffer + early <- Control([]string{string(bytes.TrimSpace(jobstream.ControlLine(true, "admin")))}, &b) + }() + runPlaybook = func(j ansible.Job, sec ansible.Secrets, jio ansible.IO) { + if code := <-early; code != 0 { + t.Errorf("an early control: %d", code) + } + jio.PauseFile(file) + waitFor(t, func() bool { data, _ := os.ReadFile(file); return string(data) == `{"by":"admin"}` }) + var b bytes.Buffer + if code := Control([]string{string(bytes.TrimSpace(jobstream.ControlLine(false, "bob")))}, &b); code != 0 { + t.Errorf("control %d: %s", code, b.String()) + } + waitFor(t, func() bool { _, err := os.Stat(file); return os.IsNotExist(err) }) + jio.End(1, "stdout", "success", "", map[string]any{}) + } + var out bytes.Buffer + time.Sleep(50 * time.Millisecond) + if code := Run(stream(t, jobstream.Header{Playbook: "p"}, nil), &out, make(chan os.Signal)); code != 0 { + t.Errorf("exit %d", code) + } + if _, err := os.Stat(controlPipe()); !os.IsNotExist(err) { + t.Error("the control pipe is left") + } +} + +// TestControlFails checks a control command given no line, one whose pipe cannot be made, one no +// job reads ; and a job whose control pipe cannot be made or opened, which runs without it. +func TestControlFails(t *testing.T) { + wasTemp, wasWait := tempDir, controlWait + defer func() { tempDir, controlWait = wasTemp, wasWait }() + var b bytes.Buffer + if Control(nil, &b) != 1 || !strings.Contains(b.String(), "one control line") { + t.Errorf("no line: %s", b.String()) + } + tempDir = func() string { return filepath.Join(t.TempDir(), "missing") } + b.Reset() + if Control([]string{"x"}, &b) != 1 || !strings.Contains(b.String(), "cannot be made") { + t.Errorf("no folder: %s", b.String()) + } + if close := openControls(&lines{}); close == nil { + t.Error("no closer") + } else { + close() + } + dir := t.TempDir() + tempDir = func() string { return dir } + controlWait = 50 * time.Millisecond + b.Reset() + if Control([]string{"x"}, &b) != 1 || !strings.Contains(b.String(), "does not read its control pipe") { + t.Errorf("no reader: %s", b.String()) + } + _ = os.Remove(controlPipe()) + _ = os.WriteFile(controlPipe(), nil, 0o000) + openControls(&lines{})() +} diff --git a/internal/engine/docker/docker.go b/internal/engine/docker/docker.go index 743cbc8..d7c4b3d 100644 --- a/internal/engine/docker/docker.go +++ b/internal/engine/docker/docker.go @@ -2,8 +2,9 @@ // speaks) on their unix socket, without their SDK. A job's container is created from RTE_IMAGE // (pulled when the host does not have it), the Runner's own binary copied into it as its // entrypoint, its stdin attached before it starts so the whole job goes in, and labelled with its -// job and its Runner. Its stdin stays open after the job (StdinOnce false): a pause or a resume is -// written on it later through an attach of its own. +// job and its Runner. A pause or a resume is handed to its job later by an exec of that binary's +// control command: Podman closes a container's stdin once its first attach ends, whatever +// StdinOnce says, so nothing more can be written there. package docker import ( @@ -25,7 +26,6 @@ import ( "strconv" "strings" "sync" - "time" "github.com/ansibleforms/runner/internal/engine" ) @@ -290,7 +290,7 @@ func (e *Engine) Start(ctx context.Context, spec engine.Spec, stdin io.Reader) ( err = e.callJSON(ctx, http.MethodPost, "/containers/create", map[string]any{ "Image": spec.Image, "Entrypoint": []string{AgentPath}, "Cmd": []string{"job"}, "Env": e.env, "Labels": map[string]string{LabelJob: strconv.FormatInt(spec.JobID, 10), LabelRunner: e.runner}, - "OpenStdin": true, "StdinOnce": false, "AttachStdin": true, "Tty": false, + "OpenStdin": true, "StdinOnce": true, "AttachStdin": true, "Tty": false, "HostConfig": map[string]any{"Binds": e.Binds}, }, &created) if err != nil { @@ -334,31 +334,42 @@ func (e *Engine) begin(ctx context.Context, id string, agent io.Reader, stdin io if _, err := io.Copy(conn, stdin); err != nil { return fmt.Errorf("the job cannot be written to its container: %v", err) } - // this attach's end: the job read whole, the container's stdin left open (StdinOnce false) + // its stdin closed: the job read whole return conn.(*net.UnixConn).CloseWrite() } -// Send writes on a running container's stdin through an attach of its own, which ends once it is -// written: the container's stdin stays open (StdinOnce false). +// Send hands a running container's job a control line (a pause, a resume): the Runner's binary's +// control command, run in the container by an exec, writes it on the job's control pipe. What +// the command said is the error when it fails. func (e *Engine) Send(ctx context.Context, id string, data []byte) error { - conn, err := e.attach(ctx, id) + var created struct { + ID string `json:"Id"` + } + err := e.callJSON(ctx, http.MethodPost, "/containers/"+id+"/exec", map[string]any{ + "Cmd": []string{AgentPath, "control", strings.TrimSpace(string(data))}, "AttachStdout": true, "AttachStderr": true, + }, &created) if err != nil { return err } - defer conn.Close() - _, err = conn.Write(data) - if err == nil { - // the attach's end: the host has taken what was written once it closes its side - _ = conn.(*net.UnixConn).CloseWrite() - _ = conn.SetReadDeadline(time.Now().Add(sendWait)) - _, _ = io.Copy(io.Discard, conn) + // its output, read to its end: the command has ended then + res, err := e.call(ctx, http.MethodPost, "/exec/"+created.ID+"/start", strings.NewReader(`{"Detach":false,"Tty":false}`), "application/json") + if err != nil { + return err } - return err + said, _ := io.ReadAll(&demux{body: res.Body}) + res.Body.Close() + var info struct { + ExitCode int + } + if err := e.callJSON(ctx, http.MethodGet, "/exec/"+created.ID+"/json", nil, &info); err != nil { + return err + } + if info.ExitCode != 0 { + return fmt.Errorf("its control command ended with status %d: %s", info.ExitCode, strings.TrimSpace(string(said))) + } + return nil } -// sendWait is how long Send waits for the host to close its side of an attach. -var sendWait = 5 * time.Second - // attach attaches a container's stdin: the HTTP connection the host takes over as its stream. // // Args: diff --git a/internal/engine/docker/docker_integration_test.go b/internal/engine/docker/docker_integration_test.go index 3985415..eae699d 100644 --- a/internal/engine/docker/docker_integration_test.go +++ b/internal/engine/docker/docker_integration_test.go @@ -95,11 +95,11 @@ func TestRealPlaybook(t *testing.T) { } // TestRealPause pauses a real playbook and resumes it, as the Runner does on a pause message: the -// pause written on the container's stdin after its job, the playbook held before its next task -// (a paused item, "Paused by" in its output), then let go on by a resume ("Resumed by"), its later -// tasks run and its end a success. Its checkpoints come sealed with the job's key, and open with -// the Runner's token. A second run started again from checkpoints begins at its task two, with -// the variable they restore. +// pause handed to the job by an exec of the Runner's control command, the playbook held before +// its next task (a paused item, "Paused by" in its output), then let go on by a resume ("Resumed +// by"), its later tasks run and its end a success. Its checkpoints come sealed with the job's key, +// and open with the Runner's token. A second run started again from checkpoints begins at its +// task two, with the variable they restore. func TestRealPause(t *testing.T) { binary, image := os.Getenv("AF_RUNNER_BINARY"), os.Getenv("RTE_IMAGE") if binary == "" || image == "" { diff --git a/internal/engine/docker/docker_test.go b/internal/engine/docker/docker_test.go index 77820e3..53a00c0 100644 --- a/internal/engine/docker/docker_test.go +++ b/internal/engine/docker/docker_test.go @@ -34,6 +34,8 @@ type box struct { stopped bool // mounts are what its inspection lists (the Runner's own container) mounts []map[string]string + // controls are the control lines its execs were given + controls []string } // host is a fake Docker host on a unix socket: images, containers, and what each call did. @@ -51,6 +53,8 @@ type host struct { vanish bool // auths are the registry logins the pulls came with, by image auths map[string]string + // execs are the commands of the execs made, by their id + execs map[string][]any } // newHost starts a fake host. @@ -143,6 +147,18 @@ func (h *host) ServeHTTP(w http.ResponseWriter, r *http.Request) { _ = json.NewDecoder(r.Body).Decode(&bx.create) h.boxes[id] = bx fmt.Fprintf(w, `{"Id":%q}`, id) + case strings.HasPrefix(path, "/exec/"): + id, what, _ := strings.Cut(strings.TrimPrefix(path, "/exec/"), "/") + cmd := h.execs[id] + failed := strings.Contains(cmd[2].(string), "fail") + switch { + case what == "start" && r.Method == "POST": + if failed { + w.Write(frame(1, "the job does not read its control pipe\n")) + } + case what == "json": + fmt.Fprintf(w, `{"ExitCode":%d}`, map[bool]int{true: 1}[failed]) + } case b == nil: answer(404, "No such container")(w) case len(parts) == 2 && parts[1] == "archive": @@ -170,9 +186,20 @@ func (h *host) ServeHTTP(w http.ResponseWriter, r *http.Request) { buf.Flush() data, _ := io.ReadAll(buf) h.mu.Lock() - b.stdin = append(b.stdin, data...) + b.stdin = data h.mu.Unlock() }() + case len(parts) == 2 && parts[1] == "exec": + var exec map[string]any + _ = json.NewDecoder(r.Body).Decode(&exec) + h.n++ + id := fmt.Sprintf("e%d", h.n) + if h.execs == nil { + h.execs = map[string][]any{} + } + h.execs[id] = exec["Cmd"].([]any) + b.controls = append(b.controls, exec["Cmd"].([]any)[2].(string)) + fmt.Fprintf(w, `{"Id":%q}`, id) case len(parts) == 2 && parts[1] == "start": b.running = true w.WriteHeader(204) @@ -235,7 +262,7 @@ func TestStart(t *testing.T) { defer h.mu.Unlock() c := b.create if c["Image"] != "ghcr.io/x/rte:7" || c["Entrypoint"].([]any)[0] != AgentPath || c["Cmd"].([]any)[0] != "job" || c["Env"].([]any)[0] != "LOG_LEVEL=debug" || - c["Labels"].(map[string]any)[LabelJob] != "7" || c["Labels"].(map[string]any)[LabelRunner] != "rte-test-8000" || c["OpenStdin"] != true || c["StdinOnce"] != false || + c["Labels"].(map[string]any)[LabelJob] != "7" || c["Labels"].(map[string]any)[LabelRunner] != "rte-test-8000" || c["OpenStdin"] != true || c["StdinOnce"] != true || c["HostConfig"].(map[string]any)["Binds"].([]any)[0] != "/srv/roles:/etc/ansible/roles:ro" { t.Errorf("created %v", c) } @@ -250,34 +277,37 @@ func TestStart(t *testing.T) { } } -// TestSend checks a control written on a running container's stdin, after its job, through an -// attach of its own ; an attach refused said. +// TestSend checks a control handed to a running container's job: the Runner's control command +// run by an exec, its line as its argument ; a command that fails said with what it said, an +// exec that cannot be made or started, or inspected, said. func TestSend(t *testing.T) { h := newHost(t) e := engineOn(t, h) ctx := context.Background() + h.images["rte:7"] = true id, err := e.Start(ctx, engine.Spec{JobID: 7, Image: "rte:7"}, strings.NewReader("the job")) if err != nil { t.Fatal(err) } - stdin := func() string { h.mu.Lock(); defer h.mu.Unlock(); return string(h.boxes[id].stdin) } - for i := 0; i < 200 && stdin() != "the job"; i++ { - time.Sleep(5 * time.Millisecond) - } - if err := e.Send(ctx, id, []byte("pause\n")); err != nil { + if err := e.Send(ctx, id, []byte(`{"t":"pause"}`+"\n")); err != nil { t.Fatal(err) } - for i := 0; i < 200 && stdin() != "the jobpause\n"; i++ { - time.Sleep(5 * time.Millisecond) - } - if got := stdin(); got != "the jobpause\n" { - t.Errorf("stdin %q", got) - } h.mu.Lock() - h.fail["POST /containers/"+id+"/attach"] = answer(409, "container is not running") + cmd := h.execs["e2"] h.mu.Unlock() - if err := e.Send(ctx, id, []byte("x")); err == nil || !strings.Contains(err.Error(), "not running") { - t.Errorf("refused: %v", err) + if len(cmd) != 3 || cmd[0] != AgentPath || cmd[1] != "control" || cmd[2] != `{"t":"pause"}` { + t.Errorf("exec %v", cmd) + } + if err := e.Send(ctx, id, []byte("fail")); err == nil || err.Error() != "its control command ended with status 1: the job does not read its control pipe" { + t.Errorf("a control that failed: %v", err) + } + for _, call := range []string{"POST /containers/" + id + "/exec", "POST /exec/", "GET /exec/"} { + h.mu.Lock() + h.fail = map[string]func(http.ResponseWriter){call: answer(500, "engine down")} + h.mu.Unlock() + if err := e.Send(ctx, id, []byte("x")); err == nil || !strings.Contains(err.Error(), "engine down") { + t.Errorf("%s refused: %v", call, err) + } } } diff --git a/internal/engine/engine.go b/internal/engine/engine.go index 16ac9c1..8b2f88a 100644 --- a/internal/engine/engine.go +++ b/internal/engine/engine.go @@ -48,10 +48,11 @@ type Found struct { // Engine starts and follows the jobs' containers. type Engine interface { // Start starts a job's container, the job written on its stdin, and the Runner's binary its - // entrypoint (ansibleforms-rte-runner job). Its stdin stays open for what Send writes. + // entrypoint (ansibleforms-rte-runner job). Start(ctx context.Context, spec Spec, stdin io.Reader) (string, error) - // Send writes on a running container's stdin, after its job: a control (a pause, a resume). - // A Runner that restarted sends on a container an earlier start made. + // Send hands a running container's job a control line (jobstream.ControlLine: a pause, a + // resume): on its stdin after the job (Kubernetes), or by an exec of the Runner's control + // command (Docker, Podman). A Runner that restarted sends to a container an earlier start made. Send(ctx context.Context, id string, data []byte) error // Logs reads its stdout from its start, followed to its end. Logs(ctx context.Context, id string) (io.ReadCloser, error) diff --git a/main.go b/main.go index c32d439..d7a571e 100644 --- a/main.go +++ b/main.go @@ -43,6 +43,7 @@ Commands: run meet the controller and run the jobs it hands over (default) health exit 0 when its probes answer: the image's HEALTHCHECK job run the job its stdin carries, inside the job's container (the Runner starts it) + control hand a running job a pause or a resume, inside its container (the Runner runs it) version print its version Its settings are environment variables: RTE_MODE, RTE_TOKEN, RTE_JOIN_TOKEN, RTE_NAME, RTE_URL, @@ -95,6 +96,8 @@ func command(args []string) int { return health() case "job": return agent.Main() + case "control": + return agent.Control(flags.Args()[1:], os.Stdout) case "version": fmt.Println(version.App) return 0 diff --git a/main_test.go b/main_test.go index 3fcc9a6..c17364b 100644 --- a/main_test.go +++ b/main_test.go @@ -95,6 +95,13 @@ func TestJob(t *testing.T) { } } +// TestControl checks control hands a job its control line: without one it says so. +func TestControl(t *testing.T) { + if code, out, _ := output(t, "control"); code != 1 || !strings.Contains(out, "one control line") { + t.Errorf("exit %d, printed %q", code, out) + } +} + // TestUsage checks --help and a command or flag it does not know. func TestUsage(t *testing.T) { if code, _, errs := output(t, "--help"); code != 0 || !strings.Contains(errs, "health") {