mirror of
https://github.com/cozystack/cozystack.git
synced 2026-11-22 12:43:32 +09:00
feat(dashboard): show resource consumption on application pages
Tenants had no way to see what their applications consume. A Metrics tab on every application detail page (except VM disks, which run no containers) charts CPU, memory and network for a selectable range through the observability proxy's application root, which injects the scope server-side, so the queries stay kind-agnostic and no per-kind UI is needed. Charts use uPlot: about 25 KB gzipped with no dependencies, built for time series, and loaded only with the Metrics tab so other pages do not pay for it. A cluster without the proxy answers 404 and the tab says metrics are not available there instead of showing an error. Assisted-by: LLM Signed-off-by: ZverGuy <maximbel2003@gmail.com>
This commit is contained in:
1 parent
e96ceedd7e
commit
063e56ede5
16 files changed
+690
-1
No files matched your search
@@ -31,7 +31,8 @@
|
||||
"react": "^19.2.4",
|
||||
"react-dom": "^19.2.4",
|
||||
"react-router": "^7.6.1",
|
||||
"simple-icons": "^16.22.0"
|
||||
"simple-icons": "^16.22.0",
|
||||
"uplot": "^1.6.32"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "^4.2.2",
|
||||
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
import { describe, it, expect, vi } from "vitest"
|
||||
import { screen, waitFor } from "@testing-library/react"
|
||||
import userEvent from "@testing-library/user-event"
|
||||
import { K8sClient } from "@cozystack/k8s-client"
|
||||
import { renderWithK8sProvider } from "../../test-utils/render.tsx"
|
||||
import type { ChartData } from "../../lib/observability/metrics.ts"
|
||||
|
||||
vi.mock("./TimeSeriesChart.tsx", () => ({
|
||||
TimeSeriesChart: ({ data }: { data: ChartData }) => (
|
||||
<div data-testid="chart">{data.series.map((s) => s.label).join(",")}</div>
|
||||
),
|
||||
}))
|
||||
|
||||
const { MetricsView } = await import("./MetricsView.tsx")
|
||||
|
||||
const scope = { namespace: "tenant-a", plural: "postgreses", name: "db" }
|
||||
|
||||
function matrix(pod: string) {
|
||||
return Response.json({
|
||||
status: "success",
|
||||
data: { resultType: "matrix", result: [{ metric: { pod }, values: [[1, "1"]] }] },
|
||||
})
|
||||
}
|
||||
|
||||
function clientWith(handler: (url: URL) => Response) {
|
||||
const client = new K8sClient()
|
||||
const raw = vi.spyOn(client, "raw").mockImplementation(async (path) => handler(new URL(path, "http://x")))
|
||||
return { client, raw }
|
||||
}
|
||||
|
||||
describe("MetricsView", () => {
|
||||
it("draws CPU, memory and network from the application root", async () => {
|
||||
const { client, raw } = clientWith(() => matrix("db-0"))
|
||||
|
||||
renderWithK8sProvider(<MetricsView scope={scope} />, { client })
|
||||
|
||||
await waitFor(() => expect(screen.getAllByTestId("chart")).toHaveLength(3))
|
||||
expect(screen.getByText("CPU (cores)")).toBeInTheDocument()
|
||||
expect(screen.getByText("Memory (working set)")).toBeInTheDocument()
|
||||
expect(screen.getByText("Network")).toBeInTheDocument()
|
||||
for (const [path] of raw.mock.calls) {
|
||||
expect(path.startsWith("/apis/apps.cozystack.io/v1alpha1/namespaces/tenant-a/postgreses/db/metrics/api/v1/query_range?")).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it("requeries with a coarser step when a longer range is picked", async () => {
|
||||
const { client, raw } = clientWith(() => matrix("db-0"))
|
||||
renderWithK8sProvider(<MetricsView scope={scope} />, { client })
|
||||
await waitFor(() => expect(raw).toHaveBeenCalled())
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: "7d" }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(raw.mock.calls.some(([p]) => new URL(p, "http://x").searchParams.get("step") === "2520")).toBe(true),
|
||||
)
|
||||
})
|
||||
|
||||
it("shows one quiet notice instead of three errors when the proxy is absent", async () => {
|
||||
const { client } = clientWith(() => new Response("404 page not found", { status: 404 }))
|
||||
|
||||
renderWithK8sProvider(<MetricsView scope={scope} />, { client })
|
||||
|
||||
expect(await screen.findByText("Metrics are not available on this cluster.")).toBeInTheDocument()
|
||||
expect(screen.getAllByRole("status")).toHaveLength(1)
|
||||
expect(screen.queryByText("CPU (cores)")).toBeNull()
|
||||
})
|
||||
|
||||
it("keeps the other panels when one query hits a limit", async () => {
|
||||
const { client } = clientWith((url) =>
|
||||
url.searchParams.get("query")?.includes("memory")
|
||||
? Response.json({ status: "error", error: "too many series" }, { status: 422 })
|
||||
: matrix("db-0"),
|
||||
)
|
||||
|
||||
renderWithK8sProvider(<MetricsView scope={scope} />, { client })
|
||||
|
||||
expect(await screen.findByText("too many series. Choose a shorter range.")).toBeInTheDocument()
|
||||
await waitFor(() => expect(screen.getAllByTestId("chart")).toHaveLength(2))
|
||||
})
|
||||
|
||||
it("says so when a panel has no data", async () => {
|
||||
const { client } = clientWith(() => Response.json({ status: "success", data: { resultType: "matrix", result: [] } }))
|
||||
|
||||
renderWithK8sProvider(<MetricsView scope={scope} />, { client })
|
||||
|
||||
await waitFor(() => expect(screen.getAllByText("No data for this range.")).toHaveLength(3))
|
||||
})
|
||||
})
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
import { useState } from "react"
|
||||
import { useQueries } from "@tanstack/react-query"
|
||||
import { useK8sClient } from "@cozystack/k8s-client"
|
||||
import { Section, Spinner } from "@cozystack/ui"
|
||||
import {
|
||||
METRIC_PANELS,
|
||||
RANGES,
|
||||
rangeWindow,
|
||||
toChartData,
|
||||
type RangeKey,
|
||||
} from "../../lib/observability/metrics.ts"
|
||||
import { isScopeWide, metricsRoot, queryRange, type ObservabilityScope } from "../../lib/observability/proxy.ts"
|
||||
import { ProxyNotice } from "./ProxyNotice.tsx"
|
||||
import { TimeSeriesChart } from "./TimeSeriesChart.tsx"
|
||||
import { RangePicker } from "./RangePicker.tsx"
|
||||
|
||||
const REFRESH_MS = 60_000
|
||||
|
||||
export function MetricsView({ scope }: { scope: ObservabilityScope }) {
|
||||
const client = useK8sClient()
|
||||
const root = metricsRoot(scope)
|
||||
const [range, setRange] = useState<RangeKey>("1h")
|
||||
|
||||
const results = useQueries({
|
||||
queries: METRIC_PANELS.map((panel) => ({
|
||||
queryKey: ["observability", "metrics", root, panel.id, range],
|
||||
queryFn: async ({ signal }: { signal: AbortSignal }) => {
|
||||
const window = rangeWindow(range, Math.floor(Date.now() / 1000))
|
||||
const series = await Promise.all(
|
||||
panel.queries(window).map(async (q) => ({
|
||||
label: q.label,
|
||||
series: await queryRange(client, root, { query: q.expr, ...window }, signal),
|
||||
})),
|
||||
)
|
||||
return toChartData(series)
|
||||
},
|
||||
retry: false,
|
||||
refetchInterval: REFRESH_MS,
|
||||
})),
|
||||
})
|
||||
|
||||
const wide = results.find((r) => isScopeWide(r.error))?.error
|
||||
|
||||
return (
|
||||
<div className="space-y-4 p-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-sm font-semibold text-slate-900">Resource consumption</h2>
|
||||
<RangePicker options={Object.keys(RANGES) as RangeKey[]} value={range} onChange={setRange} />
|
||||
</div>
|
||||
{wide ? (
|
||||
<ProxyNotice what="Metrics" error={wide} />
|
||||
) : (
|
||||
METRIC_PANELS.map((panel, i) => {
|
||||
const { data, error, isLoading } = results[i]
|
||||
return (
|
||||
<Section key={panel.id} title={panel.title}>
|
||||
{error ? (
|
||||
<ProxyNotice what="Metrics" error={error} />
|
||||
) : isLoading || !data ? (
|
||||
<Spinner />
|
||||
) : data.series.length === 0 ? (
|
||||
<p className="text-sm text-slate-500">No data for this range.</p>
|
||||
) : (
|
||||
<TimeSeriesChart data={data} format={panel.format} />
|
||||
)}
|
||||
</Section>
|
||||
)
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
import { describe, it, expect } from "vitest"
|
||||
import { render, screen } from "@testing-library/react"
|
||||
import { ProxyError } from "../../lib/observability/proxy.ts"
|
||||
import { ProxyNotice } from "./ProxyNotice.tsx"
|
||||
|
||||
describe("ProxyNotice", () => {
|
||||
it("renders a 404 as not available on this cluster, not as an error", () => {
|
||||
render(<ProxyNotice what="Metrics" error={new ProxyError("not-available", 404, "page not found")} />)
|
||||
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Metrics are not available on this cluster.")
|
||||
expect(screen.queryByRole("alert")).toBeNull()
|
||||
})
|
||||
|
||||
it("renders a 502 as a quiet notice about the store", () => {
|
||||
render(<ProxyNotice what="Logs" error={new ProxyError("store-unreachable", 502, "dial tcp")} />)
|
||||
|
||||
expect(screen.getByRole("status")).toHaveTextContent("The logs store is unreachable right now.")
|
||||
})
|
||||
|
||||
it.each([
|
||||
["forbidden", 403, "You do not have permission to read metrics here."],
|
||||
["limit", 422, "too many points. Choose a shorter range."],
|
||||
["rate-limited", 429, "Too many requests. Try again in a moment."],
|
||||
["timeout", 504, "The store did not answer in time. Choose a shorter range or a narrower filter."],
|
||||
["unavailable", 503, "The service is temporarily unavailable. Try again in a moment."],
|
||||
] as const)("explains %s", (kind, status, text) => {
|
||||
render(<ProxyNotice what="Metrics" error={new ProxyError(kind, status, "too many points")} />)
|
||||
|
||||
expect(screen.getByRole("alert")).toHaveTextContent(text)
|
||||
})
|
||||
|
||||
it("shows the server message for a rejected query", () => {
|
||||
render(<ProxyNotice what="Logs" error={new ProxyError("bad-request", 400, "cannot parse query")} />)
|
||||
|
||||
expect(screen.getByRole("alert")).toHaveTextContent("cannot parse query")
|
||||
})
|
||||
|
||||
it("falls back to the message of an unexpected error", () => {
|
||||
render(<ProxyNotice what="Logs" error={new Error("boom")} />)
|
||||
|
||||
expect(screen.getByRole("alert")).toHaveTextContent("boom")
|
||||
})
|
||||
})
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
import { ProxyError } from "../../lib/observability/proxy.ts"
|
||||
|
||||
interface ProxyNoticeProps {
|
||||
what: "Metrics" | "Logs"
|
||||
error: unknown
|
||||
}
|
||||
|
||||
function describe(what: ProxyNoticeProps["what"], error: unknown): { quiet: boolean; text: string } {
|
||||
const lower = what.toLowerCase()
|
||||
if (!(error instanceof ProxyError)) {
|
||||
return { quiet: false, text: error instanceof Error ? error.message : String(error) }
|
||||
}
|
||||
switch (error.kind) {
|
||||
case "not-available":
|
||||
return { quiet: true, text: `${what} are not available on this cluster.` }
|
||||
case "store-unreachable":
|
||||
return { quiet: true, text: `The ${lower} store is unreachable right now.` }
|
||||
case "unauthorized":
|
||||
return { quiet: false, text: "Your session has expired. Sign in again." }
|
||||
case "forbidden":
|
||||
return { quiet: false, text: `You do not have permission to read ${lower} here.` }
|
||||
case "limit":
|
||||
return { quiet: false, text: `${error.message}. Choose a shorter range.` }
|
||||
case "rate-limited":
|
||||
return { quiet: false, text: "Too many requests. Try again in a moment." }
|
||||
case "timeout":
|
||||
return { quiet: false, text: "The store did not answer in time. Choose a shorter range or a narrower filter." }
|
||||
case "unavailable":
|
||||
return { quiet: false, text: "The service is temporarily unavailable. Try again in a moment." }
|
||||
default:
|
||||
return { quiet: false, text: error.message }
|
||||
}
|
||||
}
|
||||
|
||||
export function ProxyNotice({ what, error }: ProxyNoticeProps) {
|
||||
const { quiet, text } = describe(what, error)
|
||||
if (quiet) {
|
||||
return (
|
||||
<p role="status" className="rounded-md border border-slate-200 bg-slate-50 px-4 py-3 text-sm text-slate-600">
|
||||
{text}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<p role="alert" className="rounded-md border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800">
|
||||
{text}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
import { cn } from "@cozystack/ui"
|
||||
|
||||
export function RangePicker<K extends string>({
|
||||
options,
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
options: readonly K[]
|
||||
value: K
|
||||
onChange: (value: K) => void
|
||||
}) {
|
||||
return (
|
||||
<div className="inline-flex rounded-md border border-slate-200 bg-white p-0.5">
|
||||
{options.map((key) => (
|
||||
<button
|
||||
key={key}
|
||||
type="button"
|
||||
aria-pressed={value === key}
|
||||
onClick={() => onChange(key)}
|
||||
className={cn(
|
||||
"rounded px-2.5 py-1 text-xs",
|
||||
value === key ? "bg-slate-900 text-white" : "text-slate-600 hover:bg-slate-100",
|
||||
)}
|
||||
>
|
||||
{key}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest"
|
||||
import { render } from "@testing-library/react"
|
||||
|
||||
const created: { opts: { series: { label?: string }[] }; data: unknown[]; destroy: ReturnType<typeof vi.fn> }[] = []
|
||||
|
||||
vi.mock("uplot", () => ({
|
||||
default: class {
|
||||
destroy = vi.fn()
|
||||
constructor(opts: { series: { label?: string }[] }, data: unknown[]) {
|
||||
created.push({ opts, data, destroy: this.destroy })
|
||||
}
|
||||
setSize() {}
|
||||
},
|
||||
}))
|
||||
|
||||
const { TimeSeriesChart } = await import("./TimeSeriesChart.tsx")
|
||||
|
||||
beforeEach(() => {
|
||||
created.length = 0
|
||||
})
|
||||
|
||||
describe("TimeSeriesChart", () => {
|
||||
const data = {
|
||||
timestamps: [1, 2],
|
||||
series: [
|
||||
{ label: "db-0", values: [1, 2] },
|
||||
{ label: "db-1", values: [null, 3] },
|
||||
],
|
||||
}
|
||||
|
||||
it("hands uPlot the timestamps first and one labelled series per input", () => {
|
||||
render(<TimeSeriesChart data={data} format={String} />)
|
||||
|
||||
expect(created).toHaveLength(1)
|
||||
expect(created[0].data).toEqual([[1, 2], [1, 2], [null, 3]])
|
||||
expect(created[0].opts.series.slice(1).map((s) => s.label)).toEqual(["db-0", "db-1"])
|
||||
})
|
||||
|
||||
it("destroys the chart on unmount", () => {
|
||||
const { unmount } = render(<TimeSeriesChart data={data} format={String} />)
|
||||
|
||||
unmount()
|
||||
|
||||
expect(created[0].destroy).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
import { useEffect, useRef } from "react"
|
||||
import uPlot from "uplot"
|
||||
import "uplot/dist/uPlot.min.css"
|
||||
import type { ChartData } from "../../lib/observability/metrics.ts"
|
||||
|
||||
const COLORS = ["#2563eb", "#16a34a", "#d97706", "#9333ea", "#dc2626", "#0891b2", "#4b5563", "#db2777"]
|
||||
const HEIGHT = 200
|
||||
|
||||
interface TimeSeriesChartProps {
|
||||
data: ChartData
|
||||
format: (value: number) => string
|
||||
}
|
||||
|
||||
export function TimeSeriesChart({ data, format }: TimeSeriesChartProps) {
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const el = ref.current
|
||||
if (!el) return
|
||||
const fmt = (v: number | null) => (v === null ? "–" : format(v))
|
||||
const chart = new uPlot(
|
||||
{
|
||||
width: el.clientWidth || 600,
|
||||
height: HEIGHT,
|
||||
scales: { x: { time: true } },
|
||||
legend: { live: true },
|
||||
series: [
|
||||
{},
|
||||
...data.series.map((s, i) => ({
|
||||
label: s.label,
|
||||
stroke: COLORS[i % COLORS.length],
|
||||
width: 1.5,
|
||||
value: (_: uPlot, v: number | null) => fmt(v),
|
||||
})),
|
||||
],
|
||||
axes: [{}, { size: 70, values: (_: uPlot, splits: number[]) => splits.map(format) }],
|
||||
},
|
||||
[data.timestamps, ...data.series.map((s) => s.values)],
|
||||
el,
|
||||
)
|
||||
if (typeof ResizeObserver === "undefined") return () => chart.destroy()
|
||||
const observer = new ResizeObserver(() => chart.setSize({ width: el.clientWidth, height: HEIGHT }))
|
||||
observer.observe(el)
|
||||
return () => {
|
||||
observer.disconnect()
|
||||
chart.destroy()
|
||||
}
|
||||
}, [data, format])
|
||||
|
||||
return <div ref={ref} className="w-full" />
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
import { describe, it, expect } from "vitest"
|
||||
import {
|
||||
METRIC_PANELS,
|
||||
formatBytes,
|
||||
formatCores,
|
||||
rangeWindow,
|
||||
toChartData,
|
||||
} from "./metrics.ts"
|
||||
|
||||
describe("rangeWindow", () => {
|
||||
it("ends now and spans the range in about 240 points", () => {
|
||||
const w = rangeWindow("6h", 1_000_000)
|
||||
|
||||
expect(w.end).toBe(1_000_000)
|
||||
expect(w.start).toBe(1_000_000 - 6 * 3600)
|
||||
expect(w.step).toBe(90)
|
||||
})
|
||||
|
||||
it("never steps finer than 15s", () => {
|
||||
expect(rangeWindow("1h", 0).step).toBe(15)
|
||||
})
|
||||
})
|
||||
|
||||
describe("METRIC_PANELS", () => {
|
||||
const window = { start: 0, end: 3600, step: 15 }
|
||||
|
||||
it("rates CPU over at least five minutes so sparse scrapes still draw", () => {
|
||||
const [query] = METRIC_PANELS.find((p) => p.id === "cpu")!.queries(window)
|
||||
|
||||
expect(query.expr).toBe(
|
||||
'sum by (pod) (rate(container_cpu_usage_seconds_total{container!="",container!="POD"}[300s]))',
|
||||
)
|
||||
})
|
||||
|
||||
it("widens the rate window with the step on long ranges", () => {
|
||||
const [query] = METRIC_PANELS.find((p) => p.id === "cpu")!.queries({ start: 0, end: 1, step: 2520 })
|
||||
|
||||
expect(query.expr).toContain("[5040s]")
|
||||
})
|
||||
|
||||
it("reads memory as working set per pod", () => {
|
||||
const [query] = METRIC_PANELS.find((p) => p.id === "memory")!.queries(window)
|
||||
|
||||
expect(query.expr).toBe('sum by (pod) (container_memory_working_set_bytes{container!="",container!="POD"})')
|
||||
})
|
||||
|
||||
it("draws network receive and transmit as two named series", () => {
|
||||
const queries = METRIC_PANELS.find((p) => p.id === "network")!.queries(window)
|
||||
|
||||
expect(queries.map((q) => q.label)).toEqual(["receive", "transmit"])
|
||||
expect(queries[0].expr).toBe("sum(rate(container_network_receive_bytes_total[300s]))")
|
||||
expect(queries[1].expr).toBe("sum(rate(container_network_transmit_bytes_total[300s]))")
|
||||
})
|
||||
|
||||
it("names no application kind in any query", () => {
|
||||
for (const panel of METRIC_PANELS) {
|
||||
for (const q of panel.queries(window)) expect(q.expr).not.toMatch(/apps_cozystack_io|namespace=/)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("toChartData", () => {
|
||||
it("aligns series on the union of timestamps and leaves gaps as null", () => {
|
||||
const data = toChartData([
|
||||
{ label: "a", series: [{ metric: {}, values: [[10, "1"], [20, "2"]] }] },
|
||||
{ label: "b", series: [{ metric: {}, values: [[20, "5"], [30, "6"]] }] },
|
||||
])
|
||||
|
||||
expect(data.timestamps).toEqual([10, 20, 30])
|
||||
expect(data.series).toEqual([
|
||||
{ label: "a", values: [1, 2, null] },
|
||||
{ label: "b", values: [null, 5, 6] },
|
||||
])
|
||||
})
|
||||
|
||||
it("labels each series by its pod, falling back to the query label", () => {
|
||||
const data = toChartData([
|
||||
{
|
||||
label: "cpu",
|
||||
series: [
|
||||
{ metric: { pod: "db-1" }, values: [[1, "0.5"]] },
|
||||
{ metric: {}, values: [[1, "0.1"]] },
|
||||
],
|
||||
},
|
||||
])
|
||||
|
||||
expect(data.series.map((s) => s.label)).toEqual(["db-1", "cpu"])
|
||||
})
|
||||
|
||||
it("drops NaN samples instead of drawing them as zero", () => {
|
||||
const data = toChartData([{ label: "x", series: [{ metric: {}, values: [[1, "NaN"]] }] }])
|
||||
|
||||
expect(data.series[0].values).toEqual([null])
|
||||
})
|
||||
})
|
||||
|
||||
describe("formatters", () => {
|
||||
it("formats CPU in millicores below one core", () => {
|
||||
expect(formatCores(0.25)).toBe("250m")
|
||||
expect(formatCores(2)).toBe("2")
|
||||
})
|
||||
|
||||
it("formats bytes with binary units", () => {
|
||||
expect(formatBytes(512)).toBe("512 B")
|
||||
expect(formatBytes(3 * 1024 * 1024)).toBe("3.0 MiB")
|
||||
})
|
||||
})
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
import type { PromSeries } from "./proxy.ts"
|
||||
|
||||
export const RANGES = {
|
||||
"1h": 3600,
|
||||
"6h": 6 * 3600,
|
||||
"24h": 24 * 3600,
|
||||
"7d": 7 * 24 * 3600,
|
||||
} as const
|
||||
|
||||
export type RangeKey = keyof typeof RANGES
|
||||
|
||||
export interface RangeWindow {
|
||||
start: number
|
||||
end: number
|
||||
step: number
|
||||
}
|
||||
|
||||
const POINTS = 240
|
||||
const MIN_STEP = 15
|
||||
|
||||
export function rangeWindow(range: RangeKey, nowSeconds: number): RangeWindow {
|
||||
const span = RANGES[range]
|
||||
return { start: nowSeconds - span, end: nowSeconds, step: Math.max(MIN_STEP, Math.round(span / POINTS)) }
|
||||
}
|
||||
|
||||
// A rate needs several scrapes inside its window, and on long ranges the window
|
||||
// must also cover the step or samples between points are skipped.
|
||||
function rateWindow(step: number): string {
|
||||
return `${Math.max(300, step * 2)}s`
|
||||
}
|
||||
|
||||
const CONTAINERS = 'container!="",container!="POD"'
|
||||
|
||||
export interface MetricQuery {
|
||||
label: string
|
||||
expr: string
|
||||
}
|
||||
|
||||
export interface MetricPanel {
|
||||
id: "cpu" | "memory" | "network"
|
||||
title: string
|
||||
format: (value: number) => string
|
||||
queries: (window: RangeWindow) => MetricQuery[]
|
||||
}
|
||||
|
||||
export function formatCores(value: number): string {
|
||||
if (value === 0) return "0"
|
||||
if (Math.abs(value) < 1) return `${Math.round(value * 1000)}m`
|
||||
return `${Number(value.toFixed(2))}`
|
||||
}
|
||||
|
||||
const BYTE_UNITS = ["B", "KiB", "MiB", "GiB", "TiB"]
|
||||
|
||||
export function formatBytes(value: number): string {
|
||||
let v = value
|
||||
let unit = 0
|
||||
while (Math.abs(v) >= 1024 && unit < BYTE_UNITS.length - 1) {
|
||||
v /= 1024
|
||||
unit++
|
||||
}
|
||||
return unit === 0 ? `${Math.round(v)} B` : `${v.toFixed(1)} ${BYTE_UNITS[unit]}`
|
||||
}
|
||||
|
||||
// The proxy injects the namespace or application scope, so these stay kind-agnostic.
|
||||
export const METRIC_PANELS: MetricPanel[] = [
|
||||
{
|
||||
id: "cpu",
|
||||
title: "CPU (cores)",
|
||||
format: formatCores,
|
||||
queries: ({ step }) => [
|
||||
{
|
||||
label: "cpu",
|
||||
expr: `sum by (pod) (rate(container_cpu_usage_seconds_total{${CONTAINERS}}[${rateWindow(step)}]))`,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "memory",
|
||||
title: "Memory (working set)",
|
||||
format: formatBytes,
|
||||
queries: () => [
|
||||
{ label: "memory", expr: `sum by (pod) (container_memory_working_set_bytes{${CONTAINERS}})` },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "network",
|
||||
title: "Network",
|
||||
format: (v) => `${formatBytes(v)}/s`,
|
||||
queries: ({ step }) => [
|
||||
{ label: "receive", expr: `sum(rate(container_network_receive_bytes_total[${rateWindow(step)}]))` },
|
||||
{ label: "transmit", expr: `sum(rate(container_network_transmit_bytes_total[${rateWindow(step)}]))` },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
export interface ChartSeries {
|
||||
label: string
|
||||
values: (number | null)[]
|
||||
}
|
||||
|
||||
export interface ChartData {
|
||||
timestamps: number[]
|
||||
series: ChartSeries[]
|
||||
}
|
||||
|
||||
export function toChartData(results: { label: string; series: PromSeries[] }[]): ChartData {
|
||||
const flat = results.flatMap(({ label, series }) =>
|
||||
series.map((s) => ({ label: s.metric.pod ?? label, points: new Map(s.values.map(([t, v]) => [t, Number(v)])) })),
|
||||
)
|
||||
const timestamps = [...new Set(flat.flatMap((s) => [...s.points.keys()]))].sort((a, b) => a - b)
|
||||
return {
|
||||
timestamps,
|
||||
series: flat.map(({ label, points }) => ({
|
||||
label,
|
||||
values: timestamps.map((t) => {
|
||||
const v = points.get(t)
|
||||
return v === undefined || Number.isNaN(v) ? null : v
|
||||
}),
|
||||
})),
|
||||
}
|
||||
}
|
||||
+10
@@ -4,6 +4,7 @@ import {
|
||||
ProxyError,
|
||||
errorKindForStatus,
|
||||
fieldValues,
|
||||
isScopeWide,
|
||||
logsRoot,
|
||||
metricsRoot,
|
||||
queryLogs,
|
||||
@@ -177,3 +178,12 @@ describe("tailLogs", () => {
|
||||
expect(err).toMatchObject({ kind: "forbidden" })
|
||||
})
|
||||
})
|
||||
|
||||
describe("isScopeWide", () => {
|
||||
it("is true for answers that do not depend on the query", () => {
|
||||
expect(isScopeWide(new ProxyError("not-available", 404, ""))).toBe(true)
|
||||
expect(isScopeWide(new ProxyError("forbidden", 403, ""))).toBe(true)
|
||||
expect(isScopeWide(new ProxyError("limit", 422, ""))).toBe(false)
|
||||
expect(isScopeWide(new Error("x"))).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -60,6 +60,14 @@ export class ProxyError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
// These answers hold for every query in the scope, so one notice replaces the whole view.
|
||||
export function isScopeWide(error: unknown): boolean {
|
||||
return (
|
||||
error instanceof ProxyError &&
|
||||
(error.kind === "not-available" || error.kind === "forbidden" || error.kind === "unauthorized")
|
||||
)
|
||||
}
|
||||
|
||||
// Prometheus answers {"error": "..."}, VictoriaLogs and nginx answer plain text.
|
||||
function errorMessage(text: string, status: number): string {
|
||||
try {
|
||||
|
||||
+28
@@ -59,6 +59,7 @@ vi.mock("./EventsTab.tsx", () => ({ EventsTab: () => null }))
|
||||
vi.mock("./VncTab.tsx", () => ({ VncTab: () => null }))
|
||||
vi.mock("./SerialTab.tsx", () => ({ SerialTab: () => null }))
|
||||
vi.mock("./VMPowerControls.tsx", () => ({ VMPowerControls: () => null }))
|
||||
vi.mock("./MetricsTab.tsx", () => ({ MetricsTab: () => null }))
|
||||
|
||||
const { ApplicationDetailPage } = await import("./ApplicationDetailPage.tsx")
|
||||
|
||||
@@ -111,11 +112,38 @@ describe("ApplicationDetailPage tabs for a virtual machine", () => {
|
||||
"VNC",
|
||||
"Workloads",
|
||||
"Services",
|
||||
"Metrics",
|
||||
"Events",
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe("ApplicationDetailPage observability tabs", () => {
|
||||
function showKind(kind: string, plural: string) {
|
||||
h.appKind = kind
|
||||
h.appPlural = plural
|
||||
h.get = {
|
||||
data: { kind, metadata: { name: "demo", namespace: "tenant-test" } },
|
||||
isLoading: false,
|
||||
error: undefined,
|
||||
}
|
||||
h.configMaps = []
|
||||
h.configMapsError = undefined
|
||||
h.tabLabels = []
|
||||
renderPage()
|
||||
}
|
||||
|
||||
it("offers Metrics on any application kind, ahead of Events", () => {
|
||||
showKind("Postgres", "postgreses")
|
||||
expect(h.tabLabels.slice(-3)).toEqual(["Secrets", "Metrics", "Events"])
|
||||
})
|
||||
|
||||
it("leaves Metrics off a VM disk, which runs no containers", () => {
|
||||
showKind("VMDisk", "vmdisks")
|
||||
expect(h.tabLabels).not.toContain("Metrics")
|
||||
})
|
||||
})
|
||||
|
||||
describe("ApplicationDetailPage configuration", () => {
|
||||
it("offers ConfigMaps declared by the application's resource map", () => {
|
||||
h.appKind = "FoundationDB"
|
||||
|
||||
+12
@@ -37,6 +37,8 @@ import { VncTab } from "./VncTab.tsx"
|
||||
// fetched only when a VM's console is opened. Every dashboard page reaches this
|
||||
// file, and most of them never touch a VM.
|
||||
const SerialTab = lazy(() => import("./SerialTab.tsx").then((m) => ({ default: m.SerialTab })))
|
||||
// Same for the charting library behind the Metrics tab.
|
||||
const MetricsTab = lazy(() => import("./MetricsTab.tsx").then((m) => ({ default: m.MetricsTab })))
|
||||
import { VMPowerControls } from "./VMPowerControls.tsx"
|
||||
import { useResourceBasePath } from "../../lib/portal.ts"
|
||||
import { useResourcePresence } from "./use-resource-presence.ts"
|
||||
@@ -143,6 +145,7 @@ export function ApplicationDetailPage() {
|
||||
{ to: `${base}/vnc`, label: "VNC", end: false },
|
||||
{ to: `${base}/workloads`, label: "Workloads", end: false },
|
||||
{ to: `${base}/services`, label: "Services", end: false },
|
||||
{ to: `${base}/metrics`, label: "Metrics", end: false },
|
||||
{ to: `${base}/events`, label: "Events", end: false },
|
||||
)
|
||||
} else {
|
||||
@@ -163,6 +166,7 @@ export function ApplicationDetailPage() {
|
||||
}
|
||||
tabs.push(
|
||||
{ to: `${base}/secrets`, label: "Secrets", end: false },
|
||||
{ to: `${base}/metrics`, label: "Metrics", end: false },
|
||||
{ to: `${base}/events`, label: "Events", end: false },
|
||||
)
|
||||
}
|
||||
@@ -262,6 +266,14 @@ export function ApplicationDetailPage() {
|
||||
}
|
||||
/>
|
||||
<Route path="vnc" element={<VncTab ad={ad} instance={instance} />} />
|
||||
<Route
|
||||
path="metrics"
|
||||
element={
|
||||
<Suspense fallback={<Spinner />}>
|
||||
<MetricsTab ad={ad} instance={instance} />
|
||||
</Suspense>
|
||||
}
|
||||
/>
|
||||
</Routes>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
import type { ApplicationDefinition, ApplicationInstance } from "@cozystack/types"
|
||||
import { useTenantContext } from "../../lib/tenant-context.tsx"
|
||||
import { MetricsView } from "../../components/observability/MetricsView.tsx"
|
||||
|
||||
interface MetricsTabProps {
|
||||
ad: ApplicationDefinition
|
||||
instance: ApplicationInstance
|
||||
}
|
||||
|
||||
export function MetricsTab({ ad, instance }: MetricsTabProps) {
|
||||
const { tenantNamespace } = useTenantContext()
|
||||
const plural = ad.spec?.application.plural
|
||||
if (!tenantNamespace || !plural) return null
|
||||
return <MetricsView scope={{ namespace: tenantNamespace, plural, name: instance.metadata.name }} />
|
||||
}
|
||||
@@ -92,6 +92,9 @@ importers:
|
||||
simple-icons:
|
||||
specifier: ^16.22.0
|
||||
version: 16.22.0
|
||||
uplot:
|
||||
specifier: ^1.6.32
|
||||
version: 1.6.32
|
||||
devDependencies:
|
||||
'@tailwindcss/vite':
|
||||
specifier: ^4.2.2
|
||||
@@ -1773,6 +1776,9 @@ packages:
|
||||
peerDependencies:
|
||||
browserslist: '>= 4.21.0'
|
||||
|
||||
uplot@1.6.32:
|
||||
resolution: {integrity: sha512-KIMVnG68zvu5XXUbC4LQEPnhwOxBuLyW1AHtpm6IKTXImkbLgkMy+jabjLgSLMasNuGGzQm/ep3tOkyTxpiQIw==}
|
||||
|
||||
uri-js@4.4.1:
|
||||
resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==}
|
||||
|
||||
@@ -3405,6 +3411,8 @@ snapshots:
|
||||
escalade: 3.2.0
|
||||
picocolors: 1.1.1
|
||||
|
||||
uplot@1.6.32: {}
|
||||
|
||||
uri-js@4.4.1:
|
||||
dependencies:
|
||||
punycode: 2.3.1
|
||||
|
||||
Reference in new issue
Block a user