window.rustProxyDockerDashboard = (() => { const BASES = ["docker_agents", "docker_apps", "docker_requests", "docker_host_network", "docker_host_load", "docker_containers"]; const INSTANCES = 4; const ids = BASES.flatMap(base => Array.from({ length: INSTANCES }, (_, index) => index ? `${base}_${index + 1}` : base)); const baseOf = id => id.replace(/_[2-9]$/, ""); const suffixOf = id => { const match = id.match(/_([2-9])$/); return match ? `-i${match[1]}` : ""; }; const series = new Map(); const chart = id => { if (!series.has(id)) series.set(id, { last: null, points: [], rx: [], tx: [] }); return series.get(id); }; const configuredAgents = () => (envelope?.config?.docker_agents?.agents || []).filter(agent => agent.enabled !== false); const scopes = () => window.rustProxyPreferences?.current?.()?.docker_widget_agents || {}; function scopeOf(id) { const agent = scopes()[id]; return agent && configuredAgents().some(item => item.id === agent) ? agent : ""; } async function setScope(id, agent) { const next = { ...scopes() }; if (agent) next[id] = agent; else delete next[id]; series.delete(id); clearChart(id); try { await window.rustProxyPreferences.update({ docker_widget_agents: next }); } catch (error) { if (error?.status !== 401) toast(error.message, true); } syncCardControls(); if (typeof latestStatus !== "undefined" && latestStatus) render(latestStatus, null, false); } function scopeControl(id, className = "docker-widget-scope") { if (!ids.includes(id)) return null; const agents = configuredAgents(); if (agents.length < 2) return null; const select = el("select", undefined, className); select.setAttribute("aria-label", t("dockerWidgetScope")); select.title = t("dockerWidgetScope"); const all = el("option", t("dockerWidgetScopeAll")); all.value = ""; select.append(all); for (const agent of agents) { const option = el("option", agent.name || agent.id); option.value = agent.id; select.append(option); } select.value = scopeOf(id); select.addEventListener("change", () => void setScope(id, select.value)); return select; } const card = id => document.querySelector(`[data-dashboard-widget="${id}"]`); const shown = id => card(id) && !card(id).hidden; function syncCardControls() { for (const id of ids) { const node = card(id); if (!node) continue; const instance = id.match(/_([2-9])$/)?.[1]; if (instance) node.querySelector(":scope > span")?.setAttribute("data-instance", instance); const signature = `${configuredAgents().map(agent => `${agent.id}:${agent.name}`).join("|")}#${scopeOf(id)}`; if (node.dataset.dockerScope === signature) continue; node.dataset.dockerScope = signature; node.querySelector(":scope > .docker-widget-scope")?.remove(); const control = scopeControl(id); if (control) node.querySelector(":scope > span")?.after(control); } } let wasVisible = false; const set = (id, value) => { const node = $(id); if (node) node.textContent = value; }; const has = value => value !== undefined && value !== null; function clearChart(id) { const sfx = suffixOf(id), lines = { docker_requests: ["docker-dashboard-requests-line"], docker_host_network: ["docker-dashboard-rx", "docker-dashboard-tx"] }[baseOf(id)] || []; for (const line of lines) $(`${line}${sfx}`)?.setAttribute("points", "0,55 300,55"); } function clearCharts() { series.clear(); for (const id of ids) clearChart(id); } function syncVisibility(hiddenOverride = null) { const prefs = window.rustProxyPreferences?.current?.(); const hidden = new Set(hiddenOverride ?? window.rustProxyInlineLayout?.currentDraft?.()?.hidden ?? prefs?.dashboard_hidden_widgets ?? ADMIN_APPEARANCE_DEFAULTS.dashboard_hidden_widgets); for (const id of ids) if (card(id)) card(id).hidden = hidden.has(id); for (const id of ids) if (!shown(id) && series.has(id)) { series.delete(id); clearChart(id); } wasVisible = ids.some(shown); } function line(points, peak) { return points.map((value, i) => `${i * 300 / Math.max(1, points.length - 1)},${55 - value / Math.max(1, peak) * 50}`).join(" "); } function push(list, value) { list.push(value); if (list.length > window.rustProxyOverviewSamples.getLimit()) list.shift(); } function unavailable(id) { const sfx = suffixOf(id), base = baseOf(id); if (base === "docker_host_network") { set(`docker-dashboard-network${sfx}`, "-"); set(`docker-dashboard-rx-rate${sfx}`, "-"); set(`docker-dashboard-tx-rate${sfx}`, "-"); } else { const name = { docker_agents: "agents", docker_apps: "apps", docker_requests: "requests", docker_host_load: "load", docker_containers: "containers" }[base]; set(`docker-dashboard-${name}${sfx}`, "-"); set(`docker-dashboard-${name}-detail${sfx}`, t("dockerWidgetUnavailable")); } if (base === "docker_host_load") $(`docker-dashboard-load-list${sfx}`)?.replaceChildren(); series.delete(id); clearChart(id); } function loadRow(agent) { const system = agent.system || {}, row = el("div", undefined, "docker-load-row"), name = el("span", agent.name || agent.id, "docker-load-name"); name.title = `${agent.name || agent.id}${system.os ? ` · ${system.os}` : ""}${has(system.uptime_seconds) ? ` · ${t("dockerSystemUptime")}: ${uptime(system.uptime_seconds)}` : ""}`; const bar = (label, pct, title) => { const wrap = el("span", undefined, "docker-load-bar"), meter = el("i"), fill = el("b"); const value = Math.max(0, Math.min(100, Number(pct) || 0)); fill.style.width = `${value}%`; if (value >= 90) meter.className = "is-high"; else if (value >= 75) meter.className = "is-warn"; meter.append(fill); wrap.append(el("small", label), meter); wrap.title = title; return wrap; }; row.append(name); if (!agent.ok) { row.append(el("span", t("dockerError"), "docker-load-offline")); return row; } if (has(system.cpu_percent)) row.append(bar("CPU", system.cpu_percent, `CPU ${Number(system.cpu_percent).toFixed(1)}%`)); if (has(system.memory_total_bytes) && has(system.memory_available_bytes)) { const total = Number(system.memory_total_bytes), used = Math.max(0, total - Number(system.memory_available_bytes)); row.append(bar("MEM", total ? used / total * 100 : 0, `${t("dockerSystemMemory")}: ${bytes(used)} / ${bytes(total)}`)); } if (has(system.load1)) row.append(el("span", Number(system.load1).toFixed(2), "docker-load-value")); if (row.children.length === 1) row.append(el("span", t("dockerWidgetNoSystem"), "docker-load-offline")); return row; } const onlineOf = list => list.filter(agent => agent.ok), systemsOf = list => onlineOf(list).map(agent => agent.system).filter(Boolean); const RENDERERS = { docker_agents(id, sfx, agents) { const online = onlineOf(agents), attention = agents.filter(agent => agent.observed && !agent.ok).length, waiting = agents.filter(agent => !agent.observed).length; set(`docker-dashboard-agents${sfx}`, `${online.length}/${agents.length}`); set(`docker-dashboard-agents-detail${sfx}`, [t("dockerWidgetOnline"), attention ? `${attention} ${t("dockerWidgetAttention")}` : "", waiting ? `${waiting} ${t("dockerWaiting").toLowerCase()}` : ""].filter(Boolean).join(" · ")); }, docker_apps(id, sfx, agents, status) { const poolIds = agents.flatMap(agent => agent.published_pool_ids || []), pools = new Map((status.backend_pools || []).map(pool => [pool.id, pool])); let up = 0, down = 0, other = 0; for (const poolId of poolIds) { const member = pools.get(poolId)?.members?.[0]; if (!member) other++; else if (member.status === "up") up++; else if (member.status === "down") down++; else other++; } const missing = agents.reduce((sum, agent) => sum + (Number(agent.missing_services) || 0), 0), discovered = agents.reduce((sum, agent) => sum + (Number(agent.services) || 0), 0); set(`docker-dashboard-apps${sfx}`, poolIds.length ? `${up}/${poolIds.length}` : "0"); set(`docker-dashboard-apps-detail${sfx}`, [t("vhUp").toLowerCase(), down ? `${down} ${t("dockerWidgetDown")}` : "", other ? `${other} ${t("dockerWidgetPending")}` : "", missing ? `${missing} ${t("dockerWidgetMissing")}` : ""].filter(Boolean).join(" · ")); const detail = $(`docker-dashboard-apps-detail${sfx}`); if (detail) detail.title = `${up} ${t("vhUp").toLowerCase()} · ${down} ${t("dockerWidgetDown")} · ${other} ${t("dockerWidgetPending")} · ${missing} ${t("dockerWidgetMissing")} · ${discovered} ${t("dockerWidgetDiscovered")}`; }, docker_requests(id, sfx, agents, status, recordSample) { const requests = chart(id), poolIds = agents.flatMap(agent => agent.published_pool_ids || []), metrics = status.vhost_metrics || {}, views = poolIds.map(poolId => metrics[poolId]).filter(Boolean); const total = views.reduce((sum, view) => sum + (Number(view.requests) || 0), 0), active = views.reduce((sum, view) => sum + (Number(view.active) || 0), 0), errors = views.reduce((sum, view) => sum + (Number(view.errors) || 0), 0); if (!views.length) { set(`docker-dashboard-requests${sfx}`, "-"); set(`docker-dashboard-requests-detail${sfx}`, t("dockerWidgetNoTraffic")); return; } if (!recordSample) return; const sample = rustProxyRateSampling.difference(requests.last, [total], performance.now(), rustProxyRateSampling.cadence("overview_seconds")); const paused = requests.last !== null && sample.deltas === null; requests.last = sample.next; const rate = sample.deltas ? sample.deltas[0] / sample.seconds : 0; if (!paused) push(requests.points, rate); set(`docker-dashboard-requests${sfx}`, paused ? "-" : `${rate.toFixed(1)}/s`); set(`docker-dashboard-requests-detail${sfx}`, `${fmt(active)} ${t("vhActive").toLowerCase()} · ${fmt(errors)} ${t("vhErrors").toLowerCase()}`); const peak = Math.max(1, ...requests.points); $(`docker-dashboard-requests-line${sfx}`)?.setAttribute("points", line(requests.points, peak)); window.rustProxyChartScale.axes(`docker-dashboard-requests-line${sfx}`, peak, "rate", requests.points.length, { top: 5 / 60, bottom: 55 / 60 }); }, docker_host_network(id, sfx, agents, status, recordSample) { const network = chart(id), withRates = systemsOf(agents).filter(system => has(system.network_rx_bytes_per_second)); if (!withRates.length) { set(`docker-dashboard-network${sfx}`, "-"); set(`docker-dashboard-rx-rate${sfx}`, "-"); set(`docker-dashboard-tx-rate${sfx}`, "-"); return; } const rx = withRates.reduce((sum, system) => sum + Number(system.network_rx_bytes_per_second), 0), tx = withRates.reduce((sum, system) => sum + Number(system.network_tx_bytes_per_second || 0), 0); if (recordSample) { push(network.rx, rx); push(network.tx, tx); } set(`docker-dashboard-network${sfx}`, `${rateBytes(rx + tx)}/s`); set(`docker-dashboard-rx-rate${sfx}`, `${rateBytes(rx)}/s`); set(`docker-dashboard-tx-rate${sfx}`, `${rateBytes(tx)}/s`); const peak = Math.max(1, ...network.rx, ...network.tx); $(`docker-dashboard-rx${sfx}`)?.setAttribute("points", line(network.rx, peak)); $(`docker-dashboard-tx${sfx}`)?.setAttribute("points", line(network.tx, peak)); window.rustProxyChartScale.axes(`docker-dashboard-rx${sfx}`, peak, "bytes/s", network.rx.length, { top: 5 / 60, bottom: 55 / 60 }); }, docker_host_load(id, sfx, agents) { const systems = systemsOf(agents), cpu = systems.filter(system => has(system.cpu_percent)).map(system => Number(system.cpu_percent)), busiest = cpu.length ? Math.max(...cpu) : null; set(`docker-dashboard-load${sfx}`, busiest === null ? "-" : `${busiest.toFixed(0)}%`); $(`docker-dashboard-load-list${sfx}`)?.replaceChildren(...agents.map(loadRow)); const loads = systems.filter(system => has(system.load1) && Number(system.cpu_count) > 0).map(system => Number(system.load1) / Number(system.cpu_count)); set(`docker-dashboard-load-detail${sfx}`, systems.length ? t("dockerWidgetBusiestCpu") : t("dockerWidgetNoSystem")); const loadDetail = $(`docker-dashboard-load-detail${sfx}`); if (loadDetail) loadDetail.title = loads.length ? `${t("dockerSystemLoadPerCpu")} ≤ ${Math.max(...loads).toFixed(2)}` : ""; }, docker_containers(id, sfx, agents) { const systems = systemsOf(agents), counted = systems.filter(system => has(system.containers_running)); if (!counted.length) { set(`docker-dashboard-containers${sfx}`, "-"); set(`docker-dashboard-containers-detail${sfx}`, t("dockerWidgetNoSystem")); return; } const running = counted.reduce((sum, system) => sum + Number(system.containers_running), 0), total = counted.reduce((sum, system) => sum + Number(system.containers_total || 0), 0), images = counted.reduce((sum, system) => sum + Number(system.images || 0), 0); const docker = systems.filter(system => system.runtime === "docker").length, podman = systems.filter(system => system.runtime === "podman").length; set(`docker-dashboard-containers${sfx}`, `${fmt(running)}/${fmt(total)}`); set(`docker-dashboard-containers-detail${sfx}`, [t("dockerWidgetRunning"), docker ? `Docker ${docker}` : "", podman ? `Podman ${podman}` : ""].filter(Boolean).join(" · ")); const detail = $(`docker-dashboard-containers-detail${sfx}`); if (detail) detail.title = `${t("dockerSystemImages")}: ${fmt(images)}`; }, }; function render(status, hiddenOverride = null, recordSample = true) { syncVisibility(hiddenOverride); if (!status || currentPanel !== "overview" || !ids.some(shown)) return; syncCardControls(); const enabledAgents = (status.docker?.agents || []).filter(agent => agent.enabled !== false); for (const id of ids.filter(shown)) { if (!enabledAgents.length) { unavailable(id); continue; } const agent = scopeOf(id), agents = agent ? enabledAgents.filter(item => item.id === agent) : enabledAgents; RENDERERS[baseOf(id)](id, suffixOf(id), agents, status, recordSample); } } function reset() { clearCharts(); wasVisible = false; } window.rustProxyOverviewSamples.onChange(() => { for (const entry of series.values()) for (const list of [entry.points, entry.rx, entry.tx]) window.rustProxyOverviewSamples.trim(list); if (typeof latestStatus !== "undefined" && latestStatus && currentPanel === "overview") render(latestStatus, null, false); }); const ALERT_KEYS = { agent_offline: "dockerAlertAgentOffline", disk_high: "dockerAlertDiskHigh", memory_high: "dockerAlertMemoryHigh", load_high: "dockerAlertLoadHigh", service_missing: "dockerAlertServiceMissingText", container_unhealthy: "dockerAlertContainerUnhealthy", label_invalid: "dockerAlertLabelInvalid" }; function alertText(alert) { const key = ALERT_KEYS[alert.kind]; if (!key) return `${alert.agent_name || alert.agent_id}: ${alert.kind}`; const since = alert.since_unix_ms ? new Date(alert.since_unix_ms).toLocaleTimeString(locale()) : "-"; return t(key).replace("{agent}", alert.agent_name || alert.agent_id).replace("{service}", alert.service || "-").replace("{value}", alert.value ?? "-").replace("{threshold}", alert.threshold ?? "-").replace("{since}", since).replace("{message}", alert.message || "-"); } let seenAlerts = null; function notify(status) { const alerts = status?.docker?.alerts; if (!Array.isArray(alerts)) return; const keys = new Set(alerts.map(alert => alert.key)); if (seenAlerts === null) { seenAlerts = keys; if (alerts.length) toast(t("dockerAlertsTitle").replace("{count}", alerts.length), alerts.some(alert => alert.severity === "error")); return; } for (const alert of alerts) if (!seenAlerts.has(alert.key)) toast(alertText(alert), alert.severity === "error"); seenAlerts = keys; } function healthCheck(status) { const alerts = status?.docker?.alerts; if (!status?.docker) return null; if (!alerts?.length) return { level: "ok", label: t("dockerAlertsHealth"), detail: t("dockerAlertsNone") }; const detail = alerts.slice(0, 4).map(alertText).join(" · ") + (alerts.length > 4 ? ` · +${alerts.length - 4}` : ""); return { level: alerts.some(alert => alert.severity === "error") ? "error" : "warning", label: t("dockerAlertsHealth"), detail }; } return { syncVisibility, render, reset() { reset(); seenAlerts = null; }, scopeControl, scopeOf, alertText, notify, healthCheck, ids }; })();