@yunuseon/kayra 0.13.1 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,10 +2,13 @@
2
2
  roles_path = roles/
3
3
  host_key_checking = False
4
4
  retry_files_enabled = False
5
- callbacks_enabled = ansible.builtin.default
6
- [callback_default]
7
- result_format = yaml
5
+ # kayra's output (callback_plugins/kayra.py); ANSIBLE_STDOUT_CALLBACK=default brings back Ansible's.
6
+ stdout_callback = kayra
7
+ callback_plugins = callback_plugins/
8
+ callback_result_format = yaml
8
9
  nocows = True
10
+ # Discovery stays; its warning on every playbook goes.
11
+ interpreter_python = auto_silent
9
12
 
10
13
  [ssh_connection]
11
14
  pipelining = True
@@ -0,0 +1,299 @@
1
+ # kayra's Ansible output, under the step kayra shows for the playbook: what
2
+ # changed (with its diff when asked), what failed and why, what a debug task
3
+ # says, and a recap. ok and skipped tasks are counted, not listed. On a
4
+ # terminal the task at work is one line, redrawn with a spinner and its time.
5
+ #
6
+ # ANSIBLE_STDOUT_CALLBACK=default brings back Ansible's own output.
7
+ from __future__ import annotations
8
+
9
+ DOCUMENTATION = """
10
+ name: kayra
11
+ type: stdout
12
+ short_description: what changed, what failed, and the task at work
13
+ description:
14
+ - Shows what changed, with its diff under --diff; what failed, with its message and output;
15
+ what a debug task says; retries; and a recap. ok and skipped tasks are only counted.
16
+ - On a terminal the running task is one line, redrawn with a spinner and its running time.
17
+ extends_documentation_fragment:
18
+ - result_format_callback
19
+ """
20
+
21
+ import os
22
+ import re
23
+ import shutil
24
+ import sys
25
+ import threading
26
+ import time
27
+
28
+ from ansible import constants as C
29
+ from ansible.playbook.task_include import TaskInclude
30
+ from ansible.plugins.callback import CallbackBase
31
+ from ansible.utils import color
32
+
33
+ INDENT = " "
34
+ DETAIL = INDENT + " "
35
+ # kayra caps its own lines here; the times line up with its frames.
36
+ COLUMNS = 80
37
+ TAIL = 20
38
+ FRAMES = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
39
+
40
+ TONES = {"ok": "32", "bad": "31", "warn": "33", "active": "36", "muted": "2", "strong": "1"}
41
+
42
+
43
+ def paint(tone, text):
44
+ return "\x1b[%sm%s\x1b[0m" % (TONES[tone], text) if color.ANSIBLE_COLOR and text else text
45
+
46
+
47
+ def diff_lines(diff):
48
+ """Ansible colors a diff line with its newline inside, so a line's reset may end up on the next."""
49
+ reset = "\x1b[0m" if color.ANSIBLE_COLOR else ""
50
+ lines = [line + reset for line in diff.splitlines()]
51
+ while lines and not re.sub(r"\x1b\[[0-9;]*m", "", lines[-1]).strip():
52
+ lines.pop()
53
+ return lines
54
+
55
+
56
+ def duration(seconds):
57
+ if seconds < 10:
58
+ return "%.1fs" % (int(seconds * 10) / 10)
59
+ if seconds < 60:
60
+ return "%ds" % seconds
61
+ if seconds < 3600:
62
+ return "%dm%02ds" % (seconds // 60, seconds % 60)
63
+ return "%dh%02dm" % (seconds // 3600, seconds % 3600 // 60)
64
+
65
+
66
+ def tail(text, count=TAIL):
67
+ lines = str(text).rstrip().splitlines()
68
+ return (["… %d lines before" % (len(lines) - count)] if len(lines) > count else []) + lines[-count:]
69
+
70
+
71
+ def title(task, handler=False):
72
+ """`role › task` instead of Ansible's `role : task`."""
73
+ name = task.get_name().strip()
74
+ role, sep, rest = name.partition(" : ")
75
+ name = "%s › %s" % (role, rest) if sep else name
76
+ return "handler › " + name if handler else name
77
+
78
+
79
+ class CallbackModule(CallbackBase):
80
+ CALLBACK_VERSION = 2.0
81
+ CALLBACK_TYPE = "stdout"
82
+ CALLBACK_NAME = "kayra"
83
+
84
+ def __init__(self):
85
+ super().__init__()
86
+ self._pid = os.getpid()
87
+ self._live = sys.stdout.isatty() and os.environ.get("TERM") != "dumb"
88
+ self._width = min(shutil.get_terminal_size((COLUMNS, 24)).columns, COLUMNS)
89
+ # Display's own lock: the spinner never writes in the middle of its output.
90
+ self._lock = getattr(self._display, "_lock", None) or threading.RLock()
91
+ self._task = None
92
+ self._started = time.monotonic()
93
+ self._retrying = ""
94
+ self._drawn = False
95
+ self._shown = set()
96
+ self._handlers = set()
97
+ self._root = os.getcwd()
98
+ self._done = threading.Event()
99
+ if self._live:
100
+ self._wrap_display()
101
+ threading.Thread(target=self._tick, name="kayra-spinner", daemon=True).start()
102
+
103
+ # The line for the task at work: cleared before anything is printed, drawn again after.
104
+
105
+ def _wrap_display(self):
106
+ original = self._display.display
107
+
108
+ def display(msg, *args, **kwargs):
109
+ # Forked workers hand their output to this process; only it draws.
110
+ if os.getpid() != self._pid or kwargs.get("log_only"):
111
+ return original(msg, *args, **kwargs)
112
+ with self._lock:
113
+ self._clear()
114
+ original(msg, *args, **kwargs)
115
+ self._draw()
116
+
117
+ self._display.display = display
118
+
119
+ def _tick(self):
120
+ while not self._done.wait(0.1):
121
+ with self._lock:
122
+ self._draw()
123
+
124
+ def _clear(self):
125
+ if self._drawn:
126
+ sys.stdout.write("\r\x1b[2K")
127
+ sys.stdout.flush()
128
+ self._drawn = False
129
+
130
+ def _draw(self):
131
+ if not self._live or self._task is None or self._done.is_set():
132
+ return
133
+ elapsed = time.monotonic() - self._started
134
+ frame = FRAMES[int(elapsed * 10) % len(FRAMES)]
135
+ # One line, never wrapped: \r only returns to the start of the last one.
136
+ sys.stdout.write("\r\x1b[2K" + self._line(frame, "active", self._task + self._retrying, None, duration(elapsed)))
137
+ sys.stdout.flush()
138
+ self._drawn = True
139
+
140
+ # What is printed.
141
+
142
+ def _say(self, line=""):
143
+ self._display.display(line)
144
+
145
+ def _line(self, glyph, tone, name, name_tone, right):
146
+ """A glyph, a name, and `right` flush with the last column; lengths taken before painting."""
147
+ room = self._width - len(INDENT) - 2 - (len(right) + 2 if right else 0)
148
+ name = name if len(name) <= room else name[: max(0, room - 1)] + "…"
149
+ pad = " " * (room - len(name) + 2) if right else ""
150
+ return INDENT + paint(tone, glyph) + " " + (paint(name_tone, name) if name_tone else name) + pad + paint("muted", right)
151
+
152
+ def _headline(self, glyph, tone, name, name_tone=None, note=""):
153
+ took = time.monotonic() - self._started
154
+ right = " · ".join(part for part in (note, duration(took) if took >= 1 else "") if part)
155
+ self._say(self._line(glyph, tone, name, name_tone, right))
156
+
157
+ def _failure(self, result):
158
+ """A failure's warnings; its exception says again what its message says, at length."""
159
+ self._handle_warnings(result.result)
160
+ result.result.pop("exception", None)
161
+
162
+ def _details(self, result, tone=None):
163
+ res = result.result
164
+ if res.get("censored"):
165
+ self._say(DETAIL + paint("muted", res["censored"]))
166
+ return
167
+ lines = []
168
+ if res.get("msg"):
169
+ lines += str(res["msg"]).rstrip().splitlines()
170
+ for key in ("stderr", "module_stderr", "stdout", "module_stdout"):
171
+ text = res.get(key)
172
+ if text and str(text).strip() and str(text).strip() != str(res.get("msg", "")).strip():
173
+ lines += [paint("muted", key + ":")] + [" " + line for line in tail(text)]
174
+ if not lines:
175
+ lines = self._dump_results(res, indent=2).rstrip().splitlines()
176
+ for line in lines:
177
+ self._say(DETAIL + (paint(tone, line) if tone else line))
178
+ path = result.task.get_path()
179
+ if path:
180
+ self._say(DETAIL + paint("muted", "at " + os.path.relpath(path, self._root)))
181
+
182
+ def _changed(self, result, label=""):
183
+ key = (result.task._uuid, result.host.get_name(), label)
184
+ if key in self._shown:
185
+ return
186
+ self._shown.add(key)
187
+ self._headline("~", "warn", self._name(result) + (" · %s" % label if label else ""))
188
+
189
+ def _name(self, result):
190
+ return title(result.task, handler=result.task._uuid in self._handlers)
191
+
192
+ # Ansible's events.
193
+
194
+ def v2_playbook_on_start(self, playbook):
195
+ # Tasks are named by their path from above the playbooks: roles/<role>/tasks/main.yml.
196
+ self._root = os.path.dirname(os.path.abspath(playbook._basedir))
197
+
198
+ def v2_playbook_on_play_start(self, play):
199
+ name = play.get_name().strip()
200
+ with self._lock:
201
+ self._task = None
202
+ if name:
203
+ self._say(INDENT + paint("muted", "▸ " + name))
204
+
205
+ def _start(self, task, handler=False):
206
+ with self._lock:
207
+ if handler:
208
+ self._handlers.add(task._uuid)
209
+ self._task = title(task, handler)
210
+ self._started = time.monotonic()
211
+ self._retrying = ""
212
+ self._clear()
213
+ self._draw()
214
+
215
+ def v2_playbook_on_task_start(self, task, is_conditional):
216
+ self._start(task)
217
+
218
+ def v2_playbook_on_handler_task_start(self, task):
219
+ self._start(task, handler=True)
220
+
221
+ def v2_runner_on_ok(self, result):
222
+ self._handle_warnings_and_exception(result)
223
+ if isinstance(result.task, TaskInclude):
224
+ return
225
+ res = result.result
226
+ if result.task.action in C._ACTION_DEBUG and not result.task.loop:
227
+ self._clean_results(res, result.task.action)
228
+ self._headline("·", "active", self._name(result))
229
+ msg = res.get("msg")
230
+ text = "\n".join(map(str, msg)) if isinstance(msg, list) else str(msg) if "msg" in res else self._dump_results(res, indent=2)
231
+ for line in text.rstrip().splitlines():
232
+ self._say(DETAIL + line)
233
+ return
234
+ if res.get("changed") and not (result.task.loop and "results" in res):
235
+ self._changed(result)
236
+
237
+ def v2_runner_item_on_ok(self, result):
238
+ self._handle_warnings_and_exception(result)
239
+ if result.result.get("changed"):
240
+ self._changed(result, str(self._get_item_label(result.result)))
241
+
242
+ def v2_on_file_diff(self, result):
243
+ res = result.result
244
+ items = res["results"] if result.task.loop and "results" in res else [res]
245
+ for item in items:
246
+ if item.get("diff") and item.get("changed"):
247
+ diff = self._get_diff(item["diff"])
248
+ if diff:
249
+ label = str(self._get_item_label(item)) if result.task.loop else ""
250
+ self._changed(result, label)
251
+ for line in diff_lines(diff):
252
+ self._say(DETAIL + line)
253
+
254
+ def v2_runner_on_failed(self, result, ignore_errors=False):
255
+ self._failure(result)
256
+ if result.task.loop and "results" in result.result:
257
+ return
258
+ if ignore_errors:
259
+ self._headline("✗", "muted", self._name(result), "muted", "ignored")
260
+ return
261
+ rc = result.result.get("rc")
262
+ self._headline("✗", "bad", self._name(result), "strong", "exit %s" % rc if rc not in (None, 0) else "")
263
+ self._details(result)
264
+
265
+ def v2_runner_item_on_failed(self, result):
266
+ self._failure(result)
267
+ self._headline("✗", "bad", "%s · %s" % (self._name(result), self._get_item_label(result.result)), "strong")
268
+ self._details(result)
269
+
270
+ def v2_runner_on_unreachable(self, result):
271
+ self._failure(result)
272
+ self._headline("✗", "bad", "%s unreachable" % result.host.get_name(), "strong")
273
+ self._details(result)
274
+
275
+ def v2_runner_retry(self, result):
276
+ left = result.result.get("retries", 0) - result.result.get("attempts", 0)
277
+ with self._lock:
278
+ first = not self._retrying
279
+ self._retrying = " (retrying, %d left)" % left
280
+ # On a terminal the task's line says it; elsewhere once is enough to show it is not stuck.
281
+ if first and not self._live:
282
+ self._headline("↻", "warn", "%s: retrying, %d left" % (self._name(result), left))
283
+
284
+ def v2_playbook_on_no_hosts_matched(self):
285
+ self._say(INDENT + paint("muted", "no hosts matched"))
286
+
287
+ def v2_playbook_on_stats(self, stats):
288
+ with self._lock:
289
+ self._task = None
290
+ self._done.set()
291
+ self._clear()
292
+ hosts = sorted(stats.processed.keys())
293
+ for host in hosts:
294
+ counts = stats.summarize(host)
295
+ parts = [paint("muted", "%d ok" % counts["ok"]), paint("warn" if counts["changed"] else "muted", "%d changed" % counts["changed"])]
296
+ parts += [paint("muted", "%d %s" % (counts[key], word)) for key, word in (("skipped", "skipped"), ("rescued", "rescued"), ("ignored", "ignored")) if counts[key]]
297
+ parts += [paint("bad", "%d %s" % (counts[key], word)) for key, word in (("failures", "failed"), ("unreachable", "unreachable")) if counts[key]]
298
+ prefix = paint("muted", host + ": ") if len(hosts) > 1 else ""
299
+ self._say(INDENT + prefix + paint("muted", " · ").join(parts))
package/cli/dist/cli.js CHANGED
@@ -1,40 +1,166 @@
1
- import { command, constant, multiple, object, option, optional, or } from "@optique/core";
2
- import { message } from "@optique/core/message";
1
+ import { command, constant, group, map, merge, multiple, object, option, optional, or } from "@optique/core";
2
+ import { lineBreak, message, text, url } from "@optique/core/message";
3
3
  import { argument } from "@optique/core/primitives";
4
4
  import { choice, string } from "@optique/core/valueparser";
5
5
  import { appNameParser, domainParser, serverNameParser, subdomainParser } from "./brand.js";
6
+ /** Command lines, each with what it is for, aligned. Plain text: Optique folds an indent that stands alone before a command line. */
7
+ const examples = (indent, rows) => {
8
+ const width = Math.max(...rows.map(([line]) => line.length));
9
+ return rows.flatMap(([line, what], index) => [...(index === 0 ? [] : [lineBreak()]), text(`${indent}${line.padEnd(width)} ${what}`)]);
10
+ };
11
+ const docs = message `Docs: ${url("https://yunuseon.github.io/kayra/")}`;
12
+ /** A command's examples; Optique shows a command's footer instead of the program's, so the docs follow. */
13
+ const footer = (...rows) => [
14
+ ...message `Examples:`,
15
+ lineBreak(),
16
+ ...examples(" ", rows),
17
+ lineBreak(),
18
+ lineBreak(),
19
+ ...docs,
20
+ ];
21
+ const sections = ["On a server", "Apps on a server", "In an app's repository", "The whole fleet", "Options", "Help"];
22
+ /** Arguments (the untitled section) first, then the sections in the order above. */
23
+ const sectionOrder = (a, b) => sections.indexOf(a.title ?? "") - sections.indexOf(b.title ?? "");
24
+ const usageLine = [
25
+ { type: "argument", metavar: "COMMAND" },
26
+ { type: "multiple", terms: [{ type: "argument", metavar: "ARG" }], min: 0 },
27
+ { type: "optional", terms: [{ type: "option", names: ["--dry-run"] }] },
28
+ { type: "optional", terms: [{ type: "option", names: ["-v", "--verbose"] }] },
29
+ ];
30
+ /** How kayra presents itself: help in sections, examples, the docs; errors without the full usage above them. */
31
+ export const runOptions = (version) => ({
32
+ programName: "kayra",
33
+ // `kayra help deploy` and `kayra version` work too; listed once, as options.
34
+ help: { option: { names: ["-h", "--help"], group: "Help" }, command: { hidden: "doc" } },
35
+ version: { value: version, option: { group: "Help" }, command: { hidden: "doc" } },
36
+ // The option form's ARG cannot be hidden from the help page; completion scripts call the command.
37
+ completion: { command: { group: "Help" } },
38
+ brief: message `kayra ${text(version)}: a fleet's servers, from the machine to the apps on it.`,
39
+ description: message `Run it anywhere inside a fleet (the directory holding servers/); app check also outside one. Server names are the fleet's and complete in the shell.`,
40
+ examples: examples("", [
41
+ ["kayra status", "every server, and whether it answers"],
42
+ ["kayra up shop-test", "a server from nothing"],
43
+ ["kayra plan shop-prod", "what this checkout would change on it"],
44
+ ["kayra deploy shop-prod", "host setup and every app, then verify"],
45
+ ["kayra deploy shop-prod --dry-run", "every step it would run, running none"],
46
+ ["kayra setup shop-prod -v", "with Ansible's own output"],
47
+ ["kayra app logs shop-prod shop", "the newest run's log"],
48
+ ["kayra deploy --help", "a command's arguments and examples"],
49
+ ]),
50
+ footer: docs,
51
+ usageLine,
52
+ sectionOrder,
53
+ termWidth: "auto",
54
+ showChoices: true,
55
+ aboveError: "none",
56
+ });
6
57
  /** The arguments kayra takes; server names are the fleet's, so they complete and are checked while parsing. */
7
58
  export const parser = (fleet) => {
8
59
  const [first, ...rest] = fleet.servers.map((each) => each.name);
9
60
  // Outside a fleet there is no name to offer; main refuses every server command there.
10
- const server = argument(first === undefined ? serverNameParser : choice([first, ...rest], { metavar: "SERVER" }));
61
+ // Help adds the fleet's servers to its description (showChoices): kept short so they fit beside it.
62
+ const server = argument(first === undefined ? serverNameParser : choice([first, ...rest], { metavar: "SERVER", suggest: "nearest" }), { description: message `A server` });
63
+ const app = argument(appNameParser, { description: message `An app in the server's server.yml.` });
11
64
  // eslint-disable-next-line functional/prefer-immutable-types -- Optique's Message is readonly only at the top
12
- const onServer = (name, brief) => command(name, object({ name: constant(name), server }), { brief });
13
- return object({
65
+ const onServer = (name, brief, more = {}) => command(name, object({ name: constant(name), server }), { brief, ...more });
66
+ return merge(group("Options", object({
14
67
  dryRun: option("--dry-run", { description: message `Print the plan instead of running it.` }),
15
- command: or(
16
- // On one server
17
- or(onServer("up", message `Provision, set up everything, point /etc/hosts at it.`), onServer("provision", message `Create or update the machine (target home: build the image to import).`), onServer("deploy", message `Host setup and every app, no provisioning.`), onServer("setup", message `The host layer only: the playbook for the server's kind.`), onServer("plan", message `What provision and setup would change, changing nothing (OpenTofu plan, Ansible check mode).`), onServer("verify", message `Whether a platform server works as its users see it: logins, certificates, webhooks, apps, runs, alerts.`), onServer("apps", message `Make the server's apps match server.yml: register each, remove the rest (data kept).`), onServer("hosts", message `Point the domain at a multipass VM in /etc/hosts (sudo).`), command("ssh", object({ name: constant("ssh"), server, remote: multiple(argument(string({ metavar: "COMMAND" }))) }), { brief: message `SSH into the server, or run a command there (after --).` }), onServer("down", message `Destroy the machine.`), onServer("adopt", message `Once, for a server we did not create: add the deploy user as root.`), command("backup", command("test", object({ name: constant("backup test"), server })), {
18
- brief: message `Restore the latest backup to a scratch dir, check it, delete it.`,
19
- }), command("app", or(command("check", object({ name: constant("app check"), dir: optional(argument(string({ metavar: "DIR" }))) }), {
20
- brief: message `In an app's repository: what the platform checks at deploy (app.yml, images, compose policy). No fleet needed.`,
21
- }), command("purge", object({ name: constant("app purge"), server, app: argument(appNameParser) }), {
22
- brief: message `Delete a removed app's volumes: its data, irreversibly.`,
23
- }), command("runs", object({ name: constant("app runs"), server, app: argument(appNameParser) }), {
24
- brief: message `The app's latest runs: id, result, commit, why.`,
25
- }), command("logs", object({ name: constant("app logs"), server, app: argument(appNameParser), more: optional(argument(string({ metavar: "RUN" }))) }), { brief: message `A run's log, the newest unless named.` }), command("deploy", object({ name: constant("app deploy"), server, app: argument(appNameParser), more: optional(argument(string({ metavar: "REF" }))) }), { brief: message `Build and deploy a branch, tag or commit (default: the app's ref).` }), command("rollback", object({ name: constant("app rollback"), server, app: argument(appNameParser), more: optional(argument(string({ metavar: "SHA" }))) }), { brief: message `List earlier releases, or deploy one of them again.` })), { brief: message `An app: check it before a push, or on a server its runs, logs, deploys, rollbacks, and purging its data.` }), command("job", object({
26
- name: constant("job"),
27
- server,
28
- job: argument(choice(["gc", "renovate"], { metavar: "JOB" })),
29
- noPrs: option("--no-prs", { description: message `Renovate: log what would change, open no PRs.` }),
30
- }), { brief: message `Run a platform job now: the registry GC or Renovate.` })),
31
- // On the whole fleet
32
- or(command("status", object({ name: constant("status") }), {
33
- brief: message `Every server and whether a machine exists for it.`,
34
- }), command("certs", object({ name: constant("certs"), domain: argument(domainParser), subdomains: multiple(argument(subdomainParser)) }), { brief: message `mkcert certs for a domain and its subdomains (local dev, multipass).` }), command("validate", object({ name: constant("validate"), server: optional(server) }), {
35
- brief: message `Check the fleet beyond its schemas: secrets, apps against their contract, stacks, routes.`,
36
- }), command("doctor", object({ name: constant("doctor") }), {
37
- brief: message `Check that this Mac can run every command on every server.`,
38
- }))),
39
- });
68
+ verbose: option("-v", "--verbose", {
69
+ description: message `Ansible's own output (with -v) instead of kayra's summary.`,
70
+ }),
71
+ })), map(or(group("On a server", or(onServer("up", message `Provision, set up everything, point /etc/hosts at it.`, {
72
+ description: message `Runs provision, then deploy (setup, apps, verify), then hosts: each part is a command of its own, and a failure names the one to run again.`,
73
+ footer: footer(["kayra up shop-test", "a test server from nothing"]),
74
+ }), onServer("provision", message `Create or update the machine (target home: build the image to import).`), onServer("deploy", message `Host setup and every app, no provisioning.`, {
75
+ description: message `Runs setup, then apps; a platform server is verified at the end, so a deploy that leaves it broken fails. Hetzner and home servers change only from a clean main equal to its remote, with the kayra the fleet pins.`,
76
+ footer: footer(["kayra deploy shop-prod", "after a new kayra or a fleet change"], ["kayra deploy shop-prod --dry-run", "every step, its command and environment"], ["kayra deploy shop-prod -v", "with Ansible's own output"]),
77
+ }), onServer("setup", message `The host layer only: the playbook for the server's kind.`, {
78
+ footer: footer(["kayra setup shop-prod", "after a change to vars.yml or secrets.yml"], ["kayra setup shop-prod -v", "with Ansible's own output"]),
79
+ }), onServer("plan", message `What provision and setup would change, changing nothing (OpenTofu plan, Ansible check mode).`, {
80
+ description: message `OpenTofu's plan, then the playbook in check mode with diffs; files holding secrets only say that they would change. Works from any branch: it previews this checkout against the server.`,
81
+ footer: footer(["kayra plan shop-prod", "what merging this branch would change on it"]),
82
+ }), onServer("verify", message `Whether a platform server works as its users see it: logins, certificates, webhooks, apps, runs, alerts.`, {
83
+ description: message `Run by deploy and up at the end. The probes retry for VERIFY_WAIT seconds (150), for certificates still coming.`,
84
+ }), onServer("apps", message `Make the server's apps match server.yml: register each, remove the rest (data kept).`, {
85
+ footer: footer(["kayra apps shop-prod", "after a change to apps/*.yml"]),
86
+ }), onServer("hosts", message `Point the domain at a multipass VM in /etc/hosts (sudo).`), command("ssh", object({
87
+ name: constant("ssh"),
88
+ server,
89
+ remote: multiple(argument(string({ metavar: "COMMAND" }), { description: message `A command to run there instead of a shell.` })),
90
+ }), {
91
+ brief: message `SSH into the server, or run a command there (after --).`,
92
+ footer: footer(["kayra ssh shop-test", "a shell"], ["kayra ssh shop-test -- df -h /", "one command"]),
93
+ }), onServer("down", message `Destroy the machine.`, {
94
+ description: message `OpenTofu destroy; on a Hetzner server only once its name is typed.`,
95
+ }), onServer("adopt", message `Once, for a server we did not create: add the deploy user as root.`), command("backup", command("test", object({ name: constant("backup test"), server })), {
96
+ brief: message `Restore the latest backup to a scratch dir, check it, delete it.`,
97
+ footer: footer(["kayra backup test nas", "started on the server, followed over SSH"]),
98
+ }))), group("Apps on a server", or(command("app", or(group("In an app's repository", command("check", object({
99
+ name: constant("app check"),
100
+ dir: optional(argument(string({ metavar: "DIR" }), { description: message `The app's repository; the current directory by default.` })),
101
+ }), {
102
+ brief: message `What the platform checks at deploy (app.yml, images, compose policy). No fleet needed.`,
103
+ footer: footer(["kayra app check", "in the app's repository, before a push"]),
104
+ })), group("On a server", or(command("purge", object({ name: constant("app purge"), server, app }), {
105
+ brief: message `Delete a removed app's volumes: its data, irreversibly.`,
106
+ }), command("runs", object({ name: constant("app runs"), server, app }), {
107
+ brief: message `What runs now, and the app's latest runs: state, commit, why, when, how long.`,
108
+ }), command("logs", object({
109
+ name: constant("app logs"),
110
+ server,
111
+ app,
112
+ more: optional(argument(string({ metavar: "RUN" }), { description: message `A run's id from app runs; the newest by default.` })),
113
+ }), {
114
+ brief: message `A run's log, the newest unless named.`,
115
+ footer: footer(["kayra app logs shop-prod shop", "the newest run's log"]),
116
+ }), command("deploy", object({
117
+ name: constant("app deploy"),
118
+ server,
119
+ app,
120
+ more: optional(argument(string({ metavar: "REF" }), { description: message `A branch, tag or commit; the app's ref by default.` })),
121
+ }), {
122
+ brief: message `Build and deploy a branch, tag or commit (default: the app's ref).`,
123
+ footer: footer(["kayra app deploy shop-prod shop v1.2.0", "a tag, now"]),
124
+ }), command("rollback", object({
125
+ name: constant("app rollback"),
126
+ server,
127
+ app,
128
+ more: optional(argument(string({ metavar: "SHA" }), { description: message `An earlier release's commit; 12 characters are enough.` })),
129
+ }), {
130
+ brief: message `The releases, the live one marked, or deploy an earlier one again.`,
131
+ footer: footer(["kayra app rollback shop-prod shop", "what runs now, and before"], ["kayra app rollback shop-prod shop 3f2a9c81d0be", "that release again"]),
132
+ })))), { brief: message `An app: check it before a push, or on a server its runs, logs, deploys, rollbacks, and purging its data.` }), command("job", object({
133
+ name: constant("job"),
134
+ server,
135
+ job: argument(choice(["gc", "renovate"], { metavar: "JOB", suggest: "nearest" }), {
136
+ description: message `Which job`,
137
+ }),
138
+ noPrs: option("--no-prs", { description: message `Renovate: log what would change, open no PRs.` }),
139
+ }), {
140
+ brief: message `Run a platform job now: the registry GC or Renovate.`,
141
+ footer: footer(["kayra job shop-prod renovate --no-prs", "what Renovate would change, no PRs"]),
142
+ }))), group("The whole fleet", or(command("status", object({
143
+ name: constant("status"),
144
+ json: option("--json", { description: message `The table as JSON on stdout, nothing on stderr.` }),
145
+ offline: option("--offline", { description: message `Only what the fleet and OpenTofu's state say: reach no server.` }),
146
+ }), {
147
+ brief: message `Every server: where it is, whether SSH and its login answer.`,
148
+ footer: footer(["kayra status", "every server, asked now"], ["kayra status --offline --json", "the fleet's own view, for a program"]),
149
+ }), command("validate", object({
150
+ name: constant("validate"),
151
+ server: optional(server),
152
+ json: option("--json", { description: message `The findings as JSON on stdout, nothing on stderr.` }),
153
+ }), {
154
+ brief: message `Check the fleet beyond its schemas: secrets, apps against their contract, stacks, routes.`,
155
+ footer: footer(["kayra validate", "every server"], ["kayra validate shop-prod", "one"]),
156
+ }), command("doctor", object({ name: constant("doctor") }), {
157
+ brief: message `Check that this Mac can run every command on every server.`,
158
+ }), command("certs", object({
159
+ name: constant("certs"),
160
+ domain: argument(domainParser, { description: message `The domain the certificates are for.` }),
161
+ subdomains: multiple(argument(subdomainParser, { description: message `Its subdomains, each with a certificate.` })),
162
+ }), {
163
+ brief: message `mkcert certs for a domain and its subdomains (local dev, multipass).`,
164
+ footer: footer(["kayra certs shop.test www api", "into the fleet's .cache/certs"]),
165
+ })))), (chosen) => ({ command: chosen })));
40
166
  };
@@ -30,6 +30,6 @@ export const appCheck = (kayra, root, manifest) => {
30
30
  tool("jq", "brew install jq"),
31
31
  tool("yq", "brew install yq"),
32
32
  tool("docker", "the docker CLI with Compose; no daemon is needed"),
33
- run(["bash", within(kayra, "scripts", "local", "app-check.sh"), root]),
33
+ run("Image plan and compose policy", ["bash", within(kayra, "scripts", "local", "app-check.sh"), root]),
34
34
  ]);
35
35
  };