@b3os/cli 0.1.3 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -3
- package/dist/commands/app.d.ts +7 -0
- package/dist/commands/app.js +922 -0
- package/dist/commands/app.js.map +1 -0
- package/dist/commands/auth.d.ts +18 -0
- package/dist/commands/auth.js +64 -17
- package/dist/commands/auth.js.map +1 -1
- package/dist/commands/manifest.d.ts +50 -0
- package/dist/commands/manifest.js +316 -24
- package/dist/commands/manifest.js.map +1 -1
- package/dist/commands/requests.d.ts +8 -1
- package/dist/commands/requests.js +42 -6
- package/dist/commands/requests.js.map +1 -1
- package/dist/commands/tool.d.ts +46 -0
- package/dist/commands/tool.js +197 -0
- package/dist/commands/tool.js.map +1 -0
- package/dist/main.d.ts +1 -1
- package/dist/main.js +7 -2
- package/dist/main.js.map +1 -1
- package/dist/manifest/apply.d.ts +83 -0
- package/dist/manifest/apply.js +125 -0
- package/dist/manifest/apply.js.map +1 -0
- package/dist/manifest/grant.d.ts +1 -0
- package/dist/manifest/grant.js +3 -0
- package/dist/manifest/grant.js.map +1 -0
- package/dist/manifest/load.d.ts +4 -141
- package/dist/manifest/load.js +24 -268
- package/dist/manifest/load.js.map +1 -1
- package/dist/manifest/plan.d.ts +1 -52
- package/dist/manifest/plan.js +3 -627
- package/dist/manifest/plan.js.map +1 -1
- package/dist/manifest/record.d.ts +98 -0
- package/dist/manifest/record.js +233 -0
- package/dist/manifest/record.js.map +1 -0
- package/dist/manifest/skip.d.ts +1 -0
- package/dist/manifest/skip.js +3 -0
- package/dist/manifest/skip.js.map +1 -0
- package/dist/manifest/source.d.ts +48 -0
- package/dist/manifest/source.js +223 -0
- package/dist/manifest/source.js.map +1 -0
- package/package.json +6 -6
- package/schemas/b3os.v0.schema.json +0 -244
|
@@ -0,0 +1,922 @@
|
|
|
1
|
+
// b3os app status | logs | down: an application is the objects `b3os apply` tagged with its name (`b3os.app`), so
|
|
2
|
+
// these commands read and delete by tag (NOTES/deploy-platform/phase1-plan.md 1.3, last paragraph). No server-side
|
|
3
|
+
// application object exists in phase 1. Its addresses (`<label>.b3os.io`, D2) are the edge's: status reads them,
|
|
4
|
+
// open and link use them, and down stops them before it retires anything.
|
|
5
|
+
import { existsSync } from "node:fs";
|
|
6
|
+
import { dirname, resolve } from "node:path";
|
|
7
|
+
import { BLOCKED_WORDS, clockOf, deployAfter, listHosts, noHostsRoutes, ownAddress, parseRecreated, revCommit, routeHosts, StepError, serviceHealth, serviceProcess, sleep, validDepId, validDeployId, } from "@b3os/deploy";
|
|
8
|
+
import { APP_DOMAIN, LABEL, ROUTE_SETTLE_MS, ROUTE_STALE_MAX_MS } from "@b3os/deploy/hosts";
|
|
9
|
+
import { CliError, EXIT, intFlag, parse, splitSub, UsageError } from "../ctx.js";
|
|
10
|
+
import { all, listTagged, planRollback, retire, TAG } from "../manifest/apply.js";
|
|
11
|
+
import { loadManifest, MANIFEST_FILE } from "../manifest/load.js";
|
|
12
|
+
import * as git from "../manifest/source.js";
|
|
13
|
+
import { openBrowser, WINDOWS_OPENER_NOTE } from "./auth.js";
|
|
14
|
+
import { runPlanned } from "./manifest.js";
|
|
15
|
+
import { sandboxRequests } from "./requests.js";
|
|
16
|
+
const USAGE = `usage: b3os app <command>
|
|
17
|
+
status [--file FILE | --app NAME] the application's addresses (https://<label>.b3os.io: state, the generation
|
|
18
|
+
each serves, cookies this address did not set that were dropped), its service
|
|
19
|
+
generations (last 7 days), build snapshots and routines with their last runs,
|
|
20
|
+
found by their b3os.app tag; for each running generation its URL, its process,
|
|
21
|
+
its last call to B3OS, when its lease ends, its logs command, and why a
|
|
22
|
+
keepalive recreated it; for a service with none running, what starts it again
|
|
23
|
+
logs [APP] [--service NAME] [--follow]
|
|
24
|
+
a running service's output, each line with its time (UTC); --follow keeps
|
|
25
|
+
reading until the process exits
|
|
26
|
+
requests [APP] [--service NAME] [--failed] [--limit N]
|
|
27
|
+
the calls each service made to B3OS (models, scrapes, sandboxes), newest
|
|
28
|
+
first, from its running generation (else its newest); --failed keeps 4xx and
|
|
29
|
+
5xx; needs only sandboxes:read
|
|
30
|
+
open [APP] [--service NAME] open the application's address in the browser (a link address with a link
|
|
31
|
+
that ends in 60 s); without a terminal, or when no browser starts, print the
|
|
32
|
+
address. On Windows it starts the browser with rundll32, untested on Windows
|
|
33
|
+
link [APP] [--service NAME [--port N]] [--ttl S] [--rotate] [--yes]
|
|
34
|
+
print a link to the application's own address, or to the address of service
|
|
35
|
+
NAME (--port N when it has more than one), valid --ttl seconds (default
|
|
36
|
+
604800, 7 days; 60 to 7776000): anyone who has it gets in. --rotate first makes
|
|
37
|
+
every link stop working within 6 s (streams and WebSockets already open can run
|
|
38
|
+
up to an hour more), then makes the new link
|
|
39
|
+
down --app NAME [--yes] stop its addresses (each label stays the application's), wait 7 s, then
|
|
40
|
+
delete: each running generation (TERM, up to 30 s to exit, then delete; one
|
|
41
|
+
an address serves again by then is kept), then the routines, then the build
|
|
42
|
+
snapshots
|
|
43
|
+
rollback [APP] [--to DEPLOY] [--yes] [--dry-run]
|
|
44
|
+
deploy again the commit of the last deploy before the current one (the newest
|
|
45
|
+
a running service generation or a routine names) that went live with another
|
|
46
|
+
commit, or of --to, the exact deploy you name (app status lists them), from
|
|
47
|
+
this clone without a checkout: the working tree and HEAD stay as they are.
|
|
48
|
+
With platform:read the deploy records decide: a failed or undone deploy is
|
|
49
|
+
never the target, and the plan's first line says when the target went live.
|
|
50
|
+
Without it the service generations' tags decide: a failed deploy of a service
|
|
51
|
+
with no older generation can pass for one that went live, and the first line
|
|
52
|
+
says when its generation started. Read that line, or run --dry-run, before
|
|
53
|
+
--yes. Its objects say they are a rollback, so keepalive and the plan say
|
|
54
|
+
"running <commit> by rollback" until the next b3os apply deploys HEAD. With
|
|
55
|
+
the workflow's keepalive schedule on, a rollback (or b3os apply) run from a
|
|
56
|
+
clone can overlap a scheduled keepalive; the workflow run by hand with ref set
|
|
57
|
+
to the commit is the rollback that queues behind it
|
|
58
|
+
|
|
59
|
+
The application is the b3os.yaml \`name\` (default: read from ./${MANIFEST_FILE}). b3os apply --keepalive does not
|
|
60
|
+
recreate a generation that was deleted (b3os app down), unless an address still serves it; b3os apply deploys it
|
|
61
|
+
again.`;
|
|
62
|
+
function appName(v, required) {
|
|
63
|
+
if (typeof v.app === "string")
|
|
64
|
+
return v.app;
|
|
65
|
+
if (required)
|
|
66
|
+
throw new UsageError(`app down needs --app NAME (the b3os.yaml name), so it never guesses\n${USAGE}`);
|
|
67
|
+
const file = typeof v.file === "string" ? v.file : MANIFEST_FILE;
|
|
68
|
+
const l = loadManifest(file);
|
|
69
|
+
if (!l.manifest)
|
|
70
|
+
throw new UsageError(`${l.file}: cannot read the application's name; pass --app NAME`);
|
|
71
|
+
return l.manifest.name;
|
|
72
|
+
}
|
|
73
|
+
/** Each service's command as b3os.yaml declares it, when the file in reach is this application's (argv joined). */
|
|
74
|
+
function commandsOf(v, name) {
|
|
75
|
+
const out = new Map();
|
|
76
|
+
try {
|
|
77
|
+
const l = loadManifest(typeof v.file === "string" ? v.file : MANIFEST_FILE);
|
|
78
|
+
if (l.manifest?.name !== name)
|
|
79
|
+
return out;
|
|
80
|
+
for (const s of l.manifest.services ?? [])
|
|
81
|
+
out.set(s.name, Array.isArray(s.command) ? s.command.join(" ") : s.command);
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
// No file here, or not this application's: the oldest running process stands for the service.
|
|
85
|
+
}
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
/** A generation's processes (the service's is picked by @b3os/deploy serviceProcess: its command, else the oldest). */
|
|
89
|
+
async function processesOf(b3, sandbox) {
|
|
90
|
+
return (await b3.sandboxes.listProcesses(sandbox)).data;
|
|
91
|
+
}
|
|
92
|
+
/** The application's deploys, newest first, from its service generations' tags. */
|
|
93
|
+
function pastDeploys(sandboxes) {
|
|
94
|
+
const gens = sandboxes.filter((x) => (x.metadata?.[TAG.item] ?? "").startsWith("service/"));
|
|
95
|
+
const live = (x) => x.status === "running" || x.status === "paused";
|
|
96
|
+
// The undo of an apply that did not finish deletes the new generation while an older one of the service goes on.
|
|
97
|
+
const undone = (g) => g.stop_reason === "deleted" &&
|
|
98
|
+
gens.some((o) => o.id !== g.id &&
|
|
99
|
+
o.metadata?.[TAG.item] === g.metadata?.[TAG.item] &&
|
|
100
|
+
o.created_at < g.created_at &&
|
|
101
|
+
(live(o) || (o.stopped_at ?? "") > (g.stopped_at ?? "")));
|
|
102
|
+
const by = new Map();
|
|
103
|
+
for (const g of gens) {
|
|
104
|
+
const id = g.metadata?.[TAG.deploy];
|
|
105
|
+
if (!id)
|
|
106
|
+
continue;
|
|
107
|
+
const rev = g.metadata?.[TAG.rev] ?? "";
|
|
108
|
+
const d = by.get(id) ?? {
|
|
109
|
+
deploy: id,
|
|
110
|
+
commit: rev.includes("-dirty") ? null : revCommit(rev),
|
|
111
|
+
startedAt: null,
|
|
112
|
+
liveAt: null,
|
|
113
|
+
live: false,
|
|
114
|
+
served: false,
|
|
115
|
+
};
|
|
116
|
+
d.live ||= live(g);
|
|
117
|
+
d.served ||= live(g) || !undone(g);
|
|
118
|
+
const at = g.started_at ?? null;
|
|
119
|
+
if (at && (!d.startedAt || at < d.startedAt))
|
|
120
|
+
d.startedAt = at;
|
|
121
|
+
by.set(id, d);
|
|
122
|
+
}
|
|
123
|
+
return [...by.values()].sort((x, y) => (deployAfter(x.deploy, y.deploy) ? -1 : 1));
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* The records of the deploys `history` names (the `dep_` ids; a deploy b3os apply could not record has a CLI id and
|
|
127
|
+
* no record), by id, from List deploys; or why they could not be read: List deploys needs platform:read, which a
|
|
128
|
+
* deploying key need not hold (403), and an older API does not serve it.
|
|
129
|
+
*/
|
|
130
|
+
async function recordsOf(b3, app, history) {
|
|
131
|
+
const want = new Set(history.map((h) => h.deploy).filter((id) => validDepId(id)));
|
|
132
|
+
const rows = new Map();
|
|
133
|
+
let cursor = null;
|
|
134
|
+
try {
|
|
135
|
+
// Newest first; the tags reach back 7 days, so a few pages hold every deploy they name.
|
|
136
|
+
for (let page = 0; page < 10 && rows.size < want.size; page++) {
|
|
137
|
+
const r = await b3.request({
|
|
138
|
+
method: "GET",
|
|
139
|
+
path: "/v1/deploys",
|
|
140
|
+
query: { app, limit: 100, ...(cursor ? { cursor } : {}) },
|
|
141
|
+
edge: true,
|
|
142
|
+
timeoutMs: 10_000,
|
|
143
|
+
}, { maxRetries: 1 });
|
|
144
|
+
for (const d of r.data ?? [])
|
|
145
|
+
if (want.has(d.id))
|
|
146
|
+
rows.set(d.id, d);
|
|
147
|
+
cursor = r.next_cursor ?? null;
|
|
148
|
+
if (!cursor)
|
|
149
|
+
break;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
catch (e) {
|
|
153
|
+
const x = e;
|
|
154
|
+
return {
|
|
155
|
+
why: x.code ? `${x.status ?? "no answer"} ${x.code}` : (x.message ?? String(e)),
|
|
156
|
+
status: x.status ?? null,
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
return { rows };
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* The deploy that runs now: the newest one a live service generation or a routine of the application names. A
|
|
163
|
+
* routine carries the deploy that last published or tagged it, so a deploy that changed only routines (and kept
|
|
164
|
+
* every service's generation) is the current one, not the deploy before it.
|
|
165
|
+
*/
|
|
166
|
+
function currentDeploy(history, routines) {
|
|
167
|
+
const named = history.filter((h) => h.live);
|
|
168
|
+
for (const r of routines) {
|
|
169
|
+
const id = r.metadata?.[TAG.deploy];
|
|
170
|
+
const rev = r.metadata?.[TAG.rev] ?? "";
|
|
171
|
+
if (id)
|
|
172
|
+
named.push({ deploy: id, commit: rev.includes("-dirty") ? null : revCommit(rev) });
|
|
173
|
+
}
|
|
174
|
+
let current;
|
|
175
|
+
for (const d of named)
|
|
176
|
+
if (!current || deployAfter(d.deploy, current.deploy))
|
|
177
|
+
current = d;
|
|
178
|
+
return current ?? history[0];
|
|
179
|
+
}
|
|
180
|
+
/** A recreate's cause, as the console says it (apps/web src/lib/app-deploys.ts recreatedWords). */
|
|
181
|
+
const RECREATED_WHY = {
|
|
182
|
+
process: "after a crash",
|
|
183
|
+
crash: "after a crash",
|
|
184
|
+
lease: "after the lease ended",
|
|
185
|
+
probe: "after it failed its readiness probe",
|
|
186
|
+
stopped: "after it stopped",
|
|
187
|
+
};
|
|
188
|
+
/** What a visitor of an address that does not serve gets (review 3, tm17; decision 9): its state's own page. */
|
|
189
|
+
function stateWords(state) {
|
|
190
|
+
if (state === "blocked")
|
|
191
|
+
return BLOCKED_WORDS;
|
|
192
|
+
if (state === "claimed")
|
|
193
|
+
return "it is not live yet: visitors get 503 until a deploy switches it to a generation";
|
|
194
|
+
return "it is stopped: visitors get 503, the app is not running";
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Each service with no running (or paused) generation in the last 7 days, and what starts it again, in one line
|
|
198
|
+
* (DEFECTS 41): how its newest generation ended and when, then the command. A service taken down on purpose is
|
|
199
|
+
* started by b3os apply (keepalive leaves it down); one that hit its spend cap stops again until the cap is raised.
|
|
200
|
+
* With an address the address stays; without one a new generation has a new preview URL.
|
|
201
|
+
*/
|
|
202
|
+
function notRunning(sandboxes, rows) {
|
|
203
|
+
const out = [];
|
|
204
|
+
const seen = new Set();
|
|
205
|
+
const newest = [...sandboxes].sort((x, y) => y.created_at.localeCompare(x.created_at));
|
|
206
|
+
for (const x of newest) {
|
|
207
|
+
const item = x.metadata?.[TAG.item] ?? "";
|
|
208
|
+
if (!item.startsWith("service/"))
|
|
209
|
+
continue;
|
|
210
|
+
const service = item.slice(8);
|
|
211
|
+
if (seen.has(service))
|
|
212
|
+
continue;
|
|
213
|
+
seen.add(service);
|
|
214
|
+
if (newest.some((y) => y.metadata?.[TAG.item] === item && (y.status === "running" || y.status === "paused")))
|
|
215
|
+
continue;
|
|
216
|
+
const at = x.stopped_at ? ` at ${clockOf(x.stopped_at)}` : "";
|
|
217
|
+
const address = rows.find((h) => h.service === service && h.state !== "blocked");
|
|
218
|
+
const fresh = address ? `; its address ${address.url.replace(/\/+$/, "")} stays` : ", with a new URL";
|
|
219
|
+
const line = x.stop_reason === "deleted"
|
|
220
|
+
? `nothing runs: ${x.id} was deleted${at} (b3os app down, or by hand); b3os apply starts it again (keepalive leaves it down)`
|
|
221
|
+
: x.stop_reason === "budget"
|
|
222
|
+
? `nothing runs: ${x.id} stopped at its spend cap or for credits${at}; raise grant.spend_cap_usd (or add credits), then b3os apply`
|
|
223
|
+
: `nothing runs: ${x.stop_reason === "timeout"
|
|
224
|
+
? `the lease ended${at}`
|
|
225
|
+
: x.status === "failed" || x.stop_reason === "failed"
|
|
226
|
+
? `its microVM crashed${at}`
|
|
227
|
+
: `${x.id} is ${x.status}${x.stop_reason ? ` (${x.stop_reason})` : ""}${at}`}; b3os apply --keepalive starts a new generation${fresh}`;
|
|
228
|
+
out.push({ service, sandbox: x.id, stopped_at: x.stopped_at ?? null, line });
|
|
229
|
+
}
|
|
230
|
+
return out;
|
|
231
|
+
}
|
|
232
|
+
/** "12 s ago", "4 min ago", "2 h 5 min ago", "3 d ago": how long before now `iso` was. */
|
|
233
|
+
function ago(iso, now = Date.now()) {
|
|
234
|
+
const s = Math.max(0, Math.round((now - Date.parse(iso)) / 1000));
|
|
235
|
+
if (s < 60)
|
|
236
|
+
return `${s} s ago`;
|
|
237
|
+
const m = Math.floor(s / 60);
|
|
238
|
+
if (m < 60)
|
|
239
|
+
return `${m} min ago`;
|
|
240
|
+
if (m < 24 * 60)
|
|
241
|
+
return `${Math.floor(m / 60)} h${m % 60 ? ` ${m % 60} min` : ""} ago`;
|
|
242
|
+
return `${Math.floor(m / (24 * 60))} d ago`;
|
|
243
|
+
}
|
|
244
|
+
/** The newest call code in a generation made to B3OS, or null when it made none in the 7 days the log keeps. */
|
|
245
|
+
async function lastCall(b3, sandbox) {
|
|
246
|
+
return (await sandboxRequests(b3, sandbox, { limit: 1 })).data[0] ?? null;
|
|
247
|
+
}
|
|
248
|
+
/** Each service's generation whose calls `app requests` lists: the running one, else the newest. */
|
|
249
|
+
function generationByService(sandboxes) {
|
|
250
|
+
const out = runningByService(sandboxes);
|
|
251
|
+
for (const x of sandboxes) {
|
|
252
|
+
const item = x.metadata?.[TAG.item] ?? "";
|
|
253
|
+
if (item.startsWith("service/") && !out.has(item.slice(8)))
|
|
254
|
+
out.set(item.slice(8), x);
|
|
255
|
+
}
|
|
256
|
+
return out;
|
|
257
|
+
}
|
|
258
|
+
/** "in 42 min", "in 3 h 5 min", "12 min ago": from now to `iso`. */
|
|
259
|
+
function fromNow(iso, now = Date.now()) {
|
|
260
|
+
const min = Math.round((Date.parse(iso) - now) / 60_000);
|
|
261
|
+
const span = (m) => (m >= 60 ? `${Math.floor(m / 60)} h${m % 60 ? ` ${m % 60} min` : ""}` : `${m} min`);
|
|
262
|
+
return min >= 0 ? `in ${span(min)}` : `${span(-min)} ago`;
|
|
263
|
+
}
|
|
264
|
+
/** The newest running generation of each service, newest first as the node lists them. */
|
|
265
|
+
function runningByService(sandboxes) {
|
|
266
|
+
const out = new Map();
|
|
267
|
+
for (const x of sandboxes) {
|
|
268
|
+
const item = x.metadata?.[TAG.item] ?? "";
|
|
269
|
+
if (x.status === "running" && item.startsWith("service/") && !out.has(item.slice(8)))
|
|
270
|
+
out.set(item.slice(8), x);
|
|
271
|
+
}
|
|
272
|
+
return out;
|
|
273
|
+
}
|
|
274
|
+
/** Writes a log stream's text with each line's time in front: an event's lines carry its `ts`. */
|
|
275
|
+
function stamped(write) {
|
|
276
|
+
let lineStart = true;
|
|
277
|
+
return (ev) => {
|
|
278
|
+
const data = String(ev.data ?? "");
|
|
279
|
+
if (!data)
|
|
280
|
+
return;
|
|
281
|
+
const ts = typeof ev.ts === "string" ? ev.ts : "";
|
|
282
|
+
let out = "";
|
|
283
|
+
for (const part of data.split(/(?<=\n)/)) {
|
|
284
|
+
if (lineStart && ts)
|
|
285
|
+
out += `${ts} `;
|
|
286
|
+
out += part;
|
|
287
|
+
lineStart = part.endsWith("\n");
|
|
288
|
+
}
|
|
289
|
+
write(out);
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
/** The options of every `b3os app` subcommand, beside the global ones (also the name check's, test/names.test.ts). */
|
|
293
|
+
const APP_OPTIONS = {
|
|
294
|
+
app: { type: "string" },
|
|
295
|
+
file: { type: "string", short: "f" },
|
|
296
|
+
service: { type: "string" },
|
|
297
|
+
follow: { type: "boolean" },
|
|
298
|
+
failed: { type: "boolean" },
|
|
299
|
+
limit: { type: "string" },
|
|
300
|
+
to: { type: "string" },
|
|
301
|
+
"dry-run": { type: "boolean" },
|
|
302
|
+
"no-record": { type: "boolean" },
|
|
303
|
+
"allow-secret-files": { type: "boolean" },
|
|
304
|
+
ttl: { type: "string" },
|
|
305
|
+
rotate: { type: "boolean" },
|
|
306
|
+
port: { type: "string" },
|
|
307
|
+
};
|
|
308
|
+
async function app(ctx, argv) {
|
|
309
|
+
const [sub, rest] = splitSub(argv);
|
|
310
|
+
const a = parse(rest, APP_OPTIONS);
|
|
311
|
+
ctx.applyGlobals(a.values);
|
|
312
|
+
if (!sub || a.values.help) {
|
|
313
|
+
ctx.out(USAGE);
|
|
314
|
+
return a.values.help ? EXIT.OK : EXIT.USAGE;
|
|
315
|
+
}
|
|
316
|
+
const b3 = ctx.client();
|
|
317
|
+
switch (sub) {
|
|
318
|
+
case "status": {
|
|
319
|
+
const name = appName(a.values, false);
|
|
320
|
+
const sandboxes = await listTagged(b3, { [TAG.app]: name });
|
|
321
|
+
const snapshots = (await all(b3.sandboxes.listSnapshots({ limit: 100 }), 200)).filter((x) => x.metadata?.[TAG.app] === name);
|
|
322
|
+
const routines = (await all(b3.routines.listRoutines({ limit: 100 }))).filter((r) => r.metadata?.[TAG.app] === name);
|
|
323
|
+
const runs = new Map();
|
|
324
|
+
for (const r of routines)
|
|
325
|
+
runs.set(r.id, (await b3.routines.listRuns(r.id, { limit: 5 })).data.map((x) => ({
|
|
326
|
+
id: x.id,
|
|
327
|
+
status: x.status,
|
|
328
|
+
created_at: x.created_at,
|
|
329
|
+
})));
|
|
330
|
+
// Each running generation's processes: the service's pid, and the command that reads its log (harness run 1
|
|
331
|
+
// found the pid only in the apply's output); and whether it still runs: a running sandbox whose service process
|
|
332
|
+
// exited is down (harness run 3: the table said running while the URL answered 502). A key without
|
|
333
|
+
// sandboxes:run cannot list processes.
|
|
334
|
+
const commands = commandsOf(a.values, name);
|
|
335
|
+
const procs = new Map();
|
|
336
|
+
// And its last call to B3OS: whether the service is doing anything (harness run 1 could not tell).
|
|
337
|
+
const calls = new Map();
|
|
338
|
+
const why = (e) => (e instanceof Error ? e.message : String(e));
|
|
339
|
+
for (const [, x] of runningByService(sandboxes)) {
|
|
340
|
+
procs.set(x.id, await processesOf(b3, x.id).catch(why));
|
|
341
|
+
calls.set(x.id, await lastCall(b3, x.id).catch(why));
|
|
342
|
+
}
|
|
343
|
+
// The addresses (null: this API has none yet; a string: why they could not be read).
|
|
344
|
+
const hosts = await listHosts(b3, name).catch(why);
|
|
345
|
+
// The application's own address first (the edge's `primary` when it sends it), then the rest as listed.
|
|
346
|
+
const listed = Array.isArray(hosts) ? hosts : [];
|
|
347
|
+
const own = ownAddress(listed);
|
|
348
|
+
const rows = own ? [own, ...listed.filter((h) => h !== own)] : listed;
|
|
349
|
+
// The status of the sandbox a serving address points at: an address whose generation stopped answers 503.
|
|
350
|
+
const statusOf = (id) => id === null ? null : (sandboxes.find((x) => x.id === id)?.status ?? "gone");
|
|
351
|
+
const doc = {
|
|
352
|
+
object: "app_status",
|
|
353
|
+
app: name,
|
|
354
|
+
addresses: rows.map((h) => ({
|
|
355
|
+
label: h.label,
|
|
356
|
+
url: h.url,
|
|
357
|
+
service: h.service,
|
|
358
|
+
port: h.port,
|
|
359
|
+
access: h.access,
|
|
360
|
+
cookies: h.cookies,
|
|
361
|
+
state: h.state,
|
|
362
|
+
/** The application's own address (the edge's `primary`; from an edge before it, `base_label` null). */
|
|
363
|
+
primary: h === own,
|
|
364
|
+
sandbox: h.sandbox_id,
|
|
365
|
+
/** The served sandbox's status (`gone`: not among the application's sandboxes of the last 7 days). */
|
|
366
|
+
sandbox_status: statusOf(h.sandbox_id),
|
|
367
|
+
dropped_cookies: h.dropped_cookies ?? [],
|
|
368
|
+
})),
|
|
369
|
+
...(typeof hosts === "string" ? { addresses_error: hosts } : {}),
|
|
370
|
+
services: sandboxes
|
|
371
|
+
.filter((x) => (x.metadata?.[TAG.item] ?? "").startsWith("service/"))
|
|
372
|
+
.map((x) => {
|
|
373
|
+
const service = (x.metadata?.[TAG.item] ?? "").slice(8);
|
|
374
|
+
const list = procs.get(x.id);
|
|
375
|
+
const health = serviceHealth(x.status, Array.isArray(list) ? list : null, commands.get(service));
|
|
376
|
+
const p = list === undefined ? undefined : typeof list === "string" ? list : health.process;
|
|
377
|
+
const call = calls.get(x.id);
|
|
378
|
+
return {
|
|
379
|
+
service,
|
|
380
|
+
sandbox: x.id,
|
|
381
|
+
/** The sandbox's status. */
|
|
382
|
+
status: x.status,
|
|
383
|
+
/** The service's: the sandbox's, or `down` when it runs and the service's process exited. */
|
|
384
|
+
state: health.state,
|
|
385
|
+
...(health.exit ? { exit: health.exit } : {}),
|
|
386
|
+
stop_reason: x.stop_reason,
|
|
387
|
+
rev: x.metadata?.[TAG.rev] ?? null,
|
|
388
|
+
deploy: x.metadata?.[TAG.deploy] ?? null,
|
|
389
|
+
/** Why a keepalive made this generation (its `b3os.recreated` tag, DEFECTS 38), or null. */
|
|
390
|
+
recreated: parseRecreated(x.metadata?.[TAG.recreated]),
|
|
391
|
+
spec: x.metadata?.[TAG.spec] ?? null,
|
|
392
|
+
created_at: x.created_at,
|
|
393
|
+
expires_at: x.status === "running" ? x.expires_at : null,
|
|
394
|
+
// Each generation has its own preview URL; only a running one's answers.
|
|
395
|
+
urls: x.status === "running"
|
|
396
|
+
? (x.ports ?? []).flatMap((q) => (q.public && q.url ? [q.url] : []))
|
|
397
|
+
: [],
|
|
398
|
+
...(p !== undefined
|
|
399
|
+
? {
|
|
400
|
+
process: p && typeof p === "object"
|
|
401
|
+
? {
|
|
402
|
+
pid: p.pid,
|
|
403
|
+
cmd: p.cmd,
|
|
404
|
+
status: p.status,
|
|
405
|
+
exit_code: p.exit_code,
|
|
406
|
+
signal: p.signal ?? null,
|
|
407
|
+
exited_at: p.exited_at ?? null,
|
|
408
|
+
}
|
|
409
|
+
: null,
|
|
410
|
+
...(typeof p === "string" ? { process_error: p } : {}),
|
|
411
|
+
last_call: call && typeof call === "object"
|
|
412
|
+
? {
|
|
413
|
+
at: call.started_at,
|
|
414
|
+
method: call.method,
|
|
415
|
+
path: call.path,
|
|
416
|
+
status_code: call.status_code,
|
|
417
|
+
duration_ms: call.duration_ms,
|
|
418
|
+
request_id: call.id,
|
|
419
|
+
}
|
|
420
|
+
: null,
|
|
421
|
+
...(typeof call === "string" ? { last_call_error: call } : {}),
|
|
422
|
+
logs_command: `b3os app logs ${name} --service ${service} --follow`,
|
|
423
|
+
requests_command: `b3os app requests ${name} --service ${service}`,
|
|
424
|
+
}
|
|
425
|
+
: {}),
|
|
426
|
+
};
|
|
427
|
+
}),
|
|
428
|
+
builds: snapshots.map((x) => ({
|
|
429
|
+
service: (x.metadata?.[TAG.item] ?? "").replace(/^build\//, ""),
|
|
430
|
+
snapshot: x.id,
|
|
431
|
+
key: x.metadata?.[TAG.build] ?? null,
|
|
432
|
+
status: x.status,
|
|
433
|
+
created_at: x.created_at,
|
|
434
|
+
expires_at: x.expires_at,
|
|
435
|
+
})),
|
|
436
|
+
/** Each service with no running generation, and what starts it again (DEFECTS 41). */
|
|
437
|
+
not_running: notRunning(sandboxes, listed),
|
|
438
|
+
routines: routines.map((r) => ({
|
|
439
|
+
routine: r.name,
|
|
440
|
+
id: r.id,
|
|
441
|
+
version: r.version.number,
|
|
442
|
+
status: r.status,
|
|
443
|
+
paused_reason: r.paused_reason,
|
|
444
|
+
rev: r.metadata?.[TAG.rev] ?? null,
|
|
445
|
+
runs: runs.get(r.id) ?? [],
|
|
446
|
+
})),
|
|
447
|
+
};
|
|
448
|
+
ctx.result(doc, () => {
|
|
449
|
+
ctx.out(`application ${name}`);
|
|
450
|
+
if (doc.addresses.length || typeof hosts === "string") {
|
|
451
|
+
ctx.out("addresses");
|
|
452
|
+
if (typeof hosts === "string")
|
|
453
|
+
ctx.out(` not read: ${hosts}`);
|
|
454
|
+
for (const h of doc.addresses) {
|
|
455
|
+
ctx.out(` ${h.url} ${h.state}${h.sandbox ? ` ${h.sandbox}` : ""} (${h.service} port ${h.port}, access ${h.access}, cookies ${h.cookies.mode})`);
|
|
456
|
+
if (h.state === "serving" && h.sandbox && h.sandbox_status !== "running")
|
|
457
|
+
ctx.out(` serving ${h.sandbox}, which is ${h.sandbox_status}: the address answers 503; b3os apply or b3os apply --keepalive recreates it`);
|
|
458
|
+
if (h.state === "claimed")
|
|
459
|
+
ctx.out(" claimed: the next b3os apply switches it to the service's generation");
|
|
460
|
+
if (h.state === "stopped")
|
|
461
|
+
ctx.out(` stopped: the address answers 503; the next b3os apply switches it to the service's generation if b3os.yaml still gives port ${h.port} an address (access, or public: true)`);
|
|
462
|
+
if (h.state === "blocked")
|
|
463
|
+
ctx.out(` ${BLOCKED_WORDS}`);
|
|
464
|
+
// Cookies the app's server never got (cookies: isolated), by name, never a value: the edge counts every
|
|
465
|
+
// name this address did not set, a page script's or one another b3os.io site set for the whole domain.
|
|
466
|
+
for (const d of h.dropped_cookies)
|
|
467
|
+
ctx.out(` the cookie ${d.name}, not set by this address, was dropped on ${d.requests} ${d.requests === 1 ? "request" : "requests"} in the last 7 days; list it under cookies.script only if your own page script sets it`);
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
ctx.out("services (newest generation first, last 7 days)");
|
|
471
|
+
// STATUS is the service's: `down (exited TERM)` when the sandbox runs and its process does not.
|
|
472
|
+
ctx.table(doc.services.map((x) => ({ ...x, status: x.exit ? `down (exited ${x.exit.how})` : x.status })), ["service", "sandbox", "status", "stop_reason", "rev", "deploy", "expires_at"]);
|
|
473
|
+
for (const n of doc.not_running)
|
|
474
|
+
ctx.out(`${n.service}: ${n.line}`);
|
|
475
|
+
for (const x of doc.services) {
|
|
476
|
+
if (x.status !== "running")
|
|
477
|
+
continue;
|
|
478
|
+
ctx.out(`${x.service} (${x.sandbox})`);
|
|
479
|
+
if (x.recreated)
|
|
480
|
+
ctx.out(` recreated ${RECREATED_WHY[x.recreated.cause]} ${ago(x.created_at)}: ${x.recreated.reason}${x.recreated.by ? ` (keepalive ${x.recreated.by})` : ""}`);
|
|
481
|
+
for (const h of doc.addresses)
|
|
482
|
+
if (h.state === "serving" && h.sandbox === x.sandbox)
|
|
483
|
+
ctx.out(` address ${h.url}`);
|
|
484
|
+
for (const u of x.urls)
|
|
485
|
+
ctx.out(` public URL ${u}`);
|
|
486
|
+
if ("process" in x)
|
|
487
|
+
ctx.out(` process ${x.exit && x.process
|
|
488
|
+
? `${x.exit.pid} exited (${x.exit.how})${x.exit.at ? ` at ${x.exit.at} (${ago(x.exit.at)})` : ""}: ${x.process.cmd}`
|
|
489
|
+
: x.process
|
|
490
|
+
? `${x.process.pid} ${x.process.status}: ${x.process.cmd}`
|
|
491
|
+
: x.process_error
|
|
492
|
+
? `not read: ${x.process_error}`
|
|
493
|
+
: "none started"}`);
|
|
494
|
+
if (x.exit)
|
|
495
|
+
ctx.out(` down nothing serves${x.urls.length ? " (its URL answers 502)" : ""}; the next b3os apply or b3os apply --keepalive recreates it`);
|
|
496
|
+
if ("last_call" in x)
|
|
497
|
+
ctx.out(` last call ${x.last_call
|
|
498
|
+
? `${x.last_call.at} (${ago(x.last_call.at)}): ${x.last_call.method} ${x.last_call.path} ${x.last_call.status_code}`
|
|
499
|
+
: x.last_call_error
|
|
500
|
+
? `not read: ${x.last_call_error}`
|
|
501
|
+
: "none in the last 7 days"}`);
|
|
502
|
+
if (x.expires_at)
|
|
503
|
+
ctx.out(` lease ends ${x.expires_at} (${fromNow(x.expires_at)}); b3os apply --keepalive renews it, and so does each deploy`);
|
|
504
|
+
if ("logs_command" in x)
|
|
505
|
+
ctx.out(` logs ${x.logs_command}`);
|
|
506
|
+
if ("requests_command" in x)
|
|
507
|
+
ctx.out(` requests ${x.requests_command}`);
|
|
508
|
+
}
|
|
509
|
+
ctx.out("builds");
|
|
510
|
+
ctx.table(doc.builds, ["service", "snapshot", "key", "status", "created_at"]);
|
|
511
|
+
ctx.out("routines");
|
|
512
|
+
ctx.table(doc.routines.map((r) => ({ ...r, runs: r.runs.map((x) => x.status).join(" ") || "-" })), ["routine", "id", "version", "status", "rev", "runs"]);
|
|
513
|
+
});
|
|
514
|
+
return EXIT.OK;
|
|
515
|
+
}
|
|
516
|
+
case "logs": {
|
|
517
|
+
const name = a.positionals[0] ?? appName(a.values, false);
|
|
518
|
+
const running = runningByService(await listTagged(b3, { [TAG.app]: name }));
|
|
519
|
+
if (!running.size) {
|
|
520
|
+
// What starts it again, in one line (DEFECTS 41).
|
|
521
|
+
const all = await listTagged(b3, { [TAG.app]: name });
|
|
522
|
+
const rows = await listHosts(b3, name).catch(() => null);
|
|
523
|
+
const wanted = typeof a.values.service === "string" ? a.values.service : undefined;
|
|
524
|
+
const lines = notRunning(all, rows ?? []).filter((n) => !wanted || n.service === wanted);
|
|
525
|
+
ctx.warn(`${name} has no running generation${lines.length ? `: ${lines.map((n) => (lines.length > 1 ? `${n.service}: ${n.line}` : n.line)).join("; ")}` : ": b3os app status lists its generations"}`);
|
|
526
|
+
return EXIT.NOT_FOUND;
|
|
527
|
+
}
|
|
528
|
+
const names = [...running.keys()];
|
|
529
|
+
const svc = typeof a.values.service === "string" ? a.values.service : names.length === 1 ? names[0] : undefined;
|
|
530
|
+
if (!svc)
|
|
531
|
+
throw new UsageError(`${name} runs ${names.join(", ")}: pass --service NAME`);
|
|
532
|
+
const gen = running.get(svc);
|
|
533
|
+
if (!gen)
|
|
534
|
+
throw new UsageError(`${name} has no running generation of ${svc} (running: ${names.join(", ")})`);
|
|
535
|
+
const p = serviceProcess(await processesOf(b3, gen.id), commandsOf(a.values, name).get(svc));
|
|
536
|
+
if (!p) {
|
|
537
|
+
ctx.warn(`${svc} (${gen.id}) has no process: apply starts the service's command as a background process`);
|
|
538
|
+
return EXIT.NOT_FOUND;
|
|
539
|
+
}
|
|
540
|
+
ctx.info(`${svc}: ${gen.id}, process ${p.pid} (${p.status}): ${p.cmd}`);
|
|
541
|
+
const out = stamped((t) => ctx.io.stdout.write(t));
|
|
542
|
+
const err = stamped((t) => ctx.io.stderr.write(t));
|
|
543
|
+
for await (const ev of b3.sandboxes.streamLogs(gen.id, { pid: p.pid, follow: a.values.follow === true })) {
|
|
544
|
+
if (ctx.json)
|
|
545
|
+
ctx.printJsonLine(ev);
|
|
546
|
+
else if (ev.type === "log.stdout")
|
|
547
|
+
out(ev);
|
|
548
|
+
else if (ev.type === "log.stderr")
|
|
549
|
+
err(ev);
|
|
550
|
+
else if (ev.type === "process.exited")
|
|
551
|
+
ctx.info(`[process ${ev.pid} exited ${ev.exit_code ?? "by a signal"}]`);
|
|
552
|
+
}
|
|
553
|
+
return EXIT.OK;
|
|
554
|
+
}
|
|
555
|
+
case "requests": {
|
|
556
|
+
const name = a.positionals[0] ?? appName(a.values, false);
|
|
557
|
+
const limit = intFlag(a.values.limit, "--limit") ?? 20;
|
|
558
|
+
if (limit < 1 || limit > 100)
|
|
559
|
+
throw new UsageError("--limit is 1 to 100");
|
|
560
|
+
const gens = generationByService(await listTagged(b3, { [TAG.app]: name }));
|
|
561
|
+
if (!gens.size) {
|
|
562
|
+
ctx.warn(`${name} has no service generation in the last 7 days: b3os app status lists what it has`);
|
|
563
|
+
return EXIT.NOT_FOUND;
|
|
564
|
+
}
|
|
565
|
+
const wanted = typeof a.values.service === "string" ? a.values.service : undefined;
|
|
566
|
+
if (wanted && !gens.has(wanted))
|
|
567
|
+
throw new UsageError(`${name} has no generation of ${wanted} (services: ${[...gens.keys()].join(", ")})`);
|
|
568
|
+
const statuses = a.values.failed === true ? ["4xx", "5xx"] : [undefined];
|
|
569
|
+
const rows = [];
|
|
570
|
+
for (const [service, gen] of gens) {
|
|
571
|
+
if (wanted && service !== wanted)
|
|
572
|
+
continue;
|
|
573
|
+
ctx.info(`${service}: ${gen.id} (${gen.status})`);
|
|
574
|
+
for (const status of statuses) {
|
|
575
|
+
const page = await sandboxRequests(b3, gen.id, status ? { limit, status } : { limit });
|
|
576
|
+
for (const r of page.data)
|
|
577
|
+
rows.push({ ...r, service });
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
rows.sort((x, y) => y.started_at.localeCompare(x.started_at));
|
|
581
|
+
const data = rows.slice(0, limit);
|
|
582
|
+
ctx.result({ object: "app_requests", app: name, data }, () => ctx.table(data, ["started_at", "service", "method", "path", "status_code", "duration_ms", "id"]));
|
|
583
|
+
return EXIT.OK;
|
|
584
|
+
}
|
|
585
|
+
case "down": {
|
|
586
|
+
const name = appName(a.values, true);
|
|
587
|
+
const live = (await listTagged(b3, { [TAG.app]: name })).filter((x) => x.status === "running" || x.status === "paused");
|
|
588
|
+
const routines = (await all(b3.routines.listRoutines({ limit: 100 }))).filter((r) => r.metadata?.[TAG.app] === name);
|
|
589
|
+
const snapshots = (await all(b3.sandboxes.listSnapshots({ limit: 100 }), 200)).filter((x) => x.metadata?.[TAG.app] === name);
|
|
590
|
+
// The addresses serving now (none on an API without them). The edge refuses to delete a sandbox one points at.
|
|
591
|
+
const hosts = await listHosts(b3, name);
|
|
592
|
+
const serving = (hosts ?? []).filter((h) => h.state === "serving" && h.sandbox_id);
|
|
593
|
+
const n = live.length + routines.length + snapshots.length;
|
|
594
|
+
if (!n && !serving.length) {
|
|
595
|
+
ctx.info(`nothing tagged b3os.app ${name} in this project`);
|
|
596
|
+
return EXIT.OK;
|
|
597
|
+
}
|
|
598
|
+
for (const h of serving)
|
|
599
|
+
ctx.info(`address ${h.url} serves ${h.sandbox_id}: it stops, and the label stays ${name}'s`);
|
|
600
|
+
for (const x of live)
|
|
601
|
+
ctx.info(`sandbox ${x.id} ${x.metadata?.[TAG.item] ?? ""}`);
|
|
602
|
+
for (const r of routines)
|
|
603
|
+
ctx.info(`routine ${r.id} ${r.name}`);
|
|
604
|
+
for (const x of snapshots)
|
|
605
|
+
ctx.info(`snapshot ${x.id} ${x.metadata?.[TAG.item] ?? ""}`);
|
|
606
|
+
const what = serving.length
|
|
607
|
+
? `Stop ${serving.length === 1 ? "this address" : `these ${serving.length} addresses`} and delete these ${n} objects of ${name}?`
|
|
608
|
+
: `Delete these ${n} objects of ${name}?`;
|
|
609
|
+
if (!(await ctx.confirm(what))) {
|
|
610
|
+
ctx.warn("Nothing was deleted.");
|
|
611
|
+
return EXIT.OK;
|
|
612
|
+
}
|
|
613
|
+
const done = [];
|
|
614
|
+
if (serving.length) {
|
|
615
|
+
// Every label to nothing at once (compare-and-swap on what was read), then the apps Worker's cache time and
|
|
616
|
+
// a margin before any TERM, so no request already on its way meets a stopping server.
|
|
617
|
+
await routeHosts(b3, name, {
|
|
618
|
+
targets: serving.map((h) => ({ label: h.label, sandbox_id: null, port: h.port })),
|
|
619
|
+
if_current: Object.fromEntries(serving.map((h) => [h.label, h.sandbox_id])),
|
|
620
|
+
});
|
|
621
|
+
for (const h of serving) {
|
|
622
|
+
done.push({ kind: "address", id: h.label, how: "stopped" });
|
|
623
|
+
ctx.info(`stopped ${h.url} (it served ${h.sandbox_id})`);
|
|
624
|
+
}
|
|
625
|
+
if (serving.some((h) => live.some((x) => x.id === h.sandbox_id))) {
|
|
626
|
+
ctx.info(`waiting ${ROUTE_SETTLE_MS / 1000} s before TERM`);
|
|
627
|
+
await sleep(ROUTE_SETTLE_MS);
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
// Each TERM after a second read of the addresses (FOLLOWUPS 19, as retire, extras and prune do): an apply that
|
|
631
|
+
// ran meanwhile may have switched a label back to one of these, and a sandbox an address serves is kept.
|
|
632
|
+
const kept = [];
|
|
633
|
+
for (const x of live) {
|
|
634
|
+
if (hosts !== null) {
|
|
635
|
+
const now = await listHosts(b3, name).then((r) => r ?? [], (e) => (e instanceof Error ? e : new Error(String(e))));
|
|
636
|
+
const label = now instanceof Error ? undefined : now.find((h) => h.state === "serving" && h.sandbox_id === x.id)?.label;
|
|
637
|
+
if (now instanceof Error || label) {
|
|
638
|
+
const why = label ? `kept ${x.id}, which serves ${label}` : `kept ${x.id}: the addresses could not be read`;
|
|
639
|
+
kept.push({ id: x.id, why, ...(label ? { label } : {}) });
|
|
640
|
+
ctx.warn(why);
|
|
641
|
+
continue;
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
// Without the address routes (they answered off) a generation made for an address may still serve one
|
|
645
|
+
// (review 3, T5): it is deleted first, so the edge's delete guard answers before anything stops it. A refused
|
|
646
|
+
// delete keeps the sandbox, in the edge's words, and app down goes on with the rest.
|
|
647
|
+
const first = hosts === null && (x.ports ?? []).some((p) => p.addressed === true) ? "delete" : "term";
|
|
648
|
+
let how;
|
|
649
|
+
try {
|
|
650
|
+
how = await retire(b3, x, 30, 1000, undefined, first);
|
|
651
|
+
}
|
|
652
|
+
catch (e) {
|
|
653
|
+
if (!(e instanceof StepError) || e.code !== "sandbox_routed")
|
|
654
|
+
throw e;
|
|
655
|
+
const why = `kept ${x.id}: the edge refused its delete: ${e.message.replace(/^\S+ was not deleted: /, "")}`;
|
|
656
|
+
kept.push({ id: x.id, why });
|
|
657
|
+
ctx.warn(why);
|
|
658
|
+
continue;
|
|
659
|
+
}
|
|
660
|
+
done.push({ kind: "sandbox", id: x.id, how });
|
|
661
|
+
ctx.info(`deleted ${x.id} (${how})`);
|
|
662
|
+
}
|
|
663
|
+
for (const r of routines) {
|
|
664
|
+
await b3.routines.deleteRoutine(r.id);
|
|
665
|
+
done.push({ kind: "routine", id: r.id, how: "deleted" });
|
|
666
|
+
ctx.info(`deleted routine ${r.id} (${r.name})`);
|
|
667
|
+
}
|
|
668
|
+
for (const x of snapshots) {
|
|
669
|
+
await b3.sandboxes.deleteSnapshot(x.id);
|
|
670
|
+
done.push({ kind: "snapshot", id: x.id, how: "deleted" });
|
|
671
|
+
ctx.info(`deleted snapshot ${x.id}`);
|
|
672
|
+
}
|
|
673
|
+
const stopped = done.filter((d) => d.kind === "address").length;
|
|
674
|
+
ctx.result({
|
|
675
|
+
object: "app_down",
|
|
676
|
+
app: name,
|
|
677
|
+
deleted: done.filter((d) => d.kind !== "address"),
|
|
678
|
+
stopped: done.filter((d) => d.kind === "address"),
|
|
679
|
+
kept,
|
|
680
|
+
}, () => ctx.out(`${name}: ${stopped ? `stopped ${stopped} ${stopped === 1 ? "address" : "addresses"}, ` : ""}deleted ${done.length - stopped} objects${kept.length ? `; ${kept.map((k) => k.why).join("; ")}` : ""}`));
|
|
681
|
+
return EXIT.OK;
|
|
682
|
+
}
|
|
683
|
+
case "open": {
|
|
684
|
+
const name = a.positionals[0] ?? appName(a.values, false);
|
|
685
|
+
const hosts = await listHosts(b3, name);
|
|
686
|
+
if (hosts === null) {
|
|
687
|
+
ctx.warn(`this API has no app addresses yet: b3os app status prints each running generation's URL`);
|
|
688
|
+
return EXIT.NOT_FOUND;
|
|
689
|
+
}
|
|
690
|
+
const svc = typeof a.values.service === "string" ? a.values.service : undefined;
|
|
691
|
+
const mine = hosts.filter((h) => !svc || h.service === svc);
|
|
692
|
+
const row = ownAddress(mine) ?? mine[0];
|
|
693
|
+
if (!row) {
|
|
694
|
+
ctx.warn(`${name} has no address${svc ? ` for service ${svc}` : ""}: b3os apply claims one for a port with access (or public: true)`);
|
|
695
|
+
return EXIT.NOT_FOUND;
|
|
696
|
+
}
|
|
697
|
+
// What a visitor gets there now, by the state's own page (review 3, tm17; decision 9).
|
|
698
|
+
if (row.state !== "serving")
|
|
699
|
+
ctx.warn(`${row.url}: ${stateWords(row.state)}`);
|
|
700
|
+
if (ctx.json || !ctx.isTTY) {
|
|
701
|
+
ctx.result({ object: "app_address", app: name, url: row.url, state: row.state, access: row.access }, () => ctx.out(row.url));
|
|
702
|
+
if (row.access === "link")
|
|
703
|
+
ctx.info("a link address lets in only people with a link: b3os app link prints one");
|
|
704
|
+
return EXIT.OK;
|
|
705
|
+
}
|
|
706
|
+
// A link address lets the owner in with a link of 60 s (its cookie then lasts 30 days); the link is never
|
|
707
|
+
// printed, and it is on the opener's argument list for that minute only. The URL is the address itself, checked
|
|
708
|
+
// here: never a string the server chose as it is, and never through a shell.
|
|
709
|
+
const clean = `https://${row.label}.${APP_DOMAIN}`;
|
|
710
|
+
const url = row.access === "link" ? (await createLink(b3, name, { label: row.label, ttl_s: 60 })).url : `${clean}/`;
|
|
711
|
+
if (!openable(url, row.label))
|
|
712
|
+
throw new CliError(`the edge answered a URL that is not ${clean}/ with a link: not opened`, {
|
|
713
|
+
code: "unexpected_url",
|
|
714
|
+
exit: EXIT.SERVER,
|
|
715
|
+
hint: "b3os app link prints a link to the address",
|
|
716
|
+
});
|
|
717
|
+
if (process.platform === "win32")
|
|
718
|
+
ctx.info(WINDOWS_OPENER_NOTE);
|
|
719
|
+
if (!(await openBrowser(url))) {
|
|
720
|
+
ctx.out(clean);
|
|
721
|
+
ctx.info("no browser started here: b3os app link prints a link");
|
|
722
|
+
return EXIT.OK;
|
|
723
|
+
}
|
|
724
|
+
ctx.info(`opened ${clean}${row.access === "link" ? " with a link that ends in 60 s" : ""}`);
|
|
725
|
+
return EXIT.OK;
|
|
726
|
+
}
|
|
727
|
+
case "link": {
|
|
728
|
+
const name = a.positionals[0] ?? appName(a.values, false);
|
|
729
|
+
const ttl = intFlag(a.values.ttl, "--ttl") ?? 604_800;
|
|
730
|
+
if (ttl < 60 || ttl > 7_776_000)
|
|
731
|
+
throw new UsageError("--ttl is 60 to 7776000 seconds (90 days)");
|
|
732
|
+
const rotate = a.values.rotate === true;
|
|
733
|
+
// Review 2, sm19: the edge ends no stream it already let in; an open one runs until its hour is up.
|
|
734
|
+
const rotation = `Rotating makes every link to ${name} stop working within ${ROUTE_STALE_MAX_MS / 1000} s; streams and WebSockets already open can run up to an hour more.`;
|
|
735
|
+
if (rotate) {
|
|
736
|
+
ctx.warn(rotation);
|
|
737
|
+
if (!(await ctx.confirm(`Rotate the link secret of ${name}?`))) {
|
|
738
|
+
ctx.warn("Nothing was changed.");
|
|
739
|
+
return EXIT.OK;
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
const label = await linkLabel(b3, name, a.values);
|
|
743
|
+
if (label === null) {
|
|
744
|
+
ctx.warn("this API has no app addresses yet, so there is no link to make");
|
|
745
|
+
return EXIT.NOT_FOUND;
|
|
746
|
+
}
|
|
747
|
+
let link;
|
|
748
|
+
try {
|
|
749
|
+
link = await createLink(b3, name, {
|
|
750
|
+
...(label ? { label } : {}),
|
|
751
|
+
ttl_s: ttl,
|
|
752
|
+
...(rotate ? { rotate: true } : {}),
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
catch (e) {
|
|
756
|
+
if (!noHostsRoutes(e))
|
|
757
|
+
throw e;
|
|
758
|
+
ctx.warn("this API has no app addresses yet, so there is no link to make");
|
|
759
|
+
return EXIT.NOT_FOUND;
|
|
760
|
+
}
|
|
761
|
+
ctx.result(rotate ? { ...link, warning: rotation } : link, () => {
|
|
762
|
+
ctx.out(link.url);
|
|
763
|
+
ctx.info(`a link to https://${link.label}.b3os.io until ${link.expires_at}${link.rotated ? ", made after the rotation" : ""}: anyone who has it gets in, so send it only to the people it is for`);
|
|
764
|
+
});
|
|
765
|
+
return EXIT.OK;
|
|
766
|
+
}
|
|
767
|
+
case "rollback": {
|
|
768
|
+
const name = a.positionals[0] ?? appName(a.values, false);
|
|
769
|
+
const to = typeof a.values.to === "string" ? a.values.to : undefined;
|
|
770
|
+
if (to !== undefined && !validDepId(to) && !validDeployId(to))
|
|
771
|
+
throw new UsageError(`--to takes a deploy id (dep_… or YYYYMMDDTHHMMSSZ-<8 hex>): b3os app status lists them`);
|
|
772
|
+
// The clone it rolls back from: the one that holds b3os.yaml. Nothing in it is checked out or changed.
|
|
773
|
+
const file = resolve(typeof a.values.file === "string" ? a.values.file : MANIFEST_FILE);
|
|
774
|
+
const root = existsSync(file) ? git.repoOf(dirname(file)) : null;
|
|
775
|
+
if (!root)
|
|
776
|
+
throw new UsageError(`${file} is not in a git repository: run b3os app rollback in the clone ${name} deploys from (or pass --file)`);
|
|
777
|
+
const manifestInRepo = git.inRepo(root, file);
|
|
778
|
+
const history = pastDeploys(await listTagged(b3, { [TAG.app]: name }));
|
|
779
|
+
if (!history.length) {
|
|
780
|
+
ctx.warn(`${name} has no service generation in the last 7 days: nothing to roll back to`);
|
|
781
|
+
return EXIT.NOT_FOUND;
|
|
782
|
+
}
|
|
783
|
+
const routines = (await all(b3.routines.listRoutines({ limit: 100 }))).filter((r) => r.metadata?.[TAG.app] === name);
|
|
784
|
+
const current = currentDeploy(history, routines);
|
|
785
|
+
// A deploy's record says whether it went live (a failed or undone one never is the target) and when. Without
|
|
786
|
+
// the records the tags decide, and the plan gives the time its first generation started.
|
|
787
|
+
const records = await recordsOf(b3, name, history);
|
|
788
|
+
if ("why" in records)
|
|
789
|
+
ctx.warn(`deploy records: not read (${records.why}${records.status === 403 ? "; List deploys needs platform:read" : ""}): the history comes from the service generations' tags, so read the plan's first line before --yes`);
|
|
790
|
+
else
|
|
791
|
+
for (const h of history) {
|
|
792
|
+
const row = records.rows.get(h.deploy);
|
|
793
|
+
if (!row)
|
|
794
|
+
continue;
|
|
795
|
+
h.served = row.status === "live" || row.status === "superseded";
|
|
796
|
+
h.liveAt = row.live_at;
|
|
797
|
+
}
|
|
798
|
+
const served = history.filter((h) => h.served && h.commit);
|
|
799
|
+
const listed = served.map((h) => `${h.deploy} (${h.commit?.slice(0, 7)})`).join(", ");
|
|
800
|
+
const picked = to
|
|
801
|
+
? served.find((h) => h.deploy === to)
|
|
802
|
+
: served.find((h) => current && deployAfter(current.deploy, h.deploy) && h.commit !== current.commit);
|
|
803
|
+
// The deploy that shipped that commit (DEFECTS 39): the oldest of the deploys before it that ran the same commit
|
|
804
|
+
// one after another, not a keepalive's recreate of it. --to is the exact deploy named.
|
|
805
|
+
let target = picked;
|
|
806
|
+
if (!to && picked)
|
|
807
|
+
for (let i = served.indexOf(picked) + 1; served[i]?.commit === picked.commit; i++)
|
|
808
|
+
target = served[i];
|
|
809
|
+
if (!target) {
|
|
810
|
+
if (to)
|
|
811
|
+
throw new UsageError(`${to} is not a deploy of ${name} that went live in the last 7 days: ${listed}`);
|
|
812
|
+
ctx.warn(`nothing to roll back to: no deploy of ${name} before ${current?.deploy} in the last 7 days went live with another commit${listed ? ` (${listed})` : ""}`);
|
|
813
|
+
return EXIT.NOT_FOUND;
|
|
814
|
+
}
|
|
815
|
+
const commit = git.resolveCommit(root, target.commit);
|
|
816
|
+
if (!commit)
|
|
817
|
+
throw new CliError(`commit ${target.commit} (${target.deploy}) is not in this clone`, {
|
|
818
|
+
code: "commit_not_found",
|
|
819
|
+
exit: EXIT.NOT_FOUND,
|
|
820
|
+
hint: `fetch it (git fetch origin, or git fetch --unshallow in a shallow clone), then run b3os app rollback again; nothing was changed`,
|
|
821
|
+
});
|
|
822
|
+
// HEAD reverts the target when its tree (the application's folder) is the target's parent's (DEFECTS 39): the
|
|
823
|
+
// rollback then deploys again what HEAD took out, and the plan's first line says so.
|
|
824
|
+
const head = git.resolveCommit(root, "HEAD");
|
|
825
|
+
const parent = git.resolveCommit(root, `${commit}^`);
|
|
826
|
+
const dirRel = git.inRepo(root, dirname(file));
|
|
827
|
+
const reverts = (() => {
|
|
828
|
+
if (!head || !parent || head === commit)
|
|
829
|
+
return false;
|
|
830
|
+
try {
|
|
831
|
+
return git.treeHash(root, head, dirRel) === git.treeHash(root, parent, dirRel);
|
|
832
|
+
}
|
|
833
|
+
catch {
|
|
834
|
+
return false;
|
|
835
|
+
}
|
|
836
|
+
})();
|
|
837
|
+
const ac = new AbortController();
|
|
838
|
+
const options = {
|
|
839
|
+
mode: a.values["dry-run"] === true ? "dry-run" : "apply",
|
|
840
|
+
allowSecretFiles: a.values["allow-secret-files"] === true,
|
|
841
|
+
log: (line) => ctx.warn(line),
|
|
842
|
+
confirm: async () => true,
|
|
843
|
+
signal: ac.signal,
|
|
844
|
+
};
|
|
845
|
+
const planned = await planRollback(b3, root, manifestInRepo, {
|
|
846
|
+
commit,
|
|
847
|
+
deploy: target.deploy,
|
|
848
|
+
liveAt: target.liveAt,
|
|
849
|
+
startedAt: target.liveAt ? null : target.startedAt,
|
|
850
|
+
from: current?.commit?.slice(0, 7) ?? null,
|
|
851
|
+
...(reverts && head ? { revertedBy: head.slice(0, 7) } : {}),
|
|
852
|
+
}, ctx.credential().baseUrl, options);
|
|
853
|
+
if ("problem" in planned) {
|
|
854
|
+
ctx.warn(`${planned.problem}; nothing was changed`);
|
|
855
|
+
return EXIT.INVALID;
|
|
856
|
+
}
|
|
857
|
+
if (planned.state.app !== name)
|
|
858
|
+
throw new UsageError(`${manifestInRepo} at ${commit.slice(0, 12)} names the application ${planned.state.app}, not ${name}`);
|
|
859
|
+
return runPlanned(ctx, planned, options, ac, {
|
|
860
|
+
dry: a.values["dry-run"] === true,
|
|
861
|
+
noRecord: a.values["no-record"] === true,
|
|
862
|
+
});
|
|
863
|
+
}
|
|
864
|
+
default:
|
|
865
|
+
throw new UsageError(`unknown app command "${sub}"\n${USAGE}`);
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
/**
|
|
869
|
+
* Whether `url` is what `b3os app open` may hand a browser: exactly `https://<label>.<app domain>/`, with at most a
|
|
870
|
+
* `?b3os_link=` of a link token's shape (apps/edge/src/apphosts/link.ts LINK_TOKEN).
|
|
871
|
+
*/
|
|
872
|
+
export function openable(url, label) {
|
|
873
|
+
if (!LABEL.test(label))
|
|
874
|
+
return false;
|
|
875
|
+
const host = `${label}.${APP_DOMAIN}`.replace(/[.]/g, "\\.");
|
|
876
|
+
return new RegExp(`^https://${host}/(\\?b3os_link=(0|[1-9][0-9]{0,11})\\.[A-Za-z0-9_-]{43})?$`).test(url);
|
|
877
|
+
}
|
|
878
|
+
/**
|
|
879
|
+
* The label `b3os app link` asks for: undefined for the application's own (the edge picks it), the address of
|
|
880
|
+
* `--service` (and `--port`), or null when the API has no addresses.
|
|
881
|
+
*/
|
|
882
|
+
async function linkLabel(b3, app, v) {
|
|
883
|
+
const service = typeof v.service === "string" ? v.service : undefined;
|
|
884
|
+
const port = intFlag(v.port, "--port");
|
|
885
|
+
const rows = await listHosts(b3, app);
|
|
886
|
+
if (rows === null)
|
|
887
|
+
return null;
|
|
888
|
+
// No flag: the application's own address, the edge's `primary` row when it says which (else the edge picks).
|
|
889
|
+
if (service === undefined && port === undefined)
|
|
890
|
+
return rows.some((h) => h.primary !== undefined) ? ownAddress(rows)?.label : undefined;
|
|
891
|
+
const mine = rows.filter((h) => (service === undefined || h.service === service) && (port === undefined || h.port === port));
|
|
892
|
+
const what = `${service ? `service ${service}` : app}${port !== undefined ? ` port ${port}` : ""}`;
|
|
893
|
+
if (!mine.length)
|
|
894
|
+
throw new UsageError(`${app} has no address for ${what}: ${rows.map((h) => `${h.service} port ${h.port}`).join(", ") || "none yet"}`);
|
|
895
|
+
if (mine.length === 1)
|
|
896
|
+
return mine[0].label;
|
|
897
|
+
// The service holds the application's own label: that one, as b3os app link without --service gives.
|
|
898
|
+
const own = ownAddress(mine);
|
|
899
|
+
if (own)
|
|
900
|
+
return own.label;
|
|
901
|
+
throw new UsageError(`${what} has ${mine.length} addresses (ports ${mine.map((h) => h.port).join(", ")}): pass --port`);
|
|
902
|
+
}
|
|
903
|
+
/** `POST /v1/apps/{app}/hosts/link`: a link to one of the application's link addresses (its own by default). */
|
|
904
|
+
function createLink(b3, app, body) {
|
|
905
|
+
return b3.request({
|
|
906
|
+
method: "POST",
|
|
907
|
+
path: `/v1/apps/${encodeURIComponent(app)}/hosts/link`,
|
|
908
|
+
body,
|
|
909
|
+
edge: true,
|
|
910
|
+
timeoutMs: 15_000,
|
|
911
|
+
});
|
|
912
|
+
}
|
|
913
|
+
export const commands = [
|
|
914
|
+
{
|
|
915
|
+
name: "app",
|
|
916
|
+
summary: "Status, address, logs and rollback of an app (status, open, link, logs, requests, rollback, down)",
|
|
917
|
+
order: 245,
|
|
918
|
+
run: app,
|
|
919
|
+
options: APP_OPTIONS,
|
|
920
|
+
},
|
|
921
|
+
];
|
|
922
|
+
//# sourceMappingURL=app.js.map
|