Public: anyone can read this; the crew can change it.

Infrastructure: a game box container opens on its live log, with Restart, Stop and Start #17946

opened this

Merged 22h 46m ago, live in production

sold/container-logs → main 0 commits 2 threads · 2 unresolved

  • Merged. sold/container-logs was merged into main as db96b4c.

Review

Sign in to review this change.
6 files changed +54 −15
docs/features/infra.md +2 −1
@@ -111,7 +111,8 @@ Every DigitalOcean and Hetzner account is read into provider ▸ account ▸ pro
111111 - **A resource** is at `/infra/-/<cloud>/<account>/<project>/<id>`, beside the tree, or full width on a phone: cost, state, what it is attached to and what it holds (an address its balancer, NAT gateway or task; an ECS service its balancer and cluster; a balancer the services known behind it, "Shared by" when there are several; a link AWS does not state is not drawn, which does not mean nothing uses it), an AWS list price's day, what it leaves out and whose file it is (or why there is none), the app an AWS resource is part of and how that is known (nothing when it is not), what it was made from, who made it, when it was created, when it was read, and Ask about this (a talk with those facts, fenced as data).
112112 - **Created.** An EC2 instance's is when its primary network interface was attached, which is its first launch: AWS's `launchTime` is its last start and is not shown. "not known" when the cloud does not state a date, or the forge does not read one (an AWS address, function, table, cluster or zone). An S3 bucket's is "Created, or last changed", because AWS moves it when the bucket changes, its policy for one; a filter by `created:` uses that date all the same.
113113 - **Containers.** A machine that is a game box opens into its containers (`src/cloud/containers.ts`), at `/infra/-/<cloud>/<account>/<project>/machine:<id>/container:<name>`: state, health, CPU, memory, how long it has been up, its image (the box owner's only) and a link to its page under /games, where it is changed. It is what the box's last full sync wrote, and nothing is asked of the box. The sync carries `upSince`, `memLimitMiB` and `cpuLimit` for each service, from one `docker inspect` that asks for those fields by name and never the whole answer, which holds the env (`services` in `src/games/agent.sh`): a limit of 0 is "no limit set", and one left out (an older agent) is "not known", as is a value out of its range. Without `upSince` the uptime is the diagnosis' word. "not known" is also said of figures the box could not measure, and of everything once the box is silent for two minutes ("not known: running 3 hours ago"). A container is in no count and no sum. The machine is the one the box's own row names, never found by name. Who sees which follows the games roles, and nobody sees the waker. A held box (docs/features/games.md) says so on its machine: in its row, and first in its facts with the next step. A machine's pane lists its containers as one table, on the page and in the terminal alike (`CONTAINER_COLUMNS`, `containerCell`): name (a link to the container), state, CPU limit, memory limit and started, as an ago. A value not known, or no limit set, is an em dash, never 0.
114 - **File.** A machine has two tabs, Facts and File (`?tab=file`; `[` and `]` in the terminal); a container has a third, Logs (`?tab=logs`), its newest 200 lines as its box last synced them (nothing is fetched from the box; control characters are dropped, the page escapes the rest), or a sentence saying none were synced and when the box last did. The `infra` tool returns the same lines as `logs` for a container. Only an admin sees the tree. File says which lines of which file declare the thing, links to them, and says whether that agrees with what the forge knows (`src/cloud/declared_in.ts`, `declared_read.ts`). Two kinds of file are read: an app's `infra.json`, against the forge's own record of the machine (the cloud is not asked), and a game box's compose file, against the commit the box last said it runs. When the branch is at another commit the tab says so, since its lines may not be what runs; a silent box is "not known". Of a service it shows the image, ports, volumes and the names of its environment, never a value. A thing in neither file is "in no file the forge reads", one that is part of a stack is "not known", and one in a repository the reader may not read is "in a file you cannot read", with nothing of it shown. The join goes through the forge's own rows and never by a resource's name. On the branch that is followed, the file's own page says to a forge admin "Declares 3: …" with a link to each node; to anyone else it is as before. Nothing is written.
114 - **Logs.** A game box's container has a Logs tab with the same live reader and console as its service's page on `/games/<box>/<service>`, with Restart, and Stop and Start under More, for an operator of it (they ask first when someone is on, as there). Someone with no role on the box is told so (`containerConsole` in `src/web/pages/games.ts`).
115 - **File.** A machine has two tabs, Facts and File (`?tab=file`; `[` and `]` in the terminal); a container has a third, Logs (`?tab=logs`): on the page, for someone with a role on its box, the live reader below; otherwise, in the terminal and in the `infra` tool, its newest 200 lines as its box last synced them (nothing is fetched from the box; control characters are dropped, the page escapes the rest), or a sentence saying none were synced and when the box last did. The `infra` tool returns the same lines as `logs` for a container. Only an admin sees the tree. File says which lines of which file declare the thing, links to them, and says whether that agrees with what the forge knows (`src/cloud/declared_in.ts`, `declared_read.ts`). Two kinds of file are read: an app's `infra.json`, against the forge's own record of the machine (the cloud is not asked), and a game box's compose file, against the commit the box last said it runs. When the branch is at another commit the tab says so, since its lines may not be what runs; a silent box is "not known". Of a service it shows the image, ports, volumes and the names of its environment, never a value. A thing in neither file is "in no file the forge reads", one that is part of a stack is "not known", and one in a repository the reader may not read is "in a file you cannot read", with nothing of it shown. The join goes through the forge's own rows and never by a resource's name. On the branch that is followed, the file's own page says to a forge admin "Declares 3: …" with a link to each node; to anyone else it is as before. Nothing is written.
115116 - **Keys.** j and k move, Enter opens, h and l (or the arrows) close and open, `/` filters and Enter goes to the first match.
116117 - **States.** No account (a link to /settings/cloud), not read yet, a failed read (one line: when, why, and how old what is shown is), a kind that could not be read with its reason (on its project and on the account, which says where; under the headline's sum, "Not everything is listed: 1 kind not read" links to that account, and text doors name it; a billed account's gaps count too, and change no sum), and a reading older than three of its duty's intervals. A project's note ("R2 is not switched on for this account") is a plain line and no trouble, on its account too when that has one project. **Check the account** (`a` in the terminal) opens the account: see [Cloud accounts](cloud.md#what-was-not-read-17637).
117118 - **Terminal.** `:` then Cloud resources, or `/` in Infra (`src/tui/screens/cloudtree.ts`): the same list, filter and facts, the List price, Old price, Price from and No price lines among them (both read `factsOf`); `tab` changes pane, `w` opens the web page, `P` reads every account.
src/cloud/tree.ts +5 −2
@@ -607,8 +607,11 @@ export type NodeTab = "facts" | "file" | "logs";
607607
608608 /** The tabs a node has, in the order every door shows them; none when its facts are all there is. */
609609 export const tabsOf = (n: CloudNode): readonly { readonly id: NodeTab; readonly label: string }[] =>
610 n.container !== undefined ? [{ id: "facts", label: "Facts" }, { id: "file", label: "File" }, { id: "logs", label: "Logs" }]
611 : n.resource?.kind === "machine" ? [{ id: "facts", label: "Facts" }, { id: "file", label: "File" }] : [];
610 n.container !== undefined
611 ? [{ id: "facts", label: "Facts" }, { id: "file", label: "File" }, { id: "logs", label: "Logs" }]
612 : n.resource?.kind === "machine"
613 ? [{ id: "facts", label: "Facts" }, { id: "file", label: "File" }]
614 : [];
612615
613616 /** The tab asked for, when the node has it; its first otherwise, and for null, nothing asked. */
614617 export const tabOf = (n: CloudNode, asked: string | null): NodeTab => (tabsOf(n).find((t) => t.id === asked) ?? tabsOf(n)[0])?.id ?? "facts";
src/http/infra_routes.ts +10 −4
@@ -25,10 +25,15 @@ import { filesByNode } from "../cloud/declared_read.ts";
2525 import { logsOfContainer } from "../cloud/containers.ts";
2626 import { nodeAt, tabOf, type CloudView } from "../cloud/tree.ts";
2727 import { pinnedBlock } from "./pinned_routes.ts";
28 import { containerConsole } from "../web/pages/games.ts";
29 import { LOG_READER_CSS, logReaderJs } from "../web/log_reader.ts";
30 import { terminalBlocksJs } from "../web/terminal_blocks.ts";
2831 import type { Ctx, Handler } from "./context.ts";
2932 import type { Router } from "./router.ts";
3033
3134 const SCRIPT = `${codeJs}\n${cloudTreeJs}\n${liveRegionsJs}\n${behaviorsJs}\n${infraJs}`;
35 /** A container's page also draws its game service's log reader and console. */
36 const CONTAINER_SCRIPT = `${SCRIPT}\n${logReaderJs}\n${terminalBlocksJs}`;
3237
3338 /** The compose as a form sends it, each field bounded. */
3439 const composeOf = (get: (k: string) => string): ComposeState => ({
@@ -91,12 +96,13 @@ async function infraResource(ctx: Ctx): Promise<Response> {
9196 if (part === "explorer") return fragment(cloudBranch(tree, node), { request: ctx.request });
9297 // Git is read only when the File tab is what was asked for.
9398 const tab = tabOf(node, ctx.url.searchParams.get("tab"));
94 // Lines are read from what the last sync stored, only when the Logs tab is asked for.
95 const logs = tab === "logs" && node.container !== undefined ? logsOfContainer(ctx.app.db, node.container) : undefined;
99 const game = node.container === undefined ? undefined : containerConsole(ctx, node.container.box, node.name);

tabOf still defaults to Logs from tabsOf regardless of this result; the default must depend on whether game is defined. Also the terminal (src/tui/screens/cloudtree.ts cloudLines) has no logs branch: the Logs tab shows Facts there and has no Restart/Stop/Start.

100 // A container's live reader needs a role on its box; without one its last synced lines are shown, read only when asked.
101 const logs = tab === "logs" && node.container !== undefined && game === undefined ? logsOfContainer(ctx.app.db, node.container) : undefined;
96102 const view = logs !== undefined ? { ...tree, logs } : tab !== "file" ? tree : { ...tree, files: await timePhaseAsync(ctx.request, "files", () => filesByNode(ctx.app, ctx.auth.user, tree.whole, tree.now)) };
97 const pane = timePhase(ctx.request, "render", () => cloudPane(view, node, tab));
103 const pane = timePhase(ctx.request, "render", () => cloudPane(view, node, tab, game));
98104 if (part === "1") return fragment(pane, { request: ctx.request });
99 return page({ ctx, title: `${node.name} · Infrastructure`, wide: true, scriptJs: SCRIPT, styleCss: INFRA_CSS, body: resourcesPage(tree, node.path, pane), noDock: true });
105 return page({ ctx, title: `${node.name} · Infrastructure`, wide: true, scriptJs: game === undefined ? SCRIPT : CONTAINER_SCRIPT, styleCss: game === undefined ? INFRA_CSS : INFRA_CSS + LOG_READER_CSS, body: resourcesPage(tree, node.path, pane), noDock: true });
100106 }
101107
102108 async function render(
src/web/pages/cloud_tree.ts +5 −3
@@ -281,7 +281,7 @@ function billLine(n: CloudNode): Html {
281281 }
282282
283283 /** What is open beside the tree: a branch's costliest resources, or one resource's facts or file. */
284 export function cloudPane(v: CloudView, n: CloudNode, tab: NodeTab = tabOf(n, null)): Html {
284 export function cloudPane(v: CloudView, n: CloudNode, tab: NodeTab = tabOf(n, null), game?: { readonly power: Html | null; readonly logs: Html }): Html {
285285 const r = n.resource;
286286 if (r === undefined && n.container === undefined) {
287287 return html`<section id="code-pane" data-path="${n.name}" data-cloud-pane="${n.level}">
@@ -298,11 +298,11 @@ export function cloudPane(v: CloudView, n: CloudNode, tab: NodeTab = tabOf(n, nu
298298 }
299299 const has = tabsOf(n);
300300 const head = html`${trail(v, n)}
301 <h2>${n.name}</h2>
301 <div class="cloud-head"><h2>${n.name}</h2>${game?.power ?? null}</div>
302302 ${sum(v, n)}
303303 ${has.length === 0 ? null : tabs(has.map((t) => ({ label: t.label, href: cloudHref(n.path, v.q, t.id), current: t.id === tab })), `${n.name}'s tabs`)}`;
304 if (tab === "logs") return html`<section id="code-pane" data-path="${n.name}" data-cloud-pane="resource">${head}${game?.logs ?? logsTab(v)}</section>`;
304305 if (tab === "file") return html`<section id="code-pane" data-path="${n.name}" data-cloud-pane="resource">${head}${fileTab(v, n)}</section>`;
305 if (tab === "logs") return html`<section id="code-pane" data-path="${n.name}" data-cloud-pane="resource">${head}${logsTab(v)}</section>`;
306306 const facts = linkedFacts(v.whole, n);
307307 return html`<section id="code-pane" data-path="${n.name}" data-cloud-pane="resource">
308308 ${head}
@@ -331,6 +331,8 @@ const ends = (t: Tie, v: CloudView): Html[] =>
331331 t.to.map((e, i) => html`${i > 0 ? ", " : ""}${e.node === undefined ? html`<span class="mono">${e.id.slice(e.id.indexOf(":") + 1)}</span>` : html`<a href="${cloudHref(e.node.path, v.q)}">${e.node.name}</a>`}`);
332332
333333 export const CLOUD_TREE_CSS = `/* ---- the resource tree (#17532): the code browser's column, wider, with a cost at each row's end ---- */
334 .cloud-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
335 .cloud-head h2 { margin: 0; }
334336 .cloud-total { margin: 0 0 4px; }
335337 .cloud-sum { margin: 0 0 4px; }
336338 .cloud-sum > .num { font-weight: 600; }
src/web/pages/games.ts +25
@@ -515,6 +515,31 @@ function grantsBlock(ctx: Ctx, box: GameBox): Html {
515515 </section>`;
516516 }
517517
518 /**
519 * A game box's container as Infrastructure opens it (#17939): the service's own log reader and
520 * console, and its power buttons for an operator, the same parts /games/<box>/<service> draws.
521 * Undefined for someone with no role on it.
522 */
523 export function containerConsole(ctx: Ctx, boxName: string, service: string): { readonly power: Html | null; readonly logs: Html } | undefined {
524 const box = boxNamed(ctx.app.db, boxName);
525 if (box === undefined || !SERVICE_NAME.test(service)) return undefined;
526 const role = roleOn(ctx.app.db, ctx.auth.user, box.id, service);
527 if (!mayDo(role, "viewer")) return undefined;
528 const act = mayDo(role, "operator");
529 const base = `/games/${box.name}/${service}`;
530 const blocks = serviceBlocks(ctx.app, box.id, service, act);
531 const seen = servicesOf(ctx.app.db, box.id).find((s) => s.name === service);
532 return {
533 power: act ? power(box, service, seen) : null,
534 logs: html`<p class="game-now" aria-live="polite">${nowWords(seen, powerNow(ctx.app.db, box.id, service))}</p>
535 ${logReader(logViewOf(ctx.url, base, service), gameLogPage(ctx.app.db, box.id, service), gameLogAge(ctx.app.db, box.id, service), {
536 stream: `${base}/stream`,
537 footer: blocksForm(blocks, box, `${base}/command`, { stream: `${base}/stream`, input: act, label: `Command for ${service}`, placeholder: "say hello", says: `Each command goes to ${service}'s own console at the box's next check-in.` }),
538 })}
539 <p class="muted small"><a href="${base}">${service}'s page</a> has its people, settings, mods and numbers.</p>`,
540 };
541 }
542
518543 // GET /games/:box/:service
519544 export async function gameServicePage(ctx: Ctx): Promise<Response> {
520545 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
test/cloud-containers.test.ts +7 −5
@@ -278,8 +278,9 @@ test("the page: the machine's row opens, its pane lists them, and one container
278278 const hub = await get(HUB);
279279 expect(hub).toContain('<a href="/games/mc/hub">');
280280 expect(hub).toContain("Its cost is inside its machine&#39;s.");
281 // Read only here.
282 expect(hub.split('id="code-pane"')[1]!.split("</section>")[0]).not.toContain('method="post"');
281 // An operator's power buttons on every tab: the game page's own, which ask first when someone is on.
282 const own = hub.split('id="code-pane"')[1]!.split("</section>")[0]!;
283 expect(own).toContain('action="/games/mc/hub/power"');
283284 });
284285
285286 test("the terminal: the same rows and facts, by keys", async () => {
@@ -333,7 +334,7 @@ test("a machine's containers are one table: name, state, CPU limit, memory limit
333334 expect(text).toMatch(/survival +exited +— +— +—/);
334335 });
335336
336 test("a container's Logs tab shows its synced lines as text, says so when none, and is an admin's alone (#17953)", async () => {
337 test("a container's Logs tab shows its lines as text, live for its box's owner, says so when none, and is an admin's alone (#17953)", async () => {
337338 sync({ ...SYNC, logs: { hub: ["[Server] Done (3.2s)!", "<script>alert(1)</script>", "\u001b[31mred\u001b[0m"] } });
338339 const page = await get(HUB, "?tab=logs");
339340 expect(page).toContain("[Server] Done (3.2s)!");
@@ -341,9 +342,10 @@ test("a container's Logs tab shows its synced lines as text, says so when none,
341342 expect(page).not.toContain("<script>alert(1)");
342343 expect(page).not.toContain("\u001b");
343344 expect(page).toContain("Logs");
344 // A container with no synced lines says so, and when its box last synced.
345 // An admin owns the box, so the page is its live reader and console; a container with no lines says so.
346 expect(page).toContain('data-stream="/games/mc/hub/stream"');
345347 const none = await get([...MACHINE, "container:survival"], "?tab=logs");
346 expect(none).toContain("No lines were synced for survival. Its box last synced");
348 expect(none).toContain("Nothing has been written yet");
347349 // The terminal reads the same lines.
348350 expect(cloudLines({ ...view(), logs: { lines: ["one line"], says: "" } }, at(HUB), 80, "logs").join("\n")).toContain("one line");
349351 // The tool returns them too.

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs