@yunuseon/kayra 0.14.0 → 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.
- package/ansible/ansible.cfg +6 -3
- package/ansible/callback_plugins/kayra.py +299 -0
- package/cli/dist/cli.js +156 -30
- package/cli/dist/commands/app-check.js +1 -1
- package/cli/dist/commands/server.js +68 -49
- package/cli/dist/commands/status.js +181 -30
- package/cli/dist/commands/validate.js +92 -31
- package/cli/dist/deployer/answers.js +21 -0
- package/cli/dist/deployer/ctl.js +20 -6
- package/cli/dist/gather.js +9 -5
- package/cli/dist/interpret.js +71 -50
- package/cli/dist/main.js +85 -25
- package/cli/dist/net.js +52 -0
- package/cli/dist/plan.js +35 -4
- package/cli/dist/ui/explain.js +37 -0
- package/cli/dist/ui/line.js +39 -0
- package/cli/dist/ui/progress.js +100 -0
- package/cli/dist/ui/terminal.js +93 -0
- package/cli/dist/ui/text.js +71 -0
- package/cli/dist/ui/views.js +127 -0
- package/cli/dist/validate.js +8 -3
- package/package.json +1 -1
- package/scripts/local/verify.sh +2 -2
|
@@ -1,13 +1,20 @@
|
|
|
1
1
|
import { appManifestSchema, secretsSchema, settings } from "../settings.js";
|
|
2
|
-
|
|
3
|
-
|
|
2
|
+
import { active, bad, muted, ok, strong } from "../ui/line.js";
|
|
3
|
+
import { closest } from "../validate.js";
|
|
4
|
+
const finding = (result, text, hint) => ({ result, text, ...(hint === undefined ? {} : { hint }) });
|
|
5
|
+
const problem = (text, hint) => finding("problem", text, hint);
|
|
6
|
+
const unchecked = (text, hint) => finding("unchecked", text, hint);
|
|
7
|
+
const passed = (text) => finding("passed", text);
|
|
8
|
+
/** A check's findings, or one line saying it holds when it found nothing to say. */
|
|
9
|
+
const holds = (found, text) => (found.length === 0 ? [passed(text)] : found);
|
|
10
|
+
const count = (n, noun) => `${String(n)} ${noun}${n === 1 ? "" : "s"}`;
|
|
4
11
|
const mapping = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? Object.fromEntries(Object.entries(value)) : {};
|
|
5
12
|
const strings = (value) => Array.isArray(value) ? value.filter((each) => typeof each === "string") : [];
|
|
6
13
|
const secretSettingNames = (kind) => settings.filter((each) => each.secret && each.kinds.includes(kind)).map((each) => each.name);
|
|
7
14
|
/** secrets.yml: known secrets typed; anything else must be a helper vars.yml uses. */
|
|
8
15
|
const secretsFindings = (facts) => {
|
|
9
16
|
if (facts.secrets.kind === "locked")
|
|
10
|
-
return [
|
|
17
|
+
return [unchecked(`secrets.yml not checked: ${facts.secrets.reason}`, facts.secrets.hint)];
|
|
11
18
|
const values = facts.secrets.values;
|
|
12
19
|
const typed = secretsSchema(facts.server.kind).safeParse(values);
|
|
13
20
|
const typeProblems = typed.success
|
|
@@ -17,68 +24,122 @@ const secretsFindings = (facts) => {
|
|
|
17
24
|
const unused = Object.keys(values)
|
|
18
25
|
.filter((key) => !known.includes(key) && !key.startsWith("ansible_"))
|
|
19
26
|
.filter((key) => !new RegExp(`\\b${key}\\b`).test(facts.varsText))
|
|
20
|
-
.map((key) =>
|
|
21
|
-
|
|
27
|
+
.map((key) => {
|
|
28
|
+
const meant = closest(key, known);
|
|
29
|
+
return problem(`secrets.yml: '${key}' is no secret of ${/^[aeiou]/.test(facts.server.kind) ? "an" : "a"} ${facts.server.kind} server, and vars.yml does not use it`, meant === undefined ? "remove it, or use it in vars.yml" : `did you mean '${meant}'?`);
|
|
30
|
+
});
|
|
31
|
+
return holds([...typeProblems, ...unused], `secrets.yml: ${count(Object.keys(values).length, "secret")}, each a setting or used by vars.yml`);
|
|
22
32
|
};
|
|
23
33
|
/** compose_stacks.stacks and stacks/ name the same stacks. */
|
|
24
34
|
const stackFindings = (facts) => {
|
|
25
35
|
const listed = strings(mapping(facts.vars["compose_stacks"])["stacks"]);
|
|
26
|
-
|
|
36
|
+
if (listed.length === 0 && facts.stackDirs.length === 0)
|
|
37
|
+
return [];
|
|
38
|
+
return holds([
|
|
27
39
|
...listed
|
|
28
40
|
.filter((name) => !facts.stackDirs.includes(name))
|
|
29
|
-
.map((name) => problem(`compose_stacks.stacks: '${name}' has no stacks/${name}/compose.yaml`)),
|
|
41
|
+
.map((name) => problem(`compose_stacks.stacks: '${name}' has no stacks/${name}/compose.yaml`, `add stacks/${name}/compose.yaml, or take '${name}' off the list`)),
|
|
30
42
|
...facts.stackDirs
|
|
31
43
|
.filter((name) => !listed.includes(name))
|
|
32
|
-
.map((name) => problem(`stacks/${name} is not in compose_stacks.stacks, so it never runs
|
|
33
|
-
];
|
|
44
|
+
.map((name) => problem(`stacks/${name} is not in compose_stacks.stacks, so it never runs`, "list it in compose_stacks.stacks in vars.yml, or remove the folder")),
|
|
45
|
+
], `stacks: ${count(listed.length, "stack")}, each listed in compose_stacks.stacks and in stacks/`);
|
|
34
46
|
};
|
|
35
47
|
/** edge_routes: subdomains and an upstream host:port. */
|
|
36
48
|
const routeFindings = (facts) => {
|
|
37
49
|
const routes = Array.isArray(facts.vars["edge_routes"]) ? facts.vars["edge_routes"] : [];
|
|
38
|
-
|
|
50
|
+
if (routes.length === 0)
|
|
51
|
+
return [];
|
|
52
|
+
return holds(routes.flatMap((route, index) => {
|
|
39
53
|
const fields = mapping(route);
|
|
40
54
|
const upstream = fields["upstream"];
|
|
41
55
|
return [
|
|
42
56
|
...strings(fields["subdomains"])
|
|
43
57
|
.filter((sub) => !/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(sub))
|
|
44
|
-
.map((sub) => problem(`edge_routes[${String(index)}]: '${sub}' is not a subdomain
|
|
58
|
+
.map((sub) => problem(`edge_routes[${String(index)}]: '${sub}' is not a subdomain`, "lowercase letters, digits and dashes")),
|
|
45
59
|
...(typeof upstream === "string" && /^[^\s:]+:\d+$/.test(upstream)
|
|
46
60
|
? []
|
|
47
|
-
: [problem(`edge_routes[${String(index)}]: upstream must be host:port
|
|
61
|
+
: [problem(`edge_routes[${String(index)}]: upstream must be host:port`, "a host and its port, e.g. 192.168.1.10:8080")]),
|
|
48
62
|
];
|
|
49
|
-
});
|
|
63
|
+
}), `edge_routes: ${count(routes.length, "route")}, each with subdomains and a host:port upstream`);
|
|
50
64
|
};
|
|
51
65
|
/** Each app's contract against the fleet's values for it. */
|
|
52
66
|
const appFindings = (facts) => facts.server.apps.flatMap((app) => {
|
|
53
67
|
const manifest = facts.manifests[app.name];
|
|
54
68
|
if (manifest === undefined)
|
|
55
|
-
return [
|
|
69
|
+
return [unchecked(`app ${app.name} not checked: not cloned yet`, `kayra apps ${facts.server.name} clones it`)];
|
|
56
70
|
const parsed = appManifestSchema.safeParse(manifest);
|
|
57
71
|
if (!parsed.success)
|
|
58
72
|
return [problem(`app ${app.name}: its app.yml: ${parsed.error.issues.at(0)?.message ?? "invalid"}`)];
|
|
59
73
|
if (parsed.data.name !== app.name)
|
|
60
|
-
return [problem(`app ${app.name}: its app.yml says name ${parsed.data.name}
|
|
74
|
+
return [problem(`app ${app.name}: its app.yml says name ${parsed.data.name}`, "server.yml and app.yml must name it alike")];
|
|
75
|
+
const configKeys = parsed.data.config ?? [];
|
|
76
|
+
const secretKeys = parsed.data.secrets ?? [];
|
|
61
77
|
const config = facts.appConfig[app.name] ?? {};
|
|
62
|
-
const
|
|
78
|
+
const valuesFile = `apps/${app.name}.yml`;
|
|
79
|
+
const secretsFile = `apps/${app.name}.secrets.yml`;
|
|
80
|
+
const missingConfig = configKeys
|
|
63
81
|
.filter((key) => !(key in config))
|
|
64
|
-
.map((key) => problem(
|
|
65
|
-
const secrets = facts.appSecrets[app.name];
|
|
66
|
-
const
|
|
67
|
-
|
|
82
|
+
.map((key) => problem(`${valuesFile}: no value for ${key}, which app.yml asks for`, `add ${key}: … to servers/${facts.server.name}/${valuesFile}`));
|
|
83
|
+
const secrets = facts.appSecrets[app.name] ?? { kind: "readable", values: {} };
|
|
84
|
+
const edit = facts.server.target === "multipass" ? "add it to" : "ansible-vault edit";
|
|
85
|
+
const missingSecrets = secrets.kind === "locked"
|
|
86
|
+
? secretKeys.length === 0
|
|
68
87
|
? []
|
|
69
|
-
: [
|
|
70
|
-
:
|
|
88
|
+
: [unchecked(`${secretsFile} not checked: ${secrets.reason}`, secrets.hint)]
|
|
89
|
+
: secretKeys
|
|
71
90
|
.filter((key) => !(key in secrets.values))
|
|
72
|
-
.map((key) => problem(
|
|
73
|
-
return [...missingConfig, ...missingSecrets];
|
|
91
|
+
.map((key) => problem(`${secretsFile}: no value for ${key}, which app.yml asks for`, `${edit} servers/${facts.server.name}/${secretsFile}`));
|
|
92
|
+
return holds([...missingConfig, ...missingSecrets], `app ${app.name}: ${count(configKeys.length, "config value")} and ${count(secretKeys.length, "secret")}, as its app.yml asks`);
|
|
74
93
|
});
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
94
|
+
const rank = { problem: 0, unchecked: 1, passed: 2 };
|
|
95
|
+
/** Everything validate finds for one server: problems first, then what it could not check, then what holds. */
|
|
96
|
+
export const findings = (facts) => [...secretsFindings(facts), ...stackFindings(facts), ...routeFindings(facts), ...appFindings(facts)].toSorted((a, b) => rank[a.result] - rank[b.result]);
|
|
97
|
+
/** How a set of findings went as a whole: its worst. */
|
|
98
|
+
export const overall = (found) => found.some((each) => each.result === "problem") ? "problem" : found.some((each) => each.result === "unchecked") ? "unchecked" : "passed";
|
|
99
|
+
const marks = { problem: bad("✗"), unchecked: muted("·"), passed: ok("✓") };
|
|
100
|
+
const tally = (reports) => {
|
|
101
|
+
const all = reports.flatMap((report) => report.findings);
|
|
102
|
+
return {
|
|
103
|
+
problems: all.filter((each) => each.result === "problem").length,
|
|
104
|
+
unchecked: all.filter((each) => each.result === "unchecked").length,
|
|
105
|
+
};
|
|
106
|
+
};
|
|
107
|
+
/** "✗ 3 servers · 1 problem · 2 not checked" */
|
|
108
|
+
export const summary = (reports) => {
|
|
109
|
+
const { problems, unchecked: notChecked } = tally(reports);
|
|
80
110
|
return [
|
|
81
|
-
|
|
82
|
-
|
|
111
|
+
marks[overall(reports.flatMap((report) => report.findings))],
|
|
112
|
+
" ",
|
|
113
|
+
count(reports.length, "server"),
|
|
114
|
+
muted(" · "),
|
|
115
|
+
problems === 0 ? ok("no problems") : bad(count(problems, "problem")),
|
|
116
|
+
...(notChecked === 0 ? [] : [muted(" · "), `${String(notChecked)} not checked`]),
|
|
83
117
|
];
|
|
84
118
|
};
|
|
119
|
+
/** Each server with its mark, its findings under it with what to do about them, then the summary. */
|
|
120
|
+
export const validateView = (reports) => {
|
|
121
|
+
const names = Math.max(0, ...reports.map((report) => report.server.name.length));
|
|
122
|
+
return [
|
|
123
|
+
...reports.flatMap((report) => [
|
|
124
|
+
[marks[overall(report.findings)], " ", strong(report.server.name.padEnd(names)), muted(` ${report.server.kind} on ${report.server.target}`)],
|
|
125
|
+
...report.findings.flatMap((each) => [
|
|
126
|
+
[" ", marks[each.result], " ", each.result === "passed" ? muted(each.text) : each.text],
|
|
127
|
+
...(each.hint === undefined ? [] : [[" ", active("→"), " ", each.hint]]),
|
|
128
|
+
]),
|
|
129
|
+
[],
|
|
130
|
+
]),
|
|
131
|
+
summary(reports),
|
|
132
|
+
];
|
|
133
|
+
};
|
|
134
|
+
/** `kayra validate --json`: the shape cli.md documents. */
|
|
135
|
+
export const validateJson = (reports) => ({
|
|
136
|
+
result: overall(reports.flatMap((report) => report.findings)),
|
|
137
|
+
...tally(reports),
|
|
138
|
+
servers: reports.map((report) => ({
|
|
139
|
+
name: report.server.name,
|
|
140
|
+
kind: report.server.kind,
|
|
141
|
+
target: report.server.target,
|
|
142
|
+
result: overall(report.findings),
|
|
143
|
+
findings: report.findings.map((each) => ({ result: each.result, text: each.text, hint: each.hint ?? null })),
|
|
144
|
+
})),
|
|
145
|
+
});
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** A release record's compact UTC time, 20261018T101500Z, as ISO 8601. */
|
|
2
|
+
const iso = (compact) => compact.replace(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/, "$1-$2-$3T$4:$5:$6Z");
|
|
3
|
+
const deployed = (release) => ({ sha: release.sha, time: iso(release.time) });
|
|
4
|
+
const answer = (run) => ({
|
|
5
|
+
id: run.id,
|
|
6
|
+
state: run.state,
|
|
7
|
+
why: run.why,
|
|
8
|
+
what: run.what,
|
|
9
|
+
...(run.sha === undefined ? {} : { sha: run.sha }),
|
|
10
|
+
started: run.started,
|
|
11
|
+
...(run.finished === undefined ? {} : { finished: run.finished }),
|
|
12
|
+
});
|
|
13
|
+
export const runsAnswer = (app, runs, live) => ({
|
|
14
|
+
app,
|
|
15
|
+
...(live === undefined ? {} : { live: deployed(live) }),
|
|
16
|
+
runs: runs.map(answer),
|
|
17
|
+
});
|
|
18
|
+
export const releasesAnswer = (app, releases) => ({
|
|
19
|
+
app,
|
|
20
|
+
releases: releases.map((release, index) => ({ ...deployed(release), live: index === 0 })),
|
|
21
|
+
});
|
package/cli/dist/deployer/ctl.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { existsSync, readdirSync } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
|
+
import { releasesAnswer, runsAnswer } from "./answers.js";
|
|
3
4
|
import { appOwner, appName, owner as mintOwner, runId } from "./brand.js";
|
|
4
5
|
import { releases } from "./records.js";
|
|
5
6
|
import { log, runsOf } from "./store.js";
|
|
@@ -7,7 +8,8 @@ import { log, runsOf } from "./store.js";
|
|
|
7
8
|
* The operator's side, run inside the deployer container by `kayra app …` and
|
|
8
9
|
* `kayra job …` over SSH. Reads runs/ and releases/ directly; anything that
|
|
9
10
|
* starts a run goes through the daemon's control port, so the queue stays the
|
|
10
|
-
* only place runs begin.
|
|
11
|
+
* only place runs begin. `--json` makes `runs` and rollback's list answer as
|
|
12
|
+
* data (answers.ts), which kayra draws.
|
|
11
13
|
*/
|
|
12
14
|
const platformDir = process.env["PLATFORM_DIR"] ?? "/opt/platform";
|
|
13
15
|
const runs = join(platformDir, "runs");
|
|
@@ -27,11 +29,16 @@ const releasesOf = (app) => {
|
|
|
27
29
|
return releases(existsSync(dir) ? readdirSync(dir) : []);
|
|
28
30
|
};
|
|
29
31
|
const commands = {
|
|
30
|
-
runs: ([app]) => {
|
|
32
|
+
runs: ([app], json) => {
|
|
31
33
|
const name = appName(app ?? "");
|
|
32
34
|
if (!name.ok)
|
|
33
35
|
return fail(name.error);
|
|
34
|
-
runsOf(runs, appOwner(name.value)).slice(0, 20)
|
|
36
|
+
const latest = runsOf(runs, appOwner(name.value)).slice(0, 20);
|
|
37
|
+
if (json) {
|
|
38
|
+
console.log(JSON.stringify(runsAnswer(name.value, latest, releasesOf(name.value)[0])));
|
|
39
|
+
return 0;
|
|
40
|
+
}
|
|
41
|
+
latest.forEach((run) => {
|
|
35
42
|
console.log([run.id, run.state.padEnd(8), (run.sha ?? "").slice(0, 12).padEnd(12), run.why.padEnd(8), run.what].join(" "));
|
|
36
43
|
});
|
|
37
44
|
return 0;
|
|
@@ -49,13 +56,18 @@ const commands = {
|
|
|
49
56
|
return 0;
|
|
50
57
|
},
|
|
51
58
|
deploy: ([app, ref]) => post("/deploy", { app, ref: ref ?? "", why: "deploy" }),
|
|
52
|
-
rollback: ([app, commit]) => {
|
|
59
|
+
rollback: ([app, commit], json) => {
|
|
53
60
|
const name = appName(app ?? "");
|
|
54
61
|
if (!name.ok)
|
|
55
62
|
return fail(name.error);
|
|
56
|
-
const
|
|
63
|
+
const all = releasesOf(name.value);
|
|
64
|
+
const [live, ...earlier] = all;
|
|
57
65
|
if (live === undefined)
|
|
58
66
|
return fail(`${name.value} has not been deployed yet`);
|
|
67
|
+
if (commit === undefined && json) {
|
|
68
|
+
console.log(JSON.stringify(releasesAnswer(name.value, all)));
|
|
69
|
+
return earlier.length === 0 ? 1 : 0;
|
|
70
|
+
}
|
|
59
71
|
if (commit === undefined) {
|
|
60
72
|
console.log(`${name.value} runs ${live.sha} (since ${live.time}). Earlier releases:`);
|
|
61
73
|
earlier.forEach((release) => {
|
|
@@ -73,5 +85,7 @@ const commands = {
|
|
|
73
85
|
export const ctl = async (args) => {
|
|
74
86
|
const [name, ...rest] = args;
|
|
75
87
|
const command = name === undefined ? undefined : commands[name];
|
|
76
|
-
return command === undefined
|
|
88
|
+
return command === undefined
|
|
89
|
+
? fail(`usage: ctl ${Object.keys(commands).join("|")} … [--json]`)
|
|
90
|
+
: command(rest.filter((word) => word !== "--json"), rest.includes("--json"));
|
|
77
91
|
};
|
package/cli/dist/gather.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
2
3
|
import { join } from "node:path";
|
|
3
4
|
import { yamlOf } from "./fleet.js";
|
|
4
5
|
import { capture } from "./interpret.js";
|
|
@@ -12,19 +13,22 @@ const mappingOf = (source) => {
|
|
|
12
13
|
: {};
|
|
13
14
|
};
|
|
14
15
|
const vaulted = (source) => source.startsWith("$ANSIBLE_VAULT");
|
|
15
|
-
/** A secrets file's values: plaintext as is, a vault only with the server's password file. */
|
|
16
|
+
/** A secrets file's values: plaintext as is, a vault only with the server's password file; a missing file has none. */
|
|
16
17
|
const secretsOf = async (server, path) => {
|
|
17
18
|
const source = text(path);
|
|
18
19
|
if (source === undefined)
|
|
19
|
-
return { kind: "
|
|
20
|
+
return { kind: "readable", values: {} };
|
|
20
21
|
if (!vaulted(source))
|
|
21
22
|
return { kind: "readable", values: mappingOf(source) };
|
|
22
|
-
if (server.vault.kind !== "file"
|
|
23
|
-
return { kind: "locked", reason: "vaulted, and no
|
|
23
|
+
if (server.vault.kind !== "file")
|
|
24
|
+
return { kind: "locked", reason: "vaulted, and server.yml names no vault_password_file", hint: "vault_password_file in server.yml lets kayra open it" };
|
|
25
|
+
const file = server.vault.file.replace(homedir(), "~");
|
|
26
|
+
if (!existsSync(server.vault.file))
|
|
27
|
+
return { kind: "locked", reason: `vaulted, and there is no ${file} here`, hint: "put the vault's password there" };
|
|
24
28
|
const opened = await capture(["ansible-vault", "view", "--vault-password-file", server.vault.file, path], "capture");
|
|
25
29
|
return opened.code === 0
|
|
26
30
|
? { kind: "readable", values: mappingOf(opened.stdout) }
|
|
27
|
-
: { kind: "locked", reason:
|
|
31
|
+
: { kind: "locked", reason: `${file} does not open it`, hint: "is it this vault's password?" };
|
|
28
32
|
};
|
|
29
33
|
const appPath = (entry) => {
|
|
30
34
|
const parsed = JSON.parse(entry);
|
package/cli/dist/interpret.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
2
|
import { text } from "node:stream/consumers";
|
|
3
|
+
import { all, err, flatMap, ok } from "./result.js";
|
|
4
|
+
import { active, bad, muted, ok as fine, strong } from "./ui/line.js";
|
|
5
|
+
import { position, silent } from "./ui/progress.js";
|
|
6
|
+
import { draw } from "./ui/views.js";
|
|
3
7
|
const spawned = async (argv, streams, env = {}) => {
|
|
4
8
|
const [program, ...args] = argv;
|
|
5
9
|
const child = spawn(program, args, {
|
|
@@ -19,80 +23,97 @@ const spawned = async (argv, streams, env = {}) => {
|
|
|
19
23
|
});
|
|
20
24
|
});
|
|
21
25
|
return exit instanceof Error
|
|
22
|
-
? { code: 127, stdout: "", stderr: exit.message }
|
|
23
|
-
: { code: exit, stdout: await stdout, stderr: await stderr };
|
|
26
|
+
? { code: 127, stdout: "", stderr: exit.message, started: false }
|
|
27
|
+
: { code: exit, stdout: await stdout, stderr: await stderr, started: true };
|
|
24
28
|
};
|
|
25
29
|
/** A command's stdout, for kayra to read; its stderr reaches the operator unless captured too. */
|
|
26
30
|
export const capture = (argv, stderr = "show", env = {}) => spawned(argv, { stdout: "capture", stderr }, env);
|
|
27
31
|
const answer = (probe) => spawned(probe.kind === "on-path" ? ["sh", "-c", 'command -v "$1"', "sh", probe.program] : probe.argv, { stdout: "discard", stderr: "capture" }, probe.kind === "exits-zero" ? probe.env : {});
|
|
28
|
-
/** Each query's answer in place of it, as `$(…)` would: one word, or split into many.
|
|
29
|
-
const resolve = async (argv
|
|
32
|
+
/** Each query's answer in place of it, as `$(…)` would: one word, or split into many. */
|
|
33
|
+
const resolve = async (argv) => {
|
|
30
34
|
const words = await Promise.all(argv.map(async (value) => {
|
|
31
35
|
if (typeof value === "string")
|
|
32
|
-
return [value];
|
|
36
|
+
return ok([value]);
|
|
33
37
|
const exit = await capture(value.argv, "show", value.env);
|
|
34
|
-
if (exit.code !== 0)
|
|
35
|
-
|
|
36
|
-
return undefined;
|
|
37
|
-
}
|
|
38
|
+
if (exit.code !== 0)
|
|
39
|
+
return err(`$(${value.argv.join(" ")}) failed: exit ${String(exit.code)}`);
|
|
38
40
|
const output = exit.stdout.replace(/\n+$/, "");
|
|
39
|
-
return value.words === "one" ? [output] : output.split(/\s+/).filter((word) => word !== "");
|
|
41
|
+
return ok(value.words === "one" ? [output] : output.split(/\s+/).filter((word) => word !== ""));
|
|
40
42
|
}));
|
|
41
|
-
|
|
42
|
-
|
|
43
|
+
return flatMap(all(words), (lists) => {
|
|
44
|
+
const [program, ...rest] = lists.flat();
|
|
45
|
+
return program === undefined ? err("the command is empty") : ok([program, ...rest]);
|
|
46
|
+
});
|
|
43
47
|
};
|
|
44
48
|
const lines = (text) => text
|
|
45
49
|
.trimEnd()
|
|
46
50
|
.split("\n")
|
|
47
51
|
.filter((line) => line !== "");
|
|
48
|
-
|
|
49
|
-
const
|
|
52
|
+
/** Under the step's own line. */
|
|
53
|
+
const detail = (line) => [" ", line];
|
|
54
|
+
const aside = (line) => [" ", muted(line)];
|
|
55
|
+
const hint = (text) => (text === undefined ? [] : [[" ", active("→"), " ", text]]);
|
|
56
|
+
const goOn = { failed: false, stopped: false, out: [], err: [] };
|
|
57
|
+
const check = async (step) => {
|
|
50
58
|
const exit = await answer(step.probe);
|
|
51
|
-
const
|
|
52
|
-
if (step.onFailure === "stop")
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
[
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
59
|
+
const said = [...lines(exit.stderr).map(detail), ...hint(step.hint)];
|
|
60
|
+
if (step.onFailure === "stop")
|
|
61
|
+
return exit.code === 0 ? goOn : { failed: true, stopped: true, out: [], err: said };
|
|
62
|
+
return exit.code === 0
|
|
63
|
+
? { ...goOn, out: [[fine("✓"), " ", step.label]] }
|
|
64
|
+
: { failed: true, stopped: false, out: [[bad("✗"), " ", step.label], ...said], err: [] };
|
|
65
|
+
};
|
|
66
|
+
const runStep = async (step) => {
|
|
67
|
+
const argv = await resolve(step.argv);
|
|
68
|
+
if (!argv.ok)
|
|
69
|
+
return { failed: true, stopped: true, why: "a query failed", out: [], err: [detail(argv.error)] };
|
|
70
|
+
const { stdout } = step;
|
|
71
|
+
// A quiet step's stderr waits until it is done, so it cannot tear through a spinner.
|
|
72
|
+
const quiet = stdout === "discard";
|
|
73
|
+
const exit = await spawned(argv.value, { stdout: typeof stdout === "string" ? stdout : "capture", stderr: quiet ? "capture" : "show" }, step.env);
|
|
74
|
+
if (!exit.started)
|
|
75
|
+
return { failed: true, stopped: true, why: "not started", out: [], err: [detail(`${argv.value[0]}: ${exit.stderr}`)] };
|
|
76
|
+
// Whatever it answered is shown, even when it failed: it may say why.
|
|
77
|
+
const out = typeof stdout === "string" ? [] : draw(stdout, exit.stdout, Date.now());
|
|
78
|
+
if (exit.code === 0)
|
|
79
|
+
return { ...goOn, out, err: lines(exit.stderr).map(aside) };
|
|
80
|
+
return { failed: true, stopped: true, why: `exit ${String(exit.code)}`, out, err: lines(exit.stderr).map(detail) };
|
|
64
81
|
};
|
|
65
82
|
const perform = async (step, io) => {
|
|
66
83
|
switch (step.kind) {
|
|
67
|
-
case "run":
|
|
68
|
-
|
|
69
|
-
if (argv === undefined)
|
|
70
|
-
return { failed: true, stopped: true };
|
|
71
|
-
const exit = await spawned(argv, { stdout: step.stdout, stderr: "show" }, step.env);
|
|
72
|
-
return exit.code === 0 ? goOn : { failed: true, stopped: true };
|
|
73
|
-
}
|
|
84
|
+
case "run":
|
|
85
|
+
return runStep(step);
|
|
74
86
|
case "check":
|
|
75
|
-
return check(step
|
|
87
|
+
return check(step);
|
|
76
88
|
case "confirm": {
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
return { failed: false, stopped: true };
|
|
89
|
+
io.err("");
|
|
90
|
+
io.err([" ", bad("▲"), " ", strong(step.warning)]);
|
|
91
|
+
const typed = await io.ask([" Type ", strong(step.expect), " to confirm: "]);
|
|
92
|
+
return typed === step.expect ? goOn : { failed: false, stopped: true, out: ["Aborted."], err: [] };
|
|
82
93
|
}
|
|
83
94
|
case "note":
|
|
84
|
-
|
|
85
|
-
return goOn;
|
|
95
|
+
return { ...goOn, out: [step.text] };
|
|
86
96
|
}
|
|
87
97
|
};
|
|
88
|
-
/**
|
|
89
|
-
|
|
90
|
-
|
|
98
|
+
/**
|
|
99
|
+
* Runs a plan step by step, until it ends or a step stops it, shown by `progress`.
|
|
100
|
+
* True if nothing failed and the operator did not interrupt it.
|
|
101
|
+
*/
|
|
102
|
+
export const interpret = async (plan, io, progress = silent, interrupted = () => false) => {
|
|
103
|
+
const ended = await progress.plan(plan, () => plan.reduce(async (previous, step, index) => {
|
|
91
104
|
const so = await previous;
|
|
92
|
-
if (so.
|
|
105
|
+
if (so.stop !== undefined)
|
|
93
106
|
return so;
|
|
94
|
-
const
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
107
|
+
const done = await progress.step(step, position(plan, index), () => perform(step, io));
|
|
108
|
+
// Ctrl-C reached the step's program too: how it ended says nothing about the server.
|
|
109
|
+
if (interrupted())
|
|
110
|
+
return { failures: so.failures, stop: { index, step, why: "interrupted" } };
|
|
111
|
+
done.out.forEach(io.out);
|
|
112
|
+
done.err.forEach(io.err);
|
|
113
|
+
const failures = so.failures + (done.failed ? 1 : 0);
|
|
114
|
+
if (done.stopped)
|
|
115
|
+
return { failures, stop: { index, step, why: done.failed ? "failed" : "declined" } };
|
|
116
|
+
return { failures };
|
|
117
|
+
}, Promise.resolve({ failures: 0 })));
|
|
118
|
+
return ended.failures === 0 && ended.stop?.why !== "interrupted";
|
|
98
119
|
};
|
package/cli/dist/main.js
CHANGED
|
@@ -2,20 +2,27 @@
|
|
|
2
2
|
import { run } from "@optique/run";
|
|
3
3
|
import { createInterface } from "node:readline/promises";
|
|
4
4
|
import { existsSync, readFileSync } from "node:fs";
|
|
5
|
+
import { homedir } from "node:os";
|
|
5
6
|
import { join, resolve } from "node:path";
|
|
6
7
|
import { absolutePath, fleetRoot, kayraRoot, within } from "./brand.js";
|
|
7
8
|
import { appCheck } from "./commands/app-check.js";
|
|
8
|
-
import { parser } from "./cli.js";
|
|
9
|
+
import { parser, runOptions } from "./cli.js";
|
|
9
10
|
import { doctor } from "./commands/doctor.js";
|
|
10
11
|
import * as server from "./commands/server.js";
|
|
11
|
-
import {
|
|
12
|
-
import { findings,
|
|
12
|
+
import { look, opentofu, statusJson, statusView } from "./commands/status.js";
|
|
13
|
+
import { findings, overall, validateJson, validateView } from "./commands/validate.js";
|
|
13
14
|
import { gather } from "./gather.js";
|
|
14
15
|
import { serverNamed } from "./fleet.js";
|
|
15
16
|
import { interpret } from "./interpret.js";
|
|
16
17
|
import { findFleetRoot, loadFleet } from "./load.js";
|
|
18
|
+
import { network } from "./net.js";
|
|
17
19
|
import { render } from "./plan.js";
|
|
18
|
-
import { flatMap, ok } from "./result.js";
|
|
20
|
+
import { flatMap, map, ok } from "./result.js";
|
|
21
|
+
import { explain } from "./ui/explain.js";
|
|
22
|
+
import { bad, paint } from "./ui/line.js";
|
|
23
|
+
import { framed, silent } from "./ui/progress.js";
|
|
24
|
+
import { screen, settle, watch } from "./ui/terminal.js";
|
|
25
|
+
import { truncate } from "./ui/text.js";
|
|
19
26
|
import { z } from "zod";
|
|
20
27
|
const here = absolutePath(process.cwd());
|
|
21
28
|
const engine = absolutePath(import.meta.dirname);
|
|
@@ -70,33 +77,77 @@ const plan = (fleet, command) => {
|
|
|
70
77
|
}
|
|
71
78
|
return flatMap(serverNamed(fleet, command.server), (target) => onServer(on, target, command));
|
|
72
79
|
};
|
|
80
|
+
const screens = { out: screen(process.stdout, process.env), err: screen(process.stderr, process.env) };
|
|
73
81
|
const io = {
|
|
74
|
-
out: (
|
|
75
|
-
console.log(
|
|
82
|
+
out: (text) => {
|
|
83
|
+
console.log(paint(text, screens.out.colors, screens.out.links));
|
|
76
84
|
},
|
|
77
|
-
err: (
|
|
78
|
-
console.error(
|
|
85
|
+
err: (text) => {
|
|
86
|
+
console.error(paint(text, screens.err.colors, screens.err.links));
|
|
79
87
|
},
|
|
80
88
|
ask: async (prompt) => {
|
|
81
89
|
const terminal = createInterface({ input: process.stdin, output: process.stderr });
|
|
82
|
-
|
|
90
|
+
// Ctrl-C at the prompt, or no more input: no answer, so nothing happens.
|
|
91
|
+
const answer = await new Promise((resolve) => {
|
|
92
|
+
terminal.once("SIGINT", () => {
|
|
93
|
+
resolve("");
|
|
94
|
+
});
|
|
95
|
+
terminal.once("close", () => {
|
|
96
|
+
resolve("");
|
|
97
|
+
});
|
|
98
|
+
void terminal.question(paint(prompt, screens.err.colors)).then(resolve, () => {
|
|
99
|
+
resolve("");
|
|
100
|
+
});
|
|
101
|
+
});
|
|
83
102
|
terminal.close();
|
|
84
103
|
return answer;
|
|
85
104
|
},
|
|
86
105
|
};
|
|
87
106
|
const fail = (message) => {
|
|
88
|
-
|
|
107
|
+
io.err(screens.err.live ? [bad("✗"), " ", message] : `kayra: ${message}`);
|
|
89
108
|
process.exit(1);
|
|
90
109
|
};
|
|
110
|
+
/** The heading's facts: what the server is, and which kayra runs. */
|
|
111
|
+
const invocation = (target) => ({
|
|
112
|
+
command: ["kayra", ...process.argv.slice(2).filter((word) => word !== "--dry-run")].join(" "),
|
|
113
|
+
...(target === undefined ? {} : { server: target.name }),
|
|
114
|
+
about: [...(target === undefined ? [] : [`${target.kind} on ${target.target}`, target.domain]), `kayra ${version}`],
|
|
115
|
+
});
|
|
116
|
+
/** Paths by the root they are under, the longest first: the engine may live inside the fleet. */
|
|
117
|
+
const shortener = (roots) => (text) => roots.toSorted(([a], [b]) => b.length - a.length).reduce((short, [path, name]) => short.replaceAll(path, name), text);
|
|
118
|
+
/** --dry-run: the plan as data, styled on a terminal, plain and copyable for a program. */
|
|
119
|
+
const show = (steps, about, short) => {
|
|
120
|
+
(screens.out.live ? explain(about, steps, short, screens.out.columns) : render(steps)).forEach(io.out);
|
|
121
|
+
};
|
|
122
|
+
/** Runs a plan, framed on stderr unless its output is the point; the exit status says how it went. */
|
|
123
|
+
const execute = async (steps, about, framing) => {
|
|
124
|
+
const interrupt = new AbortController();
|
|
125
|
+
// Ctrl-C reaches the step's program too; the plan stops once it gives up. A second one does not wait.
|
|
126
|
+
process.once("SIGINT", () => {
|
|
127
|
+
interrupt.abort();
|
|
128
|
+
process.once("SIGINT", () => process.exit(130));
|
|
129
|
+
});
|
|
130
|
+
const progress = framing
|
|
131
|
+
? framed(screens.err, (raw) => process.stderr.write(raw), about)
|
|
132
|
+
: silent;
|
|
133
|
+
const passed = await interpret(steps, io, progress, () => interrupt.signal.aborted);
|
|
134
|
+
// eslint-disable-next-line functional/immutable-data -- the exit status; process.exit() could cut piped output short
|
|
135
|
+
process.exitCode = interrupt.signal.aborted ? 130 : passed ? 0 : 1;
|
|
136
|
+
};
|
|
91
137
|
const found = flatMap(findFleetRoot(here.value), loadFleet);
|
|
92
138
|
// Outside a fleet only `app check` runs: it works in an app's repository.
|
|
93
139
|
const fleet = found.ok ? found : ok({ root: fleetRoot(here.value), servers: [] });
|
|
94
140
|
if (!fleet.ok)
|
|
95
141
|
fail(fleet.error);
|
|
96
142
|
else {
|
|
97
|
-
const args = run(parser(fleet.value),
|
|
143
|
+
const args = run(parser(fleet.value), runOptions(version));
|
|
98
144
|
if (!found.ok && args.command.name !== "app check")
|
|
99
145
|
fail(found.error);
|
|
146
|
+
const short = shortener([
|
|
147
|
+
[kayra, "<kayra>"],
|
|
148
|
+
...(found.ok ? [[fleet.value.root, "<fleet>"]] : []),
|
|
149
|
+
[homedir(), "~"],
|
|
150
|
+
]);
|
|
100
151
|
if (args.command.name === "app check") {
|
|
101
152
|
const root = absolutePath(resolve(here.value, args.command.dir ?? "."));
|
|
102
153
|
const manifestPath = root.ok ? join(root.value, "app.yml") : "";
|
|
@@ -104,32 +155,41 @@ else {
|
|
|
104
155
|
if (!steps.ok)
|
|
105
156
|
fail(steps.error);
|
|
106
157
|
else if (args.dryRun)
|
|
107
|
-
|
|
108
|
-
// eslint-disable-next-line functional/immutable-data -- the exit status; process.exit() could cut piped output short
|
|
158
|
+
show(steps.value, invocation(undefined), short);
|
|
109
159
|
else
|
|
110
|
-
|
|
160
|
+
await execute(steps.value, invocation(undefined), true);
|
|
111
161
|
}
|
|
112
162
|
else if (args.command.name === "status") {
|
|
113
|
-
|
|
163
|
+
const { json, offline } = args.command;
|
|
164
|
+
const { initial, updates } = look(fleet.value, opentofu, offline ? undefined : network(2_000));
|
|
165
|
+
// On a terminal the table is there at once, its cells filled in as the answers arrive; the report itself goes to stdout.
|
|
166
|
+
const draw = (looks, frame) => statusView(looks, { frame, room: screens.err.columns - 1, offline }).map((line) => paint(truncate(line, screens.err.columns - 1), screens.err.colors));
|
|
167
|
+
const looks = !json && screens.out.live && screens.err.live
|
|
168
|
+
? await watch((raw) => process.stderr.write(raw), initial, updates, draw)
|
|
169
|
+
: await settle(initial, updates);
|
|
170
|
+
(json
|
|
171
|
+
? [JSON.stringify(statusJson(looks), null, 2)]
|
|
172
|
+
: statusView(looks, { frame: "", room: screens.out.live ? screens.out.columns : Infinity, offline })).forEach(io.out);
|
|
114
173
|
}
|
|
115
174
|
else if (args.command.name === "validate") {
|
|
116
|
-
const chosen = args.command
|
|
175
|
+
const { server: chosen, json } = args.command;
|
|
117
176
|
const servers = fleet.value.servers.filter((each) => chosen === undefined || each.name === chosen);
|
|
118
|
-
const reports = await Promise.all(servers.map(async (each) => findings(await gather(fleet.value.root, each))));
|
|
119
|
-
|
|
120
|
-
report(servers[index]?.name ?? "", found).forEach(io.out);
|
|
121
|
-
});
|
|
177
|
+
const reports = await Promise.all(servers.map(async (each) => ({ server: each, findings: findings(await gather(fleet.value.root, each)) })));
|
|
178
|
+
(json ? [JSON.stringify(validateJson(reports), null, 2)] : validateView(reports)).forEach(io.out);
|
|
122
179
|
// eslint-disable-next-line functional/immutable-data -- the exit status; process.exit() could cut piped output short
|
|
123
|
-
process.exitCode = reports.some((
|
|
180
|
+
process.exitCode = reports.some((each) => overall(each.findings) === "problem") ? 1 : 0;
|
|
124
181
|
}
|
|
125
182
|
else {
|
|
126
|
-
const
|
|
183
|
+
const { command } = args;
|
|
184
|
+
const steps = map(plan(fleet.value, command), (each) => (args.verbose ? server.verbose(each) : each));
|
|
185
|
+
const target = "server" in command ? fleet.value.servers.find((each) => each.name === command.server) : undefined;
|
|
186
|
+
// ssh and the deployer's answers are the output itself: nothing around them.
|
|
187
|
+
const framing = command.name !== "ssh" && !isDeployer(command);
|
|
127
188
|
if (!steps.ok)
|
|
128
189
|
fail(steps.error);
|
|
129
190
|
else if (args.dryRun)
|
|
130
|
-
|
|
131
|
-
// eslint-disable-next-line functional/immutable-data -- the exit status; process.exit() could cut piped output short
|
|
191
|
+
show(steps.value, invocation(target), short);
|
|
132
192
|
else
|
|
133
|
-
|
|
193
|
+
await execute(steps.value, invocation(target), framing);
|
|
134
194
|
}
|
|
135
195
|
}
|