| 1 | import { A, useParams, useSearchParams } from "@solidjs/router"; |
| 2 | import { parseResponse } from "hono/client"; |
| 3 | import Eye from "lucide-solid/icons/eye"; |
| 4 | import EyeOff from "lucide-solid/icons/eye-off"; |
| 5 | import HardDrive from "lucide-solid/icons/hard-drive"; |
| 6 | import Package from "lucide-solid/icons/package"; |
| 7 | import RotateCcw from "lucide-solid/icons/rotate-ccw"; |
| 8 | import Search from "lucide-solid/icons/search"; |
| 9 | import X from "lucide-solid/icons/x"; |
| 10 | import { |
| 11 | createEffect, createMemo, createResource, createSignal, createUniqueId, For, type JSX, Match, onCleanup, Show, Switch, untrack, |
| 12 | } from "solid-js"; |
| 13 | import { Portal } from "solid-js/web"; |
| 14 | import { |
| 15 | type Action, type LogLine, type Series, type ServiceDetail, type TraceSummary, unacknowledgedRestart, |
| 16 | } from "../types/model.ts"; |
| 17 | import { logField, needles, parseSearch, traceField, type TraceSort } from "../types/search.ts"; |
| 18 | import { api, queries, query, reason } from "../api.ts"; |
| 19 | import { Ago } from "../components/Ago.tsx"; |
| 20 | import { AppIcon } from "../components/AppIcon.tsx"; |
| 21 | import { Copy } from "../components/Copy.tsx"; |
| 22 | import { showConfirmDialog, showTextDialog } from "../components/Dialog.tsx"; |
| 23 | import { ListPage } from "../components/ListPage.tsx"; |
| 24 | import { LogView } from "../components/LogView.tsx"; |
| 25 | import { OpenApp } from "../components/OpenApp.tsx"; |
| 26 | import { lastGood, Loaded } from "../components/Loaded.tsx"; |
| 27 | import { RangePicker } from "../components/Metric.tsx"; |
| 28 | import { TimeChart } from "../components/TimeChart.tsx"; |
| 29 | import { type Sort, SortHeader } from "../components/SortHeader.tsx"; |
| 30 | import { Status, StatusLabel } from "../components/Status.tsx"; |
| 31 | import { Strip } from "../components/Strip.tsx"; |
| 32 | import { TabBar } from "../components/TabBar.tsx"; |
| 33 | import { toast } from "../components/Toast.tsx"; |
| 34 | import { ago, bytes, clock, cores, datetime, duration, plural } from "../format.ts"; |
| 35 | import { stream } from "../live.ts"; |
| 36 | import { Definition } from "./Service.definition.tsx"; |
| 37 | import { Flame, ms } from "./Service.flame.tsx"; |
| 38 | import "./Service.css"; |
| 39 | |
| 40 | const TABS = [["", "logs"], ["traces", "traces"], ["metrics", "metrics"], ["secrets", "secrets"], ["definition", "definition"]] as const; |
| 41 | const LEVELS = [[undefined, "all"], ["warn", "warn"], ["error", "error"]] as const; |
| 42 | |
| 43 | /** URL state of the logs and traces tabs; `at` opens the logs at a moment instead of following. */ |
| 44 | type Query = { q?: string; level?: "warn" | "error"; at?: string; from?: string; to?: string; errors?: "1"; sort?: TraceSort; trace?: string }; |
| 45 | |
| 46 | /** Newest at the bottom; follows new lines while scrolled to the end, and loads older ones near the top. */ |
| 47 | export function Logs(props: { service: Pick<ServiceDetail, "id" | "containers" | "logs">; tools: HTMLElement }) { |
| 48 | const [params, setParams] = useSearchParams<Query>(); |
| 49 | const at = () => (params.at ? Number(params.at) : null); |
| 50 | const bounded = () => at() !== null || !!params.to; |
| 51 | const dateValue = (value?: string) => { |
| 52 | if (!value) return ""; |
| 53 | const date = new Date(Number(value) * 1000); |
| 54 | return new Date(date.getTime() - date.getTimezoneOffset() * 60_000).toISOString().slice(0, 16); |
| 55 | }; |
| 56 | const [all, setLines] = createSignal<LogLine[]>([]); |
| 57 | let pending: LogLine[] = []; |
| 58 | let generation = 0; |
| 59 | let older: { before: string; offset: number } | undefined; |
| 60 | const [exhausted, setExhausted] = createSignal(false); |
| 61 | const [loadingOlder, setLoadingOlder] = createSignal(false); |
| 62 | const [follow, setFollow] = createSignal(true); |
| 63 | const [unseen, setUnseen] = createSignal(0); |
| 64 | const [stalled, setStalled] = createSignal<string>(); |
| 65 | const [connected, setConnected] = createSignal(false); |
| 66 | const merge = (before: LogLine[], after: LogLine[]) => [...new Map([...before, ...after] |
| 67 | .map((line) => [line.id ?? JSON.stringify(line), line])).values()].sort((a, b) => a.t - b.t); |
| 68 | const resume = () => { |
| 69 | older = undefined; |
| 70 | setLines((lines) => merge(lines, pending).slice(-10_000)); |
| 71 | pending = []; |
| 72 | setUnseen(0); |
| 73 | setExhausted(false); |
| 74 | setFollow(true); |
| 75 | }; |
| 76 | const fetchLines = (limit: number, extra: { before?: string; after?: string; offset?: string }) => |
| 77 | parseResponse(api.services[":id"].logs.$get({ |
| 78 | param: { id: props.service.id }, |
| 79 | query: { q: params.q ?? "", ...(params.level ? { level: params.level } : {}), limit: String(limit), |
| 80 | ...(params.from ? { after: params.from } : {}), ...(params.to ? { before: params.to } : {}), ...extra }, |
| 81 | })).then((lines) => lines.reverse()); |
| 82 | const [first, { refetch }] = createResource<LogLine[], string>( |
| 83 | // A string key, since a fresh array from an unrelated rerun would count as a change and refetch. |
| 84 | () => JSON.stringify([props.service.id, params.q, params.level, params.at, params.from, params.to]), |
| 85 | () => { |
| 86 | const current = ++generation; |
| 87 | older = undefined; |
| 88 | setLines([]); |
| 89 | pending = []; |
| 90 | setLoadingOlder(false); |
| 91 | setExhausted(false); |
| 92 | setFollow(!bounded()); |
| 93 | setUnseen(0); |
| 94 | setStalled(); |
| 95 | return fetchLines(1000, at() === null ? {} : { before: String(at()! + 30) }).then((lines) => { |
| 96 | if (current === generation) setLines(lines); |
| 97 | return lines; |
| 98 | }); |
| 99 | }, |
| 100 | ); |
| 101 | |
| 102 | const loadOlder = async () => { |
| 103 | const oldest = all()[0]; |
| 104 | if (!oldest || loadingOlder() || exhausted()) return; |
| 105 | |
| 106 | setLoadingOlder(true); |
| 107 | const current = generation; |
| 108 | try { |
| 109 | const page = older ??= { before: String(oldest.t + 0.000001), offset: 0 }; |
| 110 | const fetched = await fetchLines(5000, { before: page.before, offset: String(page.offset) }); |
| 111 | if (current !== generation || older !== page) return; |
| 112 | const known = new Set(all().map((line) => line.id ?? JSON.stringify(line))); |
| 113 | const lines = fetched.filter((line) => !known.has(line.id ?? JSON.stringify(line))); |
| 114 | page.offset += fetched.length; |
| 115 | if (fetched.length < 5000) setExhausted(true); |
| 116 | setLines((previous) => merge(lines, previous)); |
| 117 | } catch (failure) { |
| 118 | if (current === generation) toast(`Couldn't load older lines. ${reason(failure)}`); |
| 119 | } finally { |
| 120 | if (current === generation) setLoadingOlder(false); |
| 121 | } |
| 122 | }; |
| 123 | |
| 124 | createEffect(() => { |
| 125 | const id = props.service.id; |
| 126 | const q = params.q ?? ""; |
| 127 | const level = params.level; |
| 128 | const from = params.from; |
| 129 | setConnected(false); |
| 130 | if (bounded() || first.state !== "ready") return; |
| 131 | let disposed = false; |
| 132 | let failures = 0; |
| 133 | let cursor = Math.max(0, ...untrack(all).map((line) => line.sequence ?? 0)); |
| 134 | let socket: WebSocket; |
| 135 | let retry: ReturnType<typeof setTimeout> | undefined; |
| 136 | let stale: ReturnType<typeof setTimeout> | undefined; |
| 137 | const connect = () => { |
| 138 | const url = new URL(`/api/services/${encodeURIComponent(id)}/logs/stream`, location.href); |
| 139 | url.protocol = location.protocol === "https:" ? "wss:" : "ws:"; |
| 140 | url.searchParams.set("q", q); |
| 141 | if (level) url.searchParams.set("level", level); |
| 142 | url.searchParams.set("cursor", String(cursor)); |
| 143 | if (from) url.searchParams.set("from", from); |
| 144 | socket = new WebSocket(url); |
| 145 | socket.onmessage = (event) => { |
| 146 | if (disposed) return; |
| 147 | const message: { lines?: LogLine[]; cursor?: number; error?: string } = JSON.parse(event.data); |
| 148 | if (message.error) { |
| 149 | setConnected(false); |
| 150 | setStalled(message.error); |
| 151 | return; |
| 152 | } |
| 153 | failures = 0; |
| 154 | setConnected(true); |
| 155 | setStalled(); |
| 156 | clearTimeout(stale); |
| 157 | stale = setTimeout(() => socket.close(), 35_000); |
| 158 | if (message.lines?.length) { |
| 159 | const known = new Set([...all(), ...pending].map((line) => line.id ?? JSON.stringify(line))); |
| 160 | const lines = message.lines.filter((line) => { |
| 161 | const id = line.id ?? JSON.stringify(line); |
| 162 | if (known.has(id)) return false; |
| 163 | known.add(id); |
| 164 | return true; |
| 165 | }); |
| 166 | if (follow()) { |
| 167 | older = undefined; |
| 168 | setLines((previous) => merge(previous, lines).slice(-10_000)); |
| 169 | } |
| 170 | else { |
| 171 | pending = merge(pending, lines).slice(-10_000); |
| 172 | setUnseen((previous) => previous + lines.length); |
| 173 | } |
| 174 | } |
| 175 | cursor = message.cursor ?? cursor; |
| 176 | }; |
| 177 | socket.onclose = () => { |
| 178 | if (disposed) return; |
| 179 | clearTimeout(stale); |
| 180 | setConnected(false); |
| 181 | setStalled((previous) => previous ?? "Live logs disconnected. Retrying…"); |
| 182 | retry = setTimeout(connect, Math.min(30, 2 ** failures++) * 1000); |
| 183 | }; |
| 184 | }; |
| 185 | connect(); |
| 186 | onCleanup(() => { |
| 187 | disposed = true; |
| 188 | clearTimeout(retry); |
| 189 | clearTimeout(stale); |
| 190 | socket.close(); |
| 191 | }); |
| 192 | }); |
| 193 | const marked = createMemo(() => (at() === null ? undefined : all().find((line) => line.t > at()!))); |
| 194 | const hints = () => [ |
| 195 | ...props.service.containers.filter((container) => !container.hook && props.service.containers.length > 1).slice(0, 1) |
| 196 | .map((container) => [`container:${container.name}`, "one container's lines"] as const), |
| 197 | ["stream:stderr", "error output only"], |
| 198 | ["stream:event", "starts, restarts, and OOM kills"], |
| 199 | ["-health", "hide lines with a word"], |
| 200 | ['"connection refused"', "an exact phrase"], |
| 201 | ] as const; |
| 202 | |
| 203 | return ( |
| 204 | <div class="logs-tab fill"> |
| 205 | <Portal mount={props.tools} ref={(el) => (el.style.display = "contents")}> |
| 206 | <Filters placeholder="search logs…" hints={hints()}> |
| 207 | <TabBar label="Level"> |
| 208 | <For each={LEVELS}> |
| 209 | {([level, label]) => ( |
| 210 | <button aria-pressed={params.level === level} onClick={() => setParams({ level }, { replace: true })} |
| 211 | data-tip={level === "warn" ? "warnings and errors" : undefined}> |
| 212 | {label} |
| 213 | </button> |
| 214 | )} |
| 215 | </For> |
| 216 | </TabBar> |
| 217 | <label>from <input type="datetime-local" value={dateValue(params.from)} |
| 218 | onChange={(event) => setParams({ from: event.currentTarget.value ? String(Date.parse(event.currentTarget.value) / 1000) : undefined }, { replace: true })} /></label> |
| 219 | <label>to <input type="datetime-local" value={dateValue(params.to)} |
| 220 | onChange={(event) => setParams({ to: event.currentTarget.value ? String(Date.parse(event.currentTarget.value) / 1000) : undefined }, { replace: true })} /></label> |
| 221 | <Show when={props.service.logs}>{(link) => <OpenApp app={link().app} href={link().url}>{link().app.name}</OpenApp>}</Show> |
| 222 | <Liveness every="lines as they arrive" connecting={!connected()} paused={bounded() ? "Showing the selected time range" : undefined} |
| 223 | failure={stalled() ?? (first.state === "errored" ? reason(first.error) : undefined)} /> |
| 224 | </Filters> |
| 225 | </Portal> |
| 226 | <Loaded data={first} what="logs" retry={refetch} skeleton={ |
| 227 | <div class="log-view"> |
| 228 | <div class="logs"> |
| 229 | <For each={Array(14)}> |
| 230 | {(_, i) => ( |
| 231 | <div class="log"><span class="skeleton" /><span class="skeleton" style={{ width: `${40 + ((i() * 37) % 55)}%` }} /></div> |
| 232 | )} |
| 233 | </For> |
| 234 | </div> |
| 235 | </div> |
| 236 | }> |
| 237 | {() => ( |
| 238 | <Show when={all().length} fallback={ |
| 239 | <div class="empty">{params.q || params.level ? "No lines match." : "No recent logs."}</div> |
| 240 | }> |
| 241 | <LogView lines={all()} marks={needles(parseSearch(params.q ?? "", logField))} follow={follow()} unseen={unseen()} |
| 242 | onStart={loadOlder} |
| 243 | onContainer={(name) => setParams({ q: [params.q, `container:${name}`].filter(Boolean).join(" ") }, { replace: true })} |
| 244 | onFollow={(end) => { |
| 245 | if (end && !bounded()) resume(); |
| 246 | else setFollow(false); |
| 247 | }} |
| 248 | onLatest={() => (at() === null ? resume() : setParams({ at: undefined }))} |
| 249 | before={(line, index) => ( |
| 250 | <> |
| 251 | <Show when={index() === 0}> |
| 252 | <div class="log-edge"> |
| 253 | <Show when={!exhausted()} fallback="No older lines"> |
| 254 | <button class="button small" disabled={loadingOlder()} aria-busy={loadingOlder()} onClick={loadOlder}> |
| 255 | load older |
| 256 | </button> |
| 257 | </Show> |
| 258 | </div> |
| 259 | </Show> |
| 260 | <Show when={line === marked()}><div class="log-edge at">{clock(at()!)}</div></Show> |
| 261 | </> |
| 262 | )} /> |
| 263 | </Show> |
| 264 | )} |
| 265 | </Loaded> |
| 266 | </div> |
| 267 | ); |
| 268 | } |
| 269 | |
| 270 | const traceList = query("traces", ({ id, ...query }: { id: string; q: string; errors?: "1"; sort?: TraceSort; limit: string }) => |
| 271 | parseResponse(api.services[":id"].traces.$get({ param: { id }, query }))); |
| 272 | const oneTrace = query("trace", (id: string) => parseResponse(api.traces[":id"].$get({ param: { id } }))); |
| 273 | const PAGE = 50; |
| 274 | |
| 275 | export function AppMetrics(props: { service: Pick<ServiceDetail, "id" | "applicationMetrics">; range: number }) { |
| 276 | const [name, setName] = createSignal(props.service.applicationMetrics[0]!); |
| 277 | const [data, { refetch }] = createResource( |
| 278 | () => [props.service.id, name(), props.range] as const, |
| 279 | ([id, metric, range]) => parseResponse(api.services[":id"].metrics[":name"].$get({ |
| 280 | param: { id, name: metric }, query: { range: String(range) }, |
| 281 | })), |
| 282 | ); |
| 283 | const timer = setInterval(refetch, 30_000); |
| 284 | onCleanup(() => clearInterval(timer)); |
| 285 | return ( |
| 286 | <div class="card metric"> |
| 287 | <div class="card-title"> |
| 288 | application metrics |
| 289 | <span class="spacer" /> |
| 290 | <label>Metric <select value={name()} onChange={(event) => setName(event.currentTarget.value)}> |
| 291 | <For each={props.service.applicationMetrics}>{(metric) => <option value={metric}>{metric}</option>}</For> |
| 292 | </select></label> |
| 293 | </div> |
| 294 | <Loaded data={data} what="application metrics" retry={refetch} skeleton={<div class="skeleton" style={{ height: "196px" }} />}> |
| 295 | {(series) => <Show when={series().length} fallback={<div class="empty">No samples in this range.</div>}> |
| 296 | <TimeChart series={series()} format={(value) => new Intl.NumberFormat(undefined, { maximumFractionDigits: 2 }).format(value)} /> |
| 297 | </Show>} |
| 298 | </Loaded> |
| 299 | </div> |
| 300 | ); |
| 301 | } |
| 302 | |
| 303 | function Traces(props: { service: ServiceDetail; tools: HTMLElement }) { |
| 304 | const [params, setParams] = useSearchParams<Query>(); |
| 305 | const [limit, setLimit] = createSignal(PAGE); |
| 306 | const [traces, { refetch }] = traceList.use(() => |
| 307 | ({ id: props.service.id, q: params.q ?? "", errors: params.errors, sort: params.sort, limit: String(limit()) })); |
| 308 | const timer = setInterval(refetch, 10_000); |
| 309 | onCleanup(() => clearInterval(timer)); |
| 310 | const shown = lastGood(traces); |
| 311 | /** Rows keep an unchanged trace's summary, so a refresh doesn't rebuild them and take focus or scroll with it. */ |
| 312 | const rows = createMemo<TraceSummary[]>((previous) => { |
| 313 | const known = new Map(previous.map((summary) => [summary.id, summary])); |
| 314 | return (shown() ?? []).map((summary) => { |
| 315 | const old = known.get(summary.id); |
| 316 | return old && old.spans === summary.spans && old.error === summary.error ? old : summary; |
| 317 | }); |
| 318 | }, []); |
| 319 | const failing = createMemo<string | undefined>((previous) => |
| 320 | traces.state === "errored" ? reason(traces.error) : traces.state === "ready" ? undefined : previous); |
| 321 | // Pinned once, so newer traces arriving above it don't swap the one being read; never from a search's old answer. |
| 322 | createEffect(() => { |
| 323 | const first = rows()[0]; |
| 324 | if (!params.trace && first && traces.state === "ready") setParams({ trace: first.id }, { replace: true }); |
| 325 | }); |
| 326 | const [trace, { refetch: refetchTrace }] = oneTrace.use(() => params.trace ?? false); |
| 327 | const slowest = () => Math.max(...rows().map((summary) => summary.root.duration)); |
| 328 | const sort = (): Sort<"when" | "duration"> => ({ |
| 329 | key: params.sort === "slowest" || params.sort === "fastest" ? "duration" : "when", |
| 330 | desc: params.sort !== "oldest" && params.sort !== "fastest", |
| 331 | }); |
| 332 | // A column's first click shows its most telling end: the newest, or the slowest. |
| 333 | const onSort = ({ key, desc }: Sort<"when" | "duration">) => setParams({ |
| 334 | sort: key === "when" ? (desc || key !== sort().key ? undefined : "oldest") : desc || key !== sort().key ? "slowest" : "fastest", |
| 335 | trace: undefined, |
| 336 | }, { replace: true }); |
| 337 | /** Up and down move the selection, keeping focus on the chosen row. */ |
| 338 | const step = (event: KeyboardEvent) => { |
| 339 | const offset = ({ ArrowDown: 1, ArrowUp: -1 } as Record<string, number>)[event.key]; |
| 340 | const next = offset && rows()[rows().findIndex((summary) => summary.id === params.trace) + offset]; |
| 341 | if (!next) return; |
| 342 | event.preventDefault(); |
| 343 | setParams({ trace: next.id }, { replace: true }); |
| 344 | (event.currentTarget as HTMLElement).querySelector<HTMLButtonElement>(`[data-trace="${next.id}"]`)?.focus(); |
| 345 | }; |
| 346 | const hints = [ |
| 347 | ["status:5xx", "by status code"], |
| 348 | ["path:/api", "paths that start with /api"], |
| 349 | ["duration:>1s", "slower than a second"], |
| 350 | ["method:post", "by method"], |
| 351 | ["-path:/health", "hide matching requests"], |
| 352 | ] as const; |
| 353 | return ( |
| 354 | <> |
| 355 | <Portal mount={props.tools} ref={(el) => (el.style.display = "contents")}> |
| 356 | <Filters placeholder="search traces…" hints={hints}> |
| 357 | <TabBar label="Show"> |
| 358 | <For each={[undefined, "1"] as const}> |
| 359 | {(errors) => ( |
| 360 | <button aria-pressed={params.errors === errors} onClick={() => setParams({ errors, trace: undefined }, { replace: true })}> |
| 361 | {errors ? "errors" : "all"} |
| 362 | </button> |
| 363 | )} |
| 364 | </For> |
| 365 | </TabBar> |
| 366 | <Liveness every="traces every 10 s" failure={failing()} /> |
| 367 | </Filters> |
| 368 | </Portal> |
| 369 | <Loaded data={traces} what="traces" retry={refetch} skeleton={ |
| 370 | <div class="fill traces"> |
| 371 | <For each={Array(6)}> |
| 372 | {(_, i) => <div class="skeleton row-skeleton" style={{ width: `${35 + ((i() * 37) % 45)}%` }} />} |
| 373 | </For> |
| 374 | </div> |
| 375 | }> |
| 376 | {() => ( |
| 377 | <Show when={rows().length} fallback={ |
| 378 | <Show when={!params.q && !params.errors} fallback={<div class="empty">No traces match in the last week.</div>}> |
| 379 | <div class="empty traces-empty"> |
| 380 | <p><strong>No traces from {props.service.name} yet.</strong></p> |
| 381 | </div> |
| 382 | </Show> |
| 383 | }> |
| 384 | <div class="fill traces"> |
| 385 | <div class="trace-list"> |
| 386 | <table class="data"> |
| 387 | <thead> |
| 388 | <tr> |
| 389 | <SortHeader column="when" label="when" sort={sort()} onSort={onSort} class="when" /> |
| 390 | <th>request</th> |
| 391 | <th class="code">status</th> |
| 392 | <th class="num spans">spans</th> |
| 393 | <SortHeader column="duration" label="duration" sort={sort()} onSort={onSort} num /> |
| 394 | </tr> |
| 395 | </thead> |
| 396 | <tbody onKeyDown={step}> |
| 397 | <For each={rows()}> |
| 398 | {(summary) => { |
| 399 | const root = summary.root; |
| 400 | const selected = () => params.trace === summary.id; |
| 401 | const status = root.attributes["http.response.status_code"]; |
| 402 | return ( |
| 403 | <tr ref={(row) => createEffect(() => selected() && row.scrollIntoView({ block: "nearest" }))} |
| 404 | classList={{ selected: selected() }} onClick={() => setParams({ trace: summary.id }, { replace: true })}> |
| 405 | <td class="when"><Ago t={root.start} /></td> |
| 406 | <td class="request"> |
| 407 | <button data-trace={summary.id} aria-current={selected() || undefined}> |
| 408 | {root.attributes["http.request.method"] ?? ""} {root.attributes["url.path"] ?? root.name} |
| 409 | </button> |
| 410 | </td> |
| 411 | <td class="code" classList={{ client: String(status).startsWith("4") }}> |
| 412 | <span> |
| 413 | <Show when={summary.error}>{(error) => <Status health="down" label={error()} />}</Show> |
| 414 | {status} |
| 415 | </span> |
| 416 | </td> |
| 417 | <td class="num spans" data-tip={summary.services.length > 1 ? summary.services.join(", ") : undefined}> |
| 418 | {summary.spans} |
| 419 | </td> |
| 420 | <td class="num"> |
| 421 | <div class="duration"> |
| 422 | <span class="track"> |
| 423 | <span class="bar" style={{ width: `${(root.duration / slowest()) * 100}%` }} /> |
| 424 | </span> |
| 425 | {ms(root.duration)} |
| 426 | </div> |
| 427 | </td> |
| 428 | </tr> |
| 429 | ); |
| 430 | }} |
| 431 | </For> |
| 432 | </tbody> |
| 433 | </table> |
| 434 | <Show when={rows().length === limit()}> |
| 435 | <div class="log-edge"> |
| 436 | <button class="button small" disabled={traces.loading} aria-busy={traces.loading} onClick={() => setLimit(limit() + PAGE)}> |
| 437 | load more |
| 438 | </button> |
| 439 | </div> |
| 440 | </Show> |
| 441 | </div> |
| 442 | <Loaded data={trace} what="this trace" retry={refetchTrace} skeleton={<div class="skeleton flame-skeleton" />}> |
| 443 | {(loaded) => <Flame trace={loaded()} needles={needles(parseSearch(params.q ?? "", traceField))} job={props.service.id} />} |
| 444 | </Loaded> |
| 445 | </div> |
| 446 | </Show> |
| 447 | )} |
| 448 | </Loaded> |
| 449 | </> |
| 450 | ); |
| 451 | } |
| 452 | |
| 453 | /** Whether a tab still takes in new data; `paused` and `failure` say why it doesn't. */ |
| 454 | function Liveness(props: { every: string; paused?: string; failure?: string; connecting?: boolean }) { |
| 455 | const health = () => (props.failure ? "degraded" : props.paused || props.connecting ? "stopped" : "healthy"); |
| 456 | return ( |
| 457 | <span class="liveness" classList={{ live: health() === "healthy" }} role="status" tabIndex={0} |
| 458 | data-tip={props.failure ?? props.paused ?? (props.connecting ? "Connecting to live logs…" : `New ${props.every}`)}> |
| 459 | <StatusLabel health={health()}>{props.failure ? props.paused ? "unavailable" : "reconnecting" : props.paused ? "paused" : props.connecting ? "connecting" : "live"}</StatusLabel> |
| 460 | </span> |
| 461 | ); |
| 462 | } |
| 463 | |
| 464 | function Secrets(props: { service: ServiceDetail; onChange: () => unknown }) { |
| 465 | const [shown, setShown] = createSignal<Record<string, string>>({}); |
| 466 | const [revealing, setRevealing] = createSignal<string>(); |
| 467 | const param = (name: string) => ({ param: { id: props.service.id, name } }); |
| 468 | const hide = (name: string) => setShown(({ [name]: _, ...rest }) => rest); |
| 469 | const reveal = async (name: string) => { |
| 470 | setRevealing(name); |
| 471 | try { |
| 472 | const { value } = await parseResponse(api.services[":id"].secrets[":name"].$get(param(name))); |
| 473 | setShown({ ...shown(), [name]: value }); |
| 474 | } catch (failure) { |
| 475 | toast(`Couldn't reveal ${name}. ${reason(failure)}`); |
| 476 | } finally { |
| 477 | setRevealing(); |
| 478 | } |
| 479 | }; |
| 480 | const rotate = (name: string) => showConfirmDialog({ |
| 481 | title: `Rotate ${name}?`, |
| 482 | description: `${props.service.name} gets a new random ${name} and restarts to use it. ` |
| 483 | + "Anything still using the old value stops working until you update it.", |
| 484 | confirmLabel: "rotate", |
| 485 | destructive: true, |
| 486 | onConfirm: async () => { |
| 487 | await parseResponse(api.services[":id"].secrets[":name"].rotate.$post(param(name))); |
| 488 | hide(name); |
| 489 | await props.onChange(); |
| 490 | }, |
| 491 | }); |
| 492 | const set = (name: string) => showTextDialog({ |
| 493 | title: `Set ${name}`, |
| 494 | description: `${props.service.name} restarts to use the new value.`, |
| 495 | label: "New value", |
| 496 | confirmLabel: "set", |
| 497 | onConfirm: async (value) => { |
| 498 | await parseResponse(api.services[":id"].secrets[":name"].$put({ ...param(name), json: { value } })); |
| 499 | hide(name); |
| 500 | await props.onChange(); |
| 501 | }, |
| 502 | }); |
| 503 | return ( |
| 504 | <Show when={props.service.secrets} fallback={<div class="empty">Secrets aren't wired up to the dashboard yet.</div>}> |
| 505 | {(secrets) => ( |
| 506 | <Show when={secrets().length} fallback={ |
| 507 | <div class="empty"> |
| 508 | <p><strong>{props.service.name} has no secrets.</strong></p> |
| 509 | <p>Secrets its service file declares appear here.</p> |
| 510 | </div> |
| 511 | }> |
| 512 | <table class="data secrets"> |
| 513 | <thead><tr><th>secret</th><th>value</th><th /></tr></thead> |
| 514 | <tbody> |
| 515 | <For each={secrets()}> |
| 516 | {(secret) => ( |
| 517 | <tr> |
| 518 | <td class="mono name">{secret.name}</td> |
| 519 | <td class="mono"> |
| 520 | <Show when={shown()[secret.name]} fallback={ |
| 521 | <button class="button small" disabled={revealing() === secret.name} aria-busy={revealing() === secret.name} |
| 522 | aria-label={`Reveal ${secret.name}`} onClick={() => reveal(secret.name)}> |
| 523 | <Eye size={14} />reveal |
| 524 | </button> |
| 525 | }> |
| 526 | {(value) => ( |
| 527 | <span class="inline"> |
| 528 | <Copy value={value()} /> |
| 529 | <button class="button small icon-only" aria-label={`Hide ${secret.name}`} data-tip="hide" |
| 530 | onClick={() => hide(secret.name)}> |
| 531 | <EyeOff size={14} /> |
| 532 | </button> |
| 533 | </span> |
| 534 | )} |
| 535 | </Show> |
| 536 | </td> |
| 537 | <td class="actions"> |
| 538 | <div> |
| 539 | <Show when={secret.generated} fallback={<button onClick={() => set(secret.name)}>set</button>}> |
| 540 | <button onClick={() => rotate(secret.name)}>rotate</button> |
| 541 | </Show> |
| 542 | </div> |
| 543 | </td> |
| 544 | </tr> |
| 545 | )} |
| 546 | </For> |
| 547 | </tbody> |
| 548 | </table> |
| 549 | </Show> |
| 550 | )} |
| 551 | </Show> |
| 552 | ); |
| 553 | } |
| 554 | |
| 555 | /** |
| 556 | * The search box and filters that share the tab row with the tabs, kept in the URL. Focusing the empty box lists |
| 557 | * `hints`, examples of the search syntax that fill the box when picked. |
| 558 | */ |
| 559 | function Filters(props: { placeholder: string; hints: readonly (readonly [string, string])[]; children: JSX.Element }) { |
| 560 | const [params, setParams] = useSearchParams<Query>(); |
| 561 | const [open, setOpen] = createSignal(false); |
| 562 | const hintsId = createUniqueId(); |
| 563 | let input!: HTMLInputElement; |
| 564 | let debounce: ReturnType<typeof setTimeout> | undefined; |
| 565 | const search = (value: string) => { |
| 566 | clearTimeout(debounce); |
| 567 | setParams({ q: value || undefined, trace: undefined }, { replace: true }); |
| 568 | }; |
| 569 | const key = (event: KeyboardEvent) => { |
| 570 | if (event.key !== "/" || (event.target as Element).closest("input, textarea, [contenteditable]")) return; |
| 571 | event.preventDefault(); |
| 572 | input.focus(); |
| 573 | }; |
| 574 | document.addEventListener("keydown", key); |
| 575 | onCleanup(() => { |
| 576 | document.removeEventListener("keydown", key); |
| 577 | clearTimeout(debounce); |
| 578 | }); |
| 579 | return ( |
| 580 | <> |
| 581 | <label class="search-box"> |
| 582 | <Search size={14} /> |
| 583 | <input ref={input} type="search" placeholder={props.placeholder} aria-label={props.placeholder.slice(0, -1)} |
| 584 | aria-describedby={hintsId} value={params.q ?? ""} |
| 585 | onFocus={(event) => setOpen(!event.currentTarget.value)} |
| 586 | onBlur={() => setOpen(false)} |
| 587 | onInput={(event) => { |
| 588 | clearTimeout(debounce); |
| 589 | const value = event.currentTarget.value; |
| 590 | setOpen(!value); |
| 591 | debounce = setTimeout(() => search(value), 200); |
| 592 | }} |
| 593 | onKeyDown={(event) => { |
| 594 | if (event.key !== "Escape") return; |
| 595 | if (!event.currentTarget.value) return setOpen(false); |
| 596 | event.currentTarget.value = ""; |
| 597 | search(""); |
| 598 | }} /> |
| 599 | <kbd aria-hidden="true">/</kbd> |
| 600 | <div id={hintsId} class="search-hints" hidden={!open()}> |
| 601 | <For each={props.hints}> |
| 602 | {([example, meaning]) => ( |
| 603 | <button type="button" tabIndex={-1} onMouseDown={(event) => event.preventDefault()} |
| 604 | onClick={() => { |
| 605 | input.value = example; |
| 606 | setOpen(false); |
| 607 | search(example); |
| 608 | }}> |
| 609 | {example}<span>{meaning}</span> |
| 610 | </button> |
| 611 | )} |
| 612 | </For> |
| 613 | </div> |
| 614 | </label> |
| 615 | {props.children} |
| 616 | </> |
| 617 | ); |
| 618 | } |
| 619 | |
| 620 | /** Remounts per service, so switching shows the new one's cached state or a skeleton, never the last one's. */ |
| 621 | export function Service() { |
| 622 | const params = useParams<{ id: string }>(); |
| 623 | return <Show when={params.id} keyed><ServicePage /></Show>; |
| 624 | } |
| 625 | |
| 626 | function ServicePage() { |
| 627 | const params = useParams<{ id: string; tab?: string }>(); |
| 628 | const [service, { refetch }] = queries.service.use(() => params.id); |
| 629 | const timer = setInterval(refetch, 10_000); |
| 630 | onCleanup(() => clearInterval(timer)); |
| 631 | // After an action the refetched detail is fresher than the stream until the stream's next tick. |
| 632 | const [since, setSince] = createSignal(0); |
| 633 | stream.start(); |
| 634 | const refresh = async () => { |
| 635 | setSince(Date.now() / 1000); |
| 636 | await refetch(); |
| 637 | }; |
| 638 | const act = async (action: Action) => { |
| 639 | await parseResponse(api.services[":id"][":action"].$post({ param: { id: params.id, action } })); |
| 640 | await refresh(); |
| 641 | }; |
| 642 | |
| 643 | const [range, setRange] = createSignal(3600); |
| 644 | |
| 645 | return ( |
| 646 | <Loaded data={service} what="this service" retry={refetch} skeleton={ |
| 647 | <div class="page"> |
| 648 | <div class="page-head"> |
| 649 | <span class="skeleton" style={{ width: "32px", height: "32px" }} /> |
| 650 | <span class="skeleton" style={{ width: "140px", height: "24px" }} /> |
| 651 | <For each={[92, 96, 110]}>{(width) => <span class="skeleton stat-skeleton" style={{ width: `${width}px` }} />}</For> |
| 652 | </div> |
| 653 | <div class="skeleton" style={{ height: "112px" }} /> |
| 654 | </div> |
| 655 | }> |
| 656 | {(data) => { |
| 657 | const tick = () => { |
| 658 | const latest = stream.latest(); |
| 659 | return latest && latest.t > since() ? latest.services[data().id] : undefined; |
| 660 | }; |
| 661 | const health = () => tick()?.health ?? data().health; |
| 662 | /** Nomad leaves usage unmeasured when the task driver reports none; the tip adds the reservation and the charted peak. */ |
| 663 | const reading = (now: number | null, reserved: string, format: (value: number) => string) => (latest: Series[]) => { |
| 664 | const values = latest[0]?.v ?? []; |
| 665 | return { |
| 666 | value: now === null ? "–" : format(now), |
| 667 | tip: reserved + (values.length ? `, ${duration(range())} peak ${format(Math.max(...values.map((v) => v ?? 0)))}` : ""), |
| 668 | stale: !stream.live(), |
| 669 | }; |
| 670 | }; |
| 671 | const failing = () => |
| 672 | (health() === "degraded" || health() === "down" ? data().checks.find((check) => !check.passing) : undefined); |
| 673 | const unacknowledged = () => unacknowledgedRestart(data()); |
| 674 | const restarts = () => data().containers.reduce((sum, container) => sum + container.restarts, 0); |
| 675 | const main = () => data().containers.filter((container) => !container.hook); |
| 676 | const started = () => (health() === "healthy" ? main()[0]?.startedAt : undefined); |
| 677 | /** One pill per image the main tasks run, however many tasks share it. */ |
| 678 | const images = () => [...new Set(main().flatMap((container) => container.image ?? []))].map((image) => ({ |
| 679 | image, tasks: main().filter((container) => container.image === image).map((container) => container.name), |
| 680 | })); |
| 681 | const [clearing, setClearing] = createSignal(false); |
| 682 | const acknowledge = () => { |
| 683 | setClearing(true); |
| 684 | parseResponse(api.services[":id"].restarts.acknowledge.$post({ param: { id: params.id } })) |
| 685 | .then(refresh, (failure) => toast(`Couldn't clear the restart. ${reason(failure)}`)) |
| 686 | .finally(() => setClearing(false)); |
| 687 | }; |
| 688 | const also = (verb: string) => data().dependents?.length |
| 689 | ? `, ${verb} ${new Intl.ListFormat("en").format(data().dependents!.map((link) => link.name))}` : ""; |
| 690 | const restart = () => showConfirmDialog({ |
| 691 | title: `Restart ${data().name}?`, |
| 692 | description: `${data().name} goes offline for a moment. Anyone using it is interrupted${also("as are")}.`, |
| 693 | confirmLabel: "restart", |
| 694 | onConfirm: () => act("restart"), |
| 695 | }); |
| 696 | const stop = () => showConfirmDialog({ |
| 697 | title: `Stop ${data().name}?`, |
| 698 | description: `${data().name} stays offline until you start it again. Anyone using it loses access${also("as do")}.`, |
| 699 | confirmLabel: "stop", |
| 700 | destructive: true, |
| 701 | onConfirm: () => act("stop"), |
| 702 | }); |
| 703 | const start = () => showConfirmDialog({ |
| 704 | title: `Start ${data().name}?`, |
| 705 | description: `${data().name} comes back online${data().release ? ` on release ${data().release!.slice(0, 8)}` : ""}.`, |
| 706 | confirmLabel: "start", |
| 707 | onConfirm: () => act("start"), |
| 708 | }); |
| 709 | const tabHref = (tab: string) => `/services/${data().id}${tab ? "/" + tab : ""}`; |
| 710 | let tools!: HTMLDivElement; |
| 711 | return ( |
| 712 | <ListPage id="service" class="service-page" flush head={ |
| 713 | <> |
| 714 | <div class="page-head"> |
| 715 | <span class="service-icon"><AppIcon id={data().id} name={data().name} icon={data().icon} /></span> |
| 716 | <h1>{data().name}</h1> |
| 717 | <Show when={data().url}>{(url) => <OpenApp app={data()} href={url()} icon={false} />}</Show> |
| 718 | <div class="stats"> |
| 719 | <Show when={started()} fallback={<span class="stat" role="status"><StatusLabel health={health()} /></span>}> |
| 720 | {(t) => ( |
| 721 | <span class="stat" role="status" tabIndex={0} |
| 722 | data-tip={[`since ${datetime(t())}`, ...data().checks.map((check) => `${check.name}: ${check.output}`)].join("; ")}> |
| 723 | <StatusLabel health="healthy">up {duration(Date.now() / 1000 - t())}</StatusLabel> |
| 724 | </span> |
| 725 | )} |
| 726 | </Show> |
| 727 | <For each={images()}> |
| 728 | {({ image, tasks }) => { |
| 729 | const [ref, digest] = image.split("@") as [string, string?]; |
| 730 | const [name, tag] = ref.slice(ref.lastIndexOf("/") + 1).split(":") as [string, string?]; |
| 731 | return ( |
| 732 | <span class="stat image"> |
| 733 | <Copy value={image} label={images().length > 1 ? `${tasks.join(" and ")} image` : "image"}> |
| 734 | <Package size={13} aria-hidden="true" /><b>{name}</b> |
| 735 | <span class="version">{digest ? digest.slice(digest.indexOf(":") + 1, digest.indexOf(":") + 9) : tag ?? "latest"}</span> |
| 736 | </Copy> |
| 737 | </span> |
| 738 | ); |
| 739 | }} |
| 740 | </For> |
| 741 | <For each={data().datasets}> |
| 742 | {(dataset) => ( |
| 743 | <A class="stat" href={`/storage?${new URLSearchParams({ dataset: dataset.name })}`} |
| 744 | data-tip={`${dataset.mountpoint}, ${bytes(dataset.snapshots)} more in snapshots`}> |
| 745 | <HardDrive size={13} aria-label="data" /><b>{bytes(dataset.used)}</b> |
| 746 | </A> |
| 747 | )} |
| 748 | </For> |
| 749 | <Show when={unacknowledged()}> |
| 750 | {(last) => ( |
| 751 | <span class="stat restart"> |
| 752 | <A href={`${tabHref("")}?at=${Math.floor(last().t)}`} |
| 753 | data-tip={`${last().reason}, ${plural(restarts(), "restart")} since deploy`}> |
| 754 | <RotateCcw size={13} aria-hidden="true" />restarted {ago(last().t)} |
| 755 | </A> |
| 756 | <button class="button icon-only" aria-label="Clear restart" data-tip="clear" disabled={clearing()} |
| 757 | aria-busy={clearing()} onClick={acknowledge}> |
| 758 | <Show when={!clearing()}><X size={12} /></Show> |
| 759 | </button> |
| 760 | </span> |
| 761 | )} |
| 762 | </Show> |
| 763 | </div> |
| 764 | <span class="spacer" /> |
| 765 | <button class="button" onClick={restart}>restart</button> |
| 766 | <Show when={health() === "stopped"} fallback={<button class="button danger" onClick={stop}>stop</button>}> |
| 767 | <button class="button" onClick={start}>start</button> |
| 768 | </Show> |
| 769 | </div> |
| 770 | <Show when={failing()}> |
| 771 | {(check) => ( |
| 772 | <div class="problem" role="status"> |
| 773 | <StatusLabel health={health()}>{check().name}</StatusLabel> |
| 774 | <span class="output">{check().output}</span> |
| 775 | <A href={`${tabHref("")}?level=error`}>error logs</A> |
| 776 | </div> |
| 777 | )} |
| 778 | </Show> |
| 779 | </> |
| 780 | } summary={ |
| 781 | <div class="service-strips"> |
| 782 | <Strip title="cpu" metric="service.cpu" service={data().id} range={range()} format={cores} |
| 783 | height={64} tabs={<RangePicker value={range()} onChange={setRange} />} |
| 784 | now={reading(tick()?.cpu ?? data().cpu, `${cores(data().cpuLimit)} cores reserved`, cores)} /> |
| 785 | <Strip title="memory" metric="service.memory" service={data().id} range={range()} format={bytes} |
| 786 | max={data().memoryLimit} height={64 + 24} last |
| 787 | now={reading(tick()?.memory ?? data().memory, `${bytes(data().memoryLimit)} limit`, bytes)} /> |
| 788 | </div> |
| 789 | }> |
| 790 | <div ref={tools} class="tab-row"> |
| 791 | <TabBar label="View"> |
| 792 | <For each={TABS.filter(([tab]) => tab !== "traces" || data().applicationTraces).filter(([tab]) => tab !== "metrics" || data().applicationMetrics.length > 0)}> |
| 793 | {([tab, label]) => <A href={tabHref(tab)} end>{label}</A>} |
| 794 | </For> |
| 795 | </TabBar> |
| 796 | </div> |
| 797 | <Switch> |
| 798 | <Match when={!params.tab}><Logs service={data()} tools={tools} /></Match> |
| 799 | <Match when={params.tab === "traces" && data().applicationTraces}><Traces service={data()} tools={tools} /></Match> |
| 800 | <Match when={params.tab === "metrics" && data().applicationMetrics.length > 0}><AppMetrics service={data()} range={range()} /></Match> |
| 801 | <Match when={params.tab === "secrets"}><Secrets service={data()} onChange={refresh} /></Match> |
| 802 | <Match when={params.tab === "definition"}><Definition service={data()} /></Match> |
| 803 | </Switch> |
| 804 | </ListPage> |
| 805 | ); |
| 806 | }} |
| 807 | </Loaded> |
| 808 | ); |
| 809 | } |