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

A container in the cloud tree has a Logs tab with its recent lines #17958

opened this

Merged 22h 59m ago, live in production

mason/forge:mason/17953-a-container-in-the-cloud-tree-has-a-logs → main 0 commits fork

  • Merged. mason/17953-a-container-in-the-cloud-tree-has-a-logs was merged into main as 07d8c64.

Review

Sign in to review this change.
9 files changed +73 −11
docs/features/infra.md +1 −1
@@ -111,7 +111,7 @@ 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 and a container have two tabs, Facts and File (`?tab=file`; `[` and `]` in the terminal). 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 - **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.
115115 - **Keys.** j and k move, Enter opens, h and l (or the arrows) close and open, `/` filters and Enter goes to the first match.
116116 - **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).
117117 - **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/containers.ts +24 −1
@@ -12,7 +12,7 @@ import { listPinned } from "../core/pinned.ts";
1212 import type { User } from "../core/users.ts";
1313 import { nowWords } from "../games/gist.ts";
1414 import { heldOn, type Held } from "../games/hold.ts";
15 import { listBoxes, mayDo, roleOn, seesBox, servicesOf, type GameBox, type GameService } from "../games/store.ts";
15 import { boxNamed, listBoxes, logsOf, mayDo, roleOn, seesBox, servicesOf, type GameBox, type GameService } from "../games/store.ts";
1616 import { agoWords } from "../kernel/ago.ts";
1717
1818 export interface Container {
@@ -144,3 +144,26 @@ export function containersOf(db: Database, viewer: User | undefined, now = Date.
144144 }
145145 return out;
146146 }
147
148 /** How many of a container's newest lines its Logs tab shows. */
149 export const LOG_SHOWN = 200;
150
151 /**
152 * A container's recent lines as its box's last sync sent them, and what to say when there are none.
153 */
154 export interface Logged {
155 readonly lines: readonly string[];
156 readonly says: string;
157 }
158
159 /**
160 * The newest lines of one container, from the rows the sync already wrote: nothing is asked of the
161 * box. A line is the container's own text, so control characters (a terminal's escapes) are
162 * dropped; the page escapes the rest. With no lines, `says` names when the box last synced.
163 */
164 export function logsOfContainer(db: Database, c: Container, now = Date.now()): Logged {
165 const box = boxNamed(db, c.box);
166 const lines = box === undefined ? [] : logsOf(db, box.id, c.name, LOG_SHOWN).lines.map((l) => l.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, ""));
167 if (lines.length > 0) return { lines, says: "" };
168 return { lines, says: `No lines were synced for ${c.name}. Its box last synced ${c.readAt === "" ? "never" : agoWords(c.readAt, now)}.` };
169 }
src/cloud/tree.ts +6 −3
@@ -10,7 +10,7 @@
1010 * branch costs what its matches do at list price.
1111 */
1212
13 import type { Container, Inside } from "./containers.ts";
13 import type { Container, Inside, Logged } from "./containers.ts";
1414 import type { Filed } from "./declared_in.ts";
1515 import { dollars } from "./prices.ts";
1616 import { PROJECT_CLOUDS, readEveryMs, type AccountRead, type CloudResource, type ProjectView } from "./projects.ts";
@@ -371,6 +371,8 @@ export interface CloudView {
371371 readonly now: number;
372372 /** What declares each node, by its path joined with slashes (`declared_read.ts`); unset until a door reads it. */
373373 readonly files?: ReadonlyMap<string, readonly Filed[]>;
374 /** The open container's recent lines, set only when its Logs tab is asked for. */
375 readonly logs?: Logged;
374376 }
375377
376378 /**
@@ -601,11 +603,12 @@ export interface Fact {
601603 }
602604
603605 /** A node's tabs beside the tree. */
604 export type NodeTab = "facts" | "file";
606 export type NodeTab = "facts" | "file" | "logs";
605607
606608 /** The tabs a node has, in the order every door shows them; none when its facts are all there is. */
607609 export const tabsOf = (n: CloudNode): readonly { readonly id: NodeTab; readonly label: string }[] =>
608 n.container !== undefined || n.resource?.kind === "machine" ? [{ id: "facts", label: "Facts" }, { id: "file", label: "File" }] : [];
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" }] : [];
609612
610613 /** The tab asked for, when the node has it; its first otherwise, and for null, nothing asked. */
611614 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 +4 −1
@@ -22,6 +22,7 @@ import { machineView } from "../actions/machine_view.ts";
2222 import { INFRA_CSS, cloudPage, consolePage, endingPage, buildTray, placesRegion, composeForm, infraJs, buildPage, planTray, recordForm, resourcesPage, runningRegion, type ComposeState } from "../web/pages/infra.ts";
2323 import { cloudBranch, cloudList, cloudOverview, cloudPane, cloudTotal, cloudTreeJs } from "../web/pages/cloud_tree.ts";
2424 import { filesByNode } from "../cloud/declared_read.ts";
25 import { logsOfContainer } from "../cloud/containers.ts";
2526 import { nodeAt, tabOf, type CloudView } from "../cloud/tree.ts";
2627 import { pinnedBlock } from "./pinned_routes.ts";
2728 import type { Ctx, Handler } from "./context.ts";
@@ -90,7 +91,9 @@ async function infraResource(ctx: Ctx): Promise<Response> {
9091 if (part === "explorer") return fragment(cloudBranch(tree, node), { request: ctx.request });
9192 // Git is read only when the File tab is what was asked for.
9293 const tab = tabOf(node, ctx.url.searchParams.get("tab"));
93 const view = tab !== "file" ? tree : { ...tree, files: await timePhaseAsync(ctx.request, "files", () => filesByNode(ctx.app, ctx.auth.user, tree.whole, tree.now)) };
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;
96 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)) };
9497 const pane = timePhase(ctx.request, "render", () => cloudPane(view, node, tab));
9598 if (part === "1") return fragment(pane, { request: ctx.request });
9699 return page({ ctx, title: `${node.name} · Infrastructure`, wide: true, scriptJs: SCRIPT, styleCss: INFRA_CSS, body: resourcesPage(tree, node.path, pane), noDock: true });
src/http/mcp/tools/infra.ts +2 −1
@@ -3,6 +3,7 @@ import { noFileSays } from "../../../cloud/declared_in.ts";
33 import { filesByNode } from "../../../cloud/declared_read.ts";
44 import { infraCode } from "../../../cloud/infra_read.ts";
55 import { accountReads, projectsOf, projectsSays } from "../../../cloud/projects.ts";
6 import { logsOfContainer } from "../../../cloud/containers.ts";
67 import { CLOUD_PROPS, CONTAINER_COST, costLine, costliestOf, cutSays, factsOf, findingOf, listedOf, moneyWords, nodeAt, orderSays, pathIn, readingOf, tabsOf, tiesOf, type CloudNode } from "../../../cloud/tree.ts";
78 import { buildOf, cloudResources, firewallWant, gameWant, planDatabase, goneWords, infraOf, infraSays, machineOf, nameFor, planById, planCompose, planWants, startBuild } from "../../../actions/infra.ts";
89 import { machineView } from "../../../actions/machine_view.ts";
@@ -164,7 +165,7 @@ export const tool: Tool = {
164165 // Which file declares it and whether that agrees, as its File tab says.
165166 const filed = tabsOf(n).length === 0 ? [] : ((await filesByNode(ctx.app, user, v.value.whole, v.value.now)).get(n.path.join("/")) ?? []);
166167 const file = tabsOf(n).length === 0 ? {} : { file: filed.length === 0 ? [{ says: noFileSays(n) }] : filed.map(({ node: _, ...f }) => f) };
167 if (n.container !== undefined) return good({ says: `${n.name}: ${n.container.state}. ${CONTAINER_COST}`, facts: factsOf(v.value.root, n), ...file, readAt: n.readAt });
168 if (n.container !== undefined) return good({ says: `${n.name}: ${n.container.state}. ${CONTAINER_COST}`, facts: factsOf(v.value.root, n), ...file, logs: logsOfContainer(ctx.app.db, n.container).lines, readAt: n.readAt });
168169 const containers = r === undefined ? [] : n.children.flatMap(({ path, container: c }) => (c === undefined ? [] : [{ id: path.join("/"), name: c.name, state: c.state, cpu: c.cpu, memory: c.memory, uptime: c.uptime, page: c.page }]));
169170 return named(v.value.whole, r === undefined ? costliestOf(n) : [], args, `${n.name}: ${costLine(n) || moneyWords(n.money) || "no resources"}`, { facts: factsOf(v.value.root, n), ...file, ...(containers.length === 0 ? {} : { containers }), readAt: n.readAt, trouble: n.trouble.map((t) => t.says), ...(n.note === "" ? {} : { note: n.note }) });
170171 }
src/tui/screens/cloudtree.ts +3 −2
@@ -9,7 +9,7 @@ import { cloudResources, readProjectsNow } from "../../actions/infra.ts";
99 import { cloudCell, CLOUD_COLUMNS, FIRST_COLUMNS, firstCell, cloudName, CONTAINER_COST, containersSay, costLine, createdLabel, cutSays, factsOf, findingOf, isStale, largestCosts, listedOf, moneyMark, nodeAt, orderSays, readingOf, tabOf, tabsOf, unreadAccounts, unreadLine, unpricedSays, type CloudNode, type CloudView, type NodeTab } from "../../cloud/tree.ts";
1010 import { noFileSays, placeSays } from "../../cloud/declared_in.ts";
1111 import { filesByNode } from "../../cloud/declared_read.ts";
12 import { CONTAINER_COLUMNS, containerCell } from "../../cloud/containers.ts";
12 import { CONTAINER_COLUMNS, containerCell, logsOfContainer } from "../../cloud/containers.ts";
1313 import { dollars } from "../../cloud/prices.ts";
1414 import { keyOf } from "../../web/keymap.ts";
1515 import type { Ctx, Screen } from "../app/app.ts";
@@ -67,6 +67,7 @@ export function cloudLines(v: CloudView, n: CloudNode, width = 80, tab: NodeTab
6767 const has = tabsOf(n);
6868 if (has.length > 0) head.push("", has.map((t) => (t.id === tab ? `[${t.label}]` : ` ${t.label} `)).join(" "));
6969 if (tab === "file") return [...head, "", ...fileLines(v, n, unset)];
70 if (tab === "logs") return [...head, "", ...(v.logs === undefined || v.logs.lines.length === 0 ? [v.logs?.says ?? "Its lines are not here."] : v.logs.lines)];
7071 const facts = factsOf(v.whole, n).map((f) => `${f.label.padEnd(12)} ${f.value}`);
7172 if (n.container !== undefined) return [...head, "", ...facts, read];
7273 if (n.resource !== undefined)
@@ -102,7 +103,7 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen {
102103 /** The tab asked for; it stays while other nodes open, as far as they have it. */
103104 let tab: NodeTab | null = null;
104105 let filesSay = READING;
105 const lines = (v: CloudView, n: CloudNode): string[] => cloudLines(v, n, room, tabOf(n, tab), filesSay).flatMap((l) => (l.length <= room ? [l] : wrap(l, room)));
106 const lines = (v: CloudView, n: CloudNode): string[] => cloudLines(tabOf(n, tab) === "logs" && n.container !== undefined ? { ...v, logs: logsOfContainer(f.app.db, n.container) } : v, n, room, tabOf(n, tab), filesSay).flatMap((l) => (l.length <= room ? [l] : wrap(l, room)));
106107 let reading: CloudView | undefined;
107108 let kept: { readonly query: string; readonly view: CloudView | undefined } | undefined;
108109
src/web/pages/cloud_tree.ts +8
@@ -302,6 +302,7 @@ export function cloudPane(v: CloudView, n: CloudNode, tab: NodeTab = tabOf(n, nu
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`)}`;
304304 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>`;
305306 const facts = linkedFacts(v.whole, n);
306307 return html`<section id="code-pane" data-path="${n.name}" data-cloud-pane="resource">
307308 ${head}
@@ -319,6 +320,12 @@ export function cloudPane(v: CloudView, n: CloudNode, tab: NodeTab = tabOf(n, nu
319320 </section>`;
320321 }
321322
323 /** The Logs tab: the container's newest lines, each escaped as text, or why there are none. */
324 const logsTab = (v: CloudView): Html =>
325 v.logs === undefined || v.logs.lines.length === 0
326 ? html`<p class="muted">${v.logs?.says ?? "Its lines are not here."}</p>`
327 : html`<pre class="mono small" data-logs tabindex="0" aria-label="Recent lines">${v.logs.lines.join("\n")}</pre>`;
328
322329 /** What a resource is tied to, each end a link when the tree has it. */
323330 const ends = (t: Tie, v: CloudView): Html[] =>
324331 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>`}`);
@@ -335,6 +342,7 @@ export const CLOUD_TREE_CSS = `/* ---- the resource tree (#17532): the code brow
335342 @media (max-width: 899px) { [data-infra][data-open] > [data-cloud-total] { display: none; } }
336343 [data-cloud-pane] > h2 { margin: 12px 0 4px; }
337344 [data-cloud-pane], [data-costliest] { max-width: 720px; }
345 [data-logs] { max-height: 60vh; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; margin: 8px 0; }
338346 @media (min-width: 900px) { [data-infra] .code-layout { grid-template-columns: minmax(0, var(--ex-w, 400px)) auto minmax(0, 1fr); } }
339347 @media (min-width: 1200px) { [data-infra] .code-layout { grid-template-columns: minmax(0, var(--ex-w, 480px)) auto minmax(0, 1fr); } }
340348 /* On a phone the tree is the page: it scrolls with it, never inside it. */
test/cloud-containers.test.ts +22
@@ -332,3 +332,25 @@ test("a machine's containers are one table: name, state, CPU limit, memory limit
332332 expect(text).toMatch(/hub +running +1\.5 cores +2\.0 GiB +26 hours ago/);
333333 expect(text).toMatch(/survival +exited +— +— +—/);
334334 });
335
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 sync({ ...SYNC, logs: { hub: ["[Server] Done (3.2s)!", "<script>alert(1)</script>", "\u001b[31mred\u001b[0m"] } });
338 const page = await get(HUB, "?tab=logs");
339 expect(page).toContain("[Server] Done (3.2s)!");
340 expect(page).toContain("&lt;script&gt;alert(1)&lt;/script&gt;");
341 expect(page).not.toContain("<script>alert(1)");
342 expect(page).not.toContain("\u001b");
343 expect(page).toContain("Logs");
344 // A container with no synced lines says so, and when its box last synced.
345 const none = await get([...MACHINE, "container:survival"], "?tab=logs");
346 expect(none).toContain("No lines were synced for survival. Its box last synced");
347 // The terminal reads the same lines.
348 expect(cloudLines({ ...view(), logs: { lines: ["one line"], says: "" } }, at(HUB), 80, "logs").join("\n")).toContain("one line");
349 // The tool returns them too.
350 const token = createToken(app.db, alice.id, "logs", "admin").token;
351 expect((await mcpTool(servers.url, token, "infra", { action: "cloud", id: HUB.join("/") })).value.logs).toEqual(["[Server] Done (3.2s)!", "<script>alert(1)</script>", "[31mred[0m"]);
352 // Someone who is not an admin does not get the tab: the page is not found.
353 const bobs = await fetch(`${servers.url}/infra/-/${HUB.join("/")}?tab=logs`, { headers: { cookie: `forge_session=${createSession(app.db, bob.id).token}` } });
354 expect(bobs.status).toBeGreaterThanOrEqual(403);
355 expect(await bobs.text()).not.toContain("Server] Done");
356 });
test/cloud-files.test.ts +3 −2
@@ -146,9 +146,10 @@ test("each entry's own lines, in YAML and in JSON, without the blank after it",
146146 expect(servicesIn("services: [")).toBe("it is not valid YAML");
147147 });
148148
149 test("a machine and a container have Facts and File, in that order; nothing else has tabs", async () => {
149 test("a machine has Facts and File, a container adds Logs (#17953), in that order; nothing else has tabs", async () => {
150150 const v = await view();
151 for (const path of [BOX, HUB]) expect(tabsOf(nodeAt(v.whole, path)!).map((t) => t.id)).toEqual(["facts", "file"]);
151 expect(tabsOf(nodeAt(v.whole, BOX)!).map((t) => t.id)).toEqual(["facts", "file"]);
152 expect(tabsOf(nodeAt(v.whole, HUB)!).map((t) => t.id)).toEqual(["facts", "file", "logs"]);
152153 for (const path of [AT, [...AT, "volume:5"]]) expect(tabsOf(nodeAt(v.whole, path)!)).toEqual([]);
153154 expect(tabOf(nodeAt(v.whole, HUB)!, "nonsense")).toBe("facts");
154155 expect(tabOf(nodeAt(v.whole, AT)!, "file")).toBe("facts");

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

Keyboard shortcuts

Docs