1import { type InferResponseType, parseResponse } from "hono/client";
2import ArrowDown from "lucide-solid/icons/arrow-down";
3import ArrowUp from "lucide-solid/icons/arrow-up";
4import BatteryWarning from "lucide-solid/icons/battery-warning";
5import HardDrive from "lucide-solid/icons/hard-drive";
6import Power from "lucide-solid/icons/power";
7import Rocket from "lucide-solid/icons/rocket";
8import ShieldCheck from "lucide-solid/icons/shield-check";
9import Trash from "lucide-solid/icons/trash";
10import Undo2 from "lucide-solid/icons/undo-2";
11import { createMemo, createResource, createRoot, createSignal, For, type JSX, onCleanup, Show } from "solid-js";
12import type { Domain, GpuShare } from "../types/vms.ts";
13import { type Health, type HostInfo, type Live, type Me, type Series, type ServiceSummary, trouble } from "../types/model.ts";
14import { api, queries, reason } from "../api.ts";
15import { Ago } from "../components/Ago.tsx";
16import { AppIcon } from "../components/AppIcon.tsx";
17import { Donut } from "../components/Donut.tsx";
18import { GpuSwitch } from "../components/GpuSwitch.tsx";
19import { lastGood, Loaded } from "../components/Loaded.tsx";
20import { Meter } from "../components/Meter.tsx";
21import { OpenApp } from "../components/OpenApp.tsx";
22import { RangePicker } from "../components/Metric.tsx";
23import { Status, StatusLabel } from "../components/Status.tsx";
24import { type Reading, Strip } from "../components/Strip.tsx";
25import { TabBar } from "../components/TabBar.tsx";
26import { toast } from "../components/Toast.tsx";
27import { ago, bytes, celsius, cores, duration, percent, plural, rate, watts } from "../format.ts";
28import { stream } from "../live.ts";
29import snowflake from "../snowflake.svg";
30import { confirmDestroyStage, followRun, type StageInfo } from "./Deploys.tsx";
31import "./Overview.css";
32
33/** How busy the machine is and what needs a look, polled for the overview and the sidebar's badge. */
34export const status = createRoot(() => {
35 const [data, { refetch }] = createResource(() => parseResponse(api.status.$get()));
36 setInterval(refetch, 30_000);
37 return { latest: lastGood(data), refetch };
38});
39
40/** Opens an app; its tagline is the tooltip, for people who don't know the app by name. */
41function AppCard(props: {
42 app: Pick<ServiceSummary, "id" | "name" | "icon" | "tagline" | "url">;
43 /** Null while it's unknown. */
44 health: Health | null;
45 children?: JSX.Element;
46}) {
47 return (
48 <a class="app" classList={{
49 out: props.health !== null && props.health !== "healthy" && props.health !== "degraded",
50 down: props.health === "down",
51 degraded: props.health === "degraded",
52 }}
53 href={props.app.url ?? undefined} target="_blank" rel="noreferrer" data-tip={props.app.tagline ?? undefined}>
54 <AppIcon id={props.app.id} name={props.app.name} icon={props.app.icon} />
55 <span class="name">{props.app.name}</span>
56 {props.children}
57 </a>
58 );
59}
60
61/** Snow gets her own line, except while previewing the dashboard as someone else. */
62function Greeting(props: { me: Me }) {
63 return (
64 <h1 class="greeting">
65 {props.me.name === "snow" && !props.me.viewing
66 ? "hi snow. keep it up."
67 : `hi ${props.me.name}… welcome to my cozy little snow globe…`}
68 </h1>
69 );
70}
71
72function Issues(props: { admin: boolean }) {
73 return (
74 <Show when={status.latest()?.issues?.length}>
75 <ul class="changes issues" aria-label="Needs a look">
76 <For each={status.latest()!.issues!}>
77 {(issue) => (
78 <li class="warn">
79 <Status health={issue.health} />
80 <span class="what"><Show when={props.admin} fallback={issue.service.name}>
81 <a href={`/services/${issue.service.id}`}>{issue.service.name}</a>
82 </Show> {issue.health} <span class="muted">{issue.failing}</span></span>
83 </li>
84 )}
85 </For>
86 </ul>
87 </Show>
88 );
89}
90
91/** The front door for everyone without machine metrics: their apps, a word when one is out, and how busy it all is. */
92function Home(props: { me: Me }) {
93 const [apps, { refetch }] = queries.launcher.use();
94 const timer = setInterval(refetch, 30_000);
95 onCleanup(() => clearInterval(timer));
96 return (
97 <div class="page home">
98 <img class="globe" src={snowflake} alt="" />
99 <Greeting me={props.me} />
100 <Show when={status.latest()}>
101 {(now) => (
102 <p class="load" tabIndex={0} data-tip={`${percent(now().load)} load over 5 min`}>
103 <Meter value={now().load} max={100} />
104 the snow globe is {now().load < 25 ? "quiet" : now().load < 60 ? "busy" : "very busy"}
105 </p>
106 )}
107 </Show>
108 <Loaded data={apps} what="your apps" retry={refetch} skeleton={
109 <div class="apps">
110 <For each={Array(4)}>
111 {() => <div class="app"><span class="skeleton icon" /><span class="skeleton" style={{ width: "72px" }} /></div>}
112 </For>
113 </div>
114 }>
115 {(list) => (
116 <Show when={list().length} fallback={
117 <div class="empty"><p>No apps shared with you yet.</p><p>They show up here once Clover gives you access.</p></div>
118 }>
119 <nav class="apps" aria-label="Your apps">
120 <For each={list()}>
121 {(app) => (
122 <AppCard app={app} health={app.health}>
123 <Show when={app.health !== "healthy" && app.health}>
124 {(health) => <StatusLabel health={health() === "stopped" ? "down" : trouble(health()) ? health() : "restarting"} />}
125 </Show>
126 </AppCard>
127 )}
128 </For>
129 </nav>
130 </Show>
131 )}
132 </Loaded>
133 <Issues admin={false} />
134 </div>
135 );
136}
137
138type Storage = InferResponseType<typeof api.storage.$get, 200>;
139
140const latestOf = (series: Series | undefined) => series?.v.findLast((v) => v != null) ?? undefined;
141
142/** The machine at a glance, for admins and the metrics group: apps, what changed, storage, and the machine's charts. */
143function Dashboard(props: { me: Me }) {
144 const admin = props.me.sections.includes("admin");
145 stream.start();
146 const [launcher, { refetch: refetchLauncher }] = queries.launcher.use();
147 const [host, { refetch: refetchHost }] = queries.host.use();
148 const [storage, { refetch: refetchStorage }] = queries.storage.use();
149 const [services, { refetch: refetchServices }] = queries.services.use();
150 const [deploys, { refetch: refetchDeploys }] = queries.deploys.use(() => (admin ? undefined : false));
151 const [vms, { refetch: refetchVms }] = queries.vms.use(() => (props.me.sections.includes("vms") ? undefined : false));
152 const timer = setInterval(() => [refetchLauncher, refetchHost, refetchStorage, refetchServices, refetchDeploys]
153 .forEach((refetch) => refetch()), 60_000);
154 const gpuGuest = () => lastGood(vms)()?.domains.find((vm): vm is Domain & { gpu: GpuShare } => vm.gpu !== null);
155 const gpuTimer = setInterval(() => gpuGuest() && refetchVms(), 5_000);
156 onCleanup(() => [timer, gpuTimer].forEach(clearInterval));
157 const info = lastGood(host);
158 const pool = lastGood(storage);
159 const apps = lastGood(launcher);
160 const history = lastGood(deploys);
161 const stages = () => (history()?.stages ?? []).filter((stage) =>
162 !stage.ready || (stage.health !== "down" && stage.health !== "stopped"));
163 const known = lastGood(services);
164 const names = () => Object.fromEntries((known() ?? []).map((service) => [service.id, service.name]));
165 const name = (id: string) => names()[id] ?? id;
166 const health = (service: { id: string; health: Health | null }) =>
167 stream.latest()?.services[service.id]?.health ?? service.health;
168 const metrics = () => apps()?.find((app) => app.id === "victoria");
169
170 const [menuId, setMenuId] = createSignal<string>();
171 const selectedStage = () => history()?.stages.find((stage) => stage.id === menuId());
172 const [destroying, setDestroying] = createSignal<string>();
173 let stageMenu!: HTMLDivElement;
174 let stageAnchor: HTMLAnchorElement;
175 let destroyRun: EventSource | undefined;
176 onCleanup(() => destroyRun?.close());
177 const showStageMenu = (stage: StageInfo, event: (MouseEvent | KeyboardEvent) & { currentTarget: HTMLAnchorElement }) => {
178 event.preventDefault();
179 stageAnchor = event.currentTarget;
180 stageAnchor.focus();
181 setMenuId(stage.id);
182 stageMenu.showPopover();
183 const rect = stageAnchor.getBoundingClientRect();
184 const x = event instanceof MouseEvent ? event.clientX : rect.left;
185 const y = event instanceof MouseEvent ? event.clientY : rect.bottom;
186 stageMenu.style.left = `${Math.max(8, Math.min(x, innerWidth - stageMenu.offsetWidth - 8))}px`;
187 stageMenu.style.top = `${Math.max(8, Math.min(y, innerHeight - stageMenu.offsetHeight - 8))}px`;
188 stageMenu.querySelector("button")?.focus();
189 };
190 const destroyStage = (stage: StageInfo) => {
191 stageMenu.hidePopover();
192 confirmDestroyStage(stage, (run) => {
193 setDestroying(stage.id);
194 destroyRun = followRun(run.id, {
195 exit: async (code) => {
196 setDestroying();
197 await refetchDeploys();
198 if (code !== 0) toast("Couldn't destroy the preview. Open its output, then retry.", {
199 label: "output", run: async () => location.assign(`/deploys/${stage.id}/output`),
200 });
201 },
202 lost: () => {
203 setDestroying();
204 toast("Lost destroy progress. Open its output to check the result.", {
205 label: "output", run: async () => location.assign(`/deploys/${stage.id}/output`),
206 });
207 },
208 });
209 refetchDeploys();
210 }, stageAnchor);
211 };
212
213 const [range, setRange] = createSignal(3600);
214 const [splitCpu, setSplitCpu] = createSignal(false);
215 const [splitMemory, setSplitMemory] = createSignal(false);
216 const groupBy = (value: () => boolean, set: (value: boolean) => void) => (
217 <TabBar label="Group by">
218 <button aria-pressed={!value()} onClick={() => set(false)}>total</button>
219 <button aria-pressed={value()} onClick={() => set(true)}>by service</button>
220 </TabBar>
221 );
222 const live = (read: (tick: Live, host: HostInfo) => Reading) => () => {
223 const tick = stream.latest();
224 const host = info();
225 return tick && host ? { ...read(tick, host), stale: !stream.live() } : undefined;
226 };
227
228 type Change = { t: number; icon: typeof Rocket; what: JSX.Element; detail?: JSX.Element; warn?: boolean };
229 const changes = createMemo(() => {
230 const list: Change[] = [];
231 const host = info();
232 for (const outage of host?.outages ?? []) {
233 list.push({
234 t: outage.start, icon: BatteryWarning, what: "on battery", warn: outage.end === null,
235 detail: outage.end === null ? "now" : `for ${duration(outage.end - outage.start)}`,
236 });
237 }
238 for (const entry of history()?.history ?? []) {
239 const rollback = entry.source === "rollback";
240 if (!rollback && entry.changed?.length === 0) continue;
241 list.push({
242 t: entry.time, icon: rollback ? Undo2 : Rocket,
243 what: <a href="/deploys" data-tip={`release ${entry.release.slice(0, 8)}`}>{rollback ? "rolled back" : "updated"}</a>,
244 detail: (
245 <For each={entry.changed ?? []}>
246 {(id, i) => <>{i() ? ", " : ""}<a href={`/services/${id}`}>{name(id)}</a></>}
247 </For>
248 ),
249 });
250 }
251 const recent = list.filter((change) => !host || change.t > host.bootedAt).sort((a, b) => b.t - a.t).slice(0, 7);
252 // Everything older than the boot is history; the boot itself always closes the list.
253 return host
254 ? [...recent, { t: host.bootedAt, icon: Power, what: "booted", detail: `up ${duration(Date.now() / 1000 - host.bootedAt)}` }]
255 : recent;
256 });
257
258 return (
259 <div class="page overview">
260 <div class="page-head"><Greeting me={props.me} /></div>
261
262 <Show when={stages().length}>
263 <section class="staging" aria-label="Staging instances">
264 <div class="staging-heading"><h2>staging</h2><span>{plural(stages().length, "preview")}</span></div>
265 <div class="staging-list">
266 <For each={stages().map((stage) => stage.id)}>
267 {(id) => <Show when={stages().find((stage) => stage.id === id)}>{(stage) => (
268 <a href={`/deploys/${id}`} aria-haspopup="menu" aria-controls="stage-menu"
269 aria-busy={destroying() === id}
270 onContextMenu={(event) => showStageMenu(stage(), event)}
271 onKeyDown={(event) => {
272 if (event.key === "ContextMenu" || (event.key === "F10" && event.shiftKey)) showStageMenu(stage(), event);
273 }}>
274 <Show when={destroying() === id} fallback={
275 <Show when={stage().health} fallback={<span class="muted">unknown</span>}>
276 {(health) => <Status health={health()} />}
277 </Show>
278 }><Status health="deploying" label="destroying" /></Show>
279 <span>{name(stage().service)}</span>
280 <span class="mono muted">{id.slice(stage().service.length + "-preview-".length)}</span>
281 </a>
282 )}</Show>}
283 </For>
284 </div>
285 </section>
286 </Show>
287
288 <div ref={stageMenu} id="stage-menu" popover="auto" class="stage-menu" role="menu"
289 aria-label="Preview actions" onToggle={(event) => event.newState === "closed" && setMenuId()}
290 onKeyDown={(event) => {
291 if (["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) event.preventDefault();
292 }}>
293 <Show when={selectedStage()}>
294 {(stage) => <button role="menuitem" disabled={!!destroying() || history()?.run?.code === null}
295 onClick={() => destroyStage(stage())}><Trash size={14} aria-hidden="true" />destroy</button>}
296 </Show>
297 </div>
298
299 <div class="glance">
300 <Loaded data={launcher} what="apps" retry={refetchLauncher} skeleton={
301 <div class="apps"><For each={Array(10)}>{() => <span class="skeleton" />}</For></div>
302 }>
303 {(list) => (
304 <Show when={list().length} fallback={<p class="muted">No apps shared with you yet.</p>}>
305 <nav class="apps" aria-label="Apps">
306 <For each={list()}>
307 {(app) => (
308 <AppCard app={app} health={health(app)}>
309 <Show when={health(app) !== "healthy" && health(app)}>{(now) => <Status health={now()} />}</Show>
310 </AppCard>
311 )}
312 </For>
313 </nav>
314 </Show>
315 )}
316 </Loaded>
317 <section aria-label="Recent changes">
318 <Issues admin={admin} />
319 <Loaded data={host} what="recent changes" retry={refetchHost} skeleton={
320 <ul class="changes"><For each={Array(5)}>{() => <li><span class="skeleton" style={{ width: "60%" }} /></li>}</For></ul>
321 }>
322 {() => (
323 <ul class="changes">
324 <For each={changes()}>
325 {(change) => (
326 <li classList={{ warn: change.warn }}>
327 <change.icon size={14} aria-hidden="true" />
328 <span class="what">{change.what} <span class="muted">{change.detail}</span></span>
329 <Ago t={change.t} />
330 </li>
331 )}
332 </For>
333 </ul>
334 )}
335 </Loaded>
336 </section>
337 </div>
338
339 <div class="section-head"><h2><a href={admin ? "/storage" : undefined}>storage</a></h2></div>
340 <Loaded data={storage} what="the pool" retry={refetchStorage} skeleton={
341 <div class="glance"><div class="skeleton" style={{ height: "140px" }} /><div class="skeleton" style={{ height: "64px" }} /></div>
342 }>
343 {(data) => <Pool data={data()} disks={admin ? "/storage?tab=disks" : undefined} />}
344 </Loaded>
345
346 <div class="section-head">
347 <h2>machine</h2>
348 <Show when={metrics()}>{(app) => <OpenApp app={app()} href={`${app().urls.metrics}/vmui/`} />}</Show>
349 <RangePicker value={range()} onChange={setRange} />
350 </div>
351 <div class="strips">
352 <Strip title="cpu" metric={splitCpu() ? "service.cpu" : "host.cpu"} range={range()} split={splitCpu()} names={names()}
353 stacked={splitCpu()} scale={splitCpu() ? 100 / (info()?.cores ?? 1) : undefined} format={percent} max={100} height={104}
354 tabs={groupBy(splitCpu, setSplitCpu)}
355 now={live((tick, host) => {
356 const [top] = Object.entries(tick.services).flatMap(([id, { cpu }]) => (cpu === null ? [] : [[id, cpu] as const]))
357 .sort((a, b) => b[1] - a[1]);
358 return {
359 value: percent(tick.host.cpu),
360 tip: `${cores((tick.host.cpu / 100) * host.cores)} / ${host.cores} cores`
361 + (top ? ` · top: ${name(top[0])} ${cores(top[1])}` : ""),
362 };
363 })} />
364 <Strip title="memory" metric={splitMemory() ? "service.memory" : "host.memory"} range={range()} split={splitMemory()}
365 names={names()} format={bytes} stacked max={splitMemory() ? undefined : info()?.memory} height={112}
366 tabs={groupBy(splitMemory, setSplitMemory)}
367 now={live((tick, host) => ({
368 value: bytes(tick.host.memory),
369 tip: `${bytes(tick.host.memory)} / ${bytes(host.memory)} (${percent((tick.host.memory / host.memory) * 100)})`
370 + (tick.host.arc === null ? "" : ` · ${bytes(tick.host.arc)} ZFS cache`),
371 }))} />
372 <Strip title="gpu" metric="host.gpu" range={range()} format={percent} max={100} height={80}
373 tabs={<Show when={gpuGuest()}>{(vm) => <GpuSwitch vm={vm()} refetch={refetchVms} />}</Show>}
374 now={(series) => {
375 const value = latestOf(series[0]);
376 return value === undefined ? undefined : { value: percent(value) };
377 }} />
378 <Strip title="power" metric="host.power" range={range()} format={watts} height={80}
379 now={live(({ ups }, host) => {
380 if (!ups) return { value: "–", tip: "No UPS is connected to this host yet." };
381 if (ups.status === "battery") {
382 return {
383 value: <StatusLabel health="degraded">on battery, {duration(ups.runtime)} left</StatusLabel>,
384 tip: `${watts(ups.load)} · ${percent(ups.charge)} charged`,
385 };
386 }
387 const outage = host.outages?.at(-1);
388 return {
389 value: watts(ups.load),
390 tip: [
391 `${duration(ups.runtime)} on battery`,
392 ups.charge < 100 && `${percent(ups.charge)} charged`,
393 outage && `last outage ${ago(outage.start)}, ${duration((outage.end ?? Date.now() / 1000) - outage.start)}`,
394 ].filter(Boolean).join(" · "),
395 };
396 })} />
397 <Strip title="temperature" metric="host.temperature" range={range()} format={celsius} zero={false} height={120}
398 now={live((tick) => {
399 const hottest = pool()?.pool.vdevs.flatMap((vdev) => vdev.disks).flatMap((disk) => disk.smart ?? [])
400 .sort((a, b) => b.temperature - a.temperature)[0];
401 return {
402 value: tick.host.temperature === null ? "–" : celsius(tick.host.temperature),
403 tip: `${tick.host.temperature === null ? "no cpu sensor read yet" : "cpu"}`
404 + `${hottest ? ` · hottest drive ${celsius(hottest.temperature)}, ${hottest.model}` : ""}`,
405 };
406 })} />
407 <Strip title="network" metric="host.network" range={range()} format={rate} height={104 + 24} last
408 now={(series) => {
409 const [down, up] = series.map(latestOf);
410 return down === undefined || up === undefined ? undefined : {
411 value: (
412 <><ArrowDown size={14} aria-label="download" />{rate(down)}<ArrowUp size={14} aria-label="upload" />{rate(up)}</>
413 ),
414 };
415 }} />
416 </div>
417 </div>
418 );
419}
420
421/** How full the pool is, which disks need a look and why, and the latest scrub; `disks` links to the disk list. */
422function Pool(props: { data: Storage; disks?: string }) {
423 const space = () => props.data.space;
424 const used = () => space().live + space().held;
425 const disks = () => props.data.pool.vdevs.flatMap((vdev) => vdev.disks);
426 const ailing = () => disks().filter((disk) => disk.issue);
427 const scan = () => props.data.pool.scan;
428 return (
429 <div class="glance pool">
430 <Donut format={bytes} center={percent((used() / (used() + space().free)) * 100)} caption="full" slices={[
431 { label: "used", value: space().live, color: "var(--series-1)" },
432 { label: "snapshots", value: space().held, color: "var(--series-2)" },
433 { label: "free", value: space().free, color: "var(--other)" },
434 ]} />
435 <ul class="changes">
436 <Show when={ailing().length} fallback={
437 <li>
438 <HardDrive size={14} aria-hidden="true" />
439 <a class="what" href={props.disks}><StatusLabel health="healthy">all {disks().length} disks healthy</StatusLabel></a>
440 </li>
441 }>
442 <For each={ailing()}>
443 {(disk) => (
444 <li class="warn">
445 <HardDrive size={14} aria-hidden="true" />
446 <span class="what">
447 <a href={props.disks}
448 data-tip={disk.smart ? `${disk.smart.model}, ${celsius(disk.smart.temperature)}` : undefined}>
449 {disk.smart?.serial ?? disk.name}
450 </a> <span class="muted">{disk.issue}</span>
451 </span>
452 </li>
453 )}
454 </For>
455 </Show>
456 <Show when={scan()} fallback={
457 <li><ShieldCheck size={14} aria-hidden="true" /><span class="what muted">never scrubbed</span></li>
458 }>
459 {(scan) => (
460 <Show when={scan().state === "scanning"} fallback={
461 <li classList={{ warn: scan().errors > 0 }}>
462 <ShieldCheck size={14} aria-hidden="true" />
463 <span class="what"
464 data-tip={scan().end ? `${bytes(scan().examined)} checked in ${duration(scan().end! - scan().start)}` : undefined}>
465 {scan().kind === "scrub" ? "scrub" : "resilver"} {scan().state}{" "}
466 <span class="muted">
467 {scan().errors ? plural(scan().errors, "unrepaired error")
468 : scan().repaired ? `repaired ${bytes(scan().repaired)}` : scan().state === "finished" ? "no errors" : ""}
469 </span>
470 </span>
471 <Ago t={scan().end ?? scan().start} />
472 </li>
473 }>
474 {(() => {
475 const elapsed = () => Date.now() / 1000 - scan().start;
476 const left = () => ((scan().total - scan().examined) / scan().examined) * elapsed();
477 return (
478 <li>
479 <ShieldCheck size={14} aria-hidden="true" />
480 <span class="what scanning"
481 data-tip={`${bytes(scan().examined)} / ${bytes(scan().total)}, started ${ago(scan().start)}`}>
482 {scan().kind === "scrub" ? "scrubbing" : "resilvering"}
483 <Meter value={scan().examined} max={scan().total} />
484 {percent((scan().examined / scan().total) * 100)}
485 </span>
486 <span class="muted">{duration(left())} left</span>
487 </li>
488 );
489 })()}
490 </Show>
491 )}
492 </Show>
493 </ul>
494 </div>
495 );
496}
497
498export function Overview(props: { me: Me }) {
499 return (
500 <Show when={props.me.sections.includes("metrics")} fallback={<Home me={props.me} />}>
501 <Dashboard me={props.me} />
502 </Show>
503 );
504}