mirror of
https://github.com/Termix-SSH/Termix.git
synced 2026-10-29 06:35:24 +00:00
feat: ship host metrics as a first-party in-process plugin
This commit is contained in:
1 parent
a2479c19b0
commit
19b70430a1
145 files changed
+675
-349
No files matched your search
@@ -1,52 +0,0 @@
|
||||
import React from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { HostMetricsTab } from "@/features/host-metrics/HostMetricsTab.tsx";
|
||||
import { FullScreenAppWrapper } from "@/features/FullScreenAppWrapper.tsx";
|
||||
import { ConnectionScreen } from "@/components/connection/ConnectionScreen.tsx";
|
||||
|
||||
interface HostMetricsAppProps {
|
||||
hostId?: string;
|
||||
}
|
||||
|
||||
const HostMetricsApp: React.FC<HostMetricsAppProps> = ({ hostId }) => {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<FullScreenAppWrapper hostId={hostId}>
|
||||
{(hostConfig, phase) => {
|
||||
if (phase === "loading") {
|
||||
return (
|
||||
<div className="relative h-full w-full">
|
||||
<ConnectionScreen
|
||||
status="connecting"
|
||||
message={t("hosts.loadingHost")}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!hostConfig) {
|
||||
return (
|
||||
<div className="relative h-full w-full">
|
||||
<ConnectionScreen
|
||||
status="disconnected"
|
||||
message={t("hosts.hostNotFound")}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<HostMetricsTab
|
||||
hostConfig={hostConfig}
|
||||
title={hostConfig.name || `${hostConfig.username}@${hostConfig.ip}`}
|
||||
isVisible={true}
|
||||
isTopbarOpen={false}
|
||||
embedded={true}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
</FullScreenAppWrapper>
|
||||
);
|
||||
};
|
||||
|
||||
export default HostMetricsApp;
|
||||
@@ -1,843 +0,0 @@
|
||||
import { getErrorMessage } from "../../lib/error-message.js";
|
||||
/* eslint-disable react-hooks/exhaustive-deps */
|
||||
import React from "react";
|
||||
import { Separator } from "@/components/separator.tsx";
|
||||
import { Button } from "@/components/button.tsx";
|
||||
import {
|
||||
getServerStatusById,
|
||||
getServerMetricsById,
|
||||
startMetricsPolling,
|
||||
stopMetricsPolling,
|
||||
submitMetricsTOTP,
|
||||
executeSnippet,
|
||||
getSnippets,
|
||||
logActivity,
|
||||
sendMetricsHeartbeat,
|
||||
getSSHHosts,
|
||||
type ServerMetrics,
|
||||
} from "@/main-axios.ts";
|
||||
import { SnippetVariablesDialog } from "@/components/SnippetVariablesDialog";
|
||||
import { useAreaPreferences } from "@/contexts/UiPreferencesContext";
|
||||
import { useConfirmation } from "@/hooks/use-confirmation.ts";
|
||||
import { hasSnippetInputs } from "@/lib/snippet-variables.ts";
|
||||
import type { Snippet } from "@/types/ui-types.ts";
|
||||
import { TOTPDialog } from "@/ssh/dialogs/TOTPDialog.tsx";
|
||||
import { useTabsSafe } from "@/shell/TabContext.tsx";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
type StatsConfig,
|
||||
DEFAULT_STATS_CONFIG,
|
||||
} from "@/types/stats-widgets.ts";
|
||||
import {
|
||||
defaultLayoutFromWidgets,
|
||||
type HostMetricsLayout,
|
||||
} from "@/types/host-metrics.ts";
|
||||
import { RefreshCw, Server, LayoutDashboard } from "lucide-react";
|
||||
import {
|
||||
ConnectionLogProvider,
|
||||
useConnectionLog,
|
||||
} from "@/ssh/connection-log/ConnectionLogContext.tsx";
|
||||
import { ConnectionScreen } from "@/components/connection/ConnectionScreen.tsx";
|
||||
import { useConnectionRetry } from "@/lib/useConnectionRetry.ts";
|
||||
import { runAdaptivePolling } from "@/lib/adaptive-polling.ts";
|
||||
import type { LogEntry } from "@/types/connection-log.ts";
|
||||
import {
|
||||
CardGridCanvas,
|
||||
ColumnCountStepper,
|
||||
} from "@/components/card-grid/CardGridCanvas.tsx";
|
||||
import type { GridCardCatalogEntry } from "@/components/card-grid/types.ts";
|
||||
import { useHostMetricsPreferences } from "./hooks/useHostMetricsPreferences.ts";
|
||||
import {
|
||||
CARD_DEFINITIONS,
|
||||
IMPLEMENTED_CARD_IDS,
|
||||
getCardDefinition,
|
||||
defaultColSpanFor,
|
||||
defaultHeightFor,
|
||||
type MetricCardHistories,
|
||||
} from "./cards";
|
||||
import { appendGpuHistories } from "./cards/gpu-history";
|
||||
import { metricsChangeKey } from "./metrics-change-key";
|
||||
|
||||
const HISTORY_LEN = 30;
|
||||
|
||||
interface QuickAction {
|
||||
name: string;
|
||||
snippetId: number;
|
||||
}
|
||||
|
||||
type ConnectionLogPayload = Omit<LogEntry, "id" | "timestamp">;
|
||||
type ConnectionLogError = Error & {
|
||||
connectionLogs?: ConnectionLogPayload[];
|
||||
};
|
||||
|
||||
interface HostConfig {
|
||||
id: number;
|
||||
name: string;
|
||||
ip: string;
|
||||
username: string;
|
||||
quickActions?: QuickAction[];
|
||||
statsConfig?: string | StatsConfig;
|
||||
authType?: string;
|
||||
port?: number;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
interface HostMetricsProps {
|
||||
hostConfig?: HostConfig;
|
||||
title?: string;
|
||||
isVisible?: boolean;
|
||||
isTopbarOpen?: boolean;
|
||||
embedded?: boolean;
|
||||
}
|
||||
|
||||
function parseStatsConfig(raw?: string | StatsConfig): StatsConfig {
|
||||
if (!raw) return DEFAULT_STATS_CONFIG;
|
||||
try {
|
||||
const parsed = typeof raw === "string" ? JSON.parse(raw) : raw;
|
||||
return { ...DEFAULT_STATS_CONFIG, ...parsed };
|
||||
} catch {
|
||||
return DEFAULT_STATS_CONFIG;
|
||||
}
|
||||
}
|
||||
|
||||
function HostMetricsInner({
|
||||
hostConfig,
|
||||
title,
|
||||
isVisible = true,
|
||||
isTopbarOpen = true,
|
||||
embedded = false,
|
||||
}: HostMetricsProps): React.ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const { addLog, clearLogs } = useConnectionLog();
|
||||
const { currentTab, removeTab } = useTabsSafe();
|
||||
|
||||
const [serverStatus, setServerStatus] = React.useState<"online" | "offline">(
|
||||
"offline",
|
||||
);
|
||||
const [metrics, setMetrics] = React.useState<ServerMetrics | null>(null);
|
||||
const [histories, setHistories] = React.useState<MetricCardHistories>({
|
||||
cpu: [],
|
||||
memory: [],
|
||||
disk: [],
|
||||
gpu: {},
|
||||
});
|
||||
const [currentHostConfig, setCurrentHostConfig] = React.useState(hostConfig);
|
||||
const [isRefreshing, setIsRefreshing] = React.useState(false);
|
||||
const [executingActions, setExecutingActions] = React.useState<Set<number>>(
|
||||
new Set(),
|
||||
);
|
||||
const [totpRequired, setTotpRequired] = React.useState(false);
|
||||
const [totpSessionId, setTotpSessionId] = React.useState<string | null>(null);
|
||||
const [totpPrompt, setTotpPrompt] = React.useState<string>("");
|
||||
const [isPageVisible, setIsPageVisible] = React.useState(!document.hidden);
|
||||
const [totpVerified, setTotpVerified] = React.useState(false);
|
||||
const [viewerSessionId, setViewerSessionId] = React.useState<string | null>(
|
||||
null,
|
||||
);
|
||||
const [editMode, setEditMode] = React.useState(false);
|
||||
const [runningAction, setRunningAction] = React.useState<{
|
||||
action: QuickAction;
|
||||
snippet: Snippet;
|
||||
} | null>(null);
|
||||
const { confirmWithToast } = useConfirmation();
|
||||
|
||||
const activityLoggedRef = React.useRef(false);
|
||||
const activityLoggingRef = React.useRef(false);
|
||||
const snippetsCacheRef = React.useRef<Snippet[] | null>(null);
|
||||
|
||||
const statsConfig = React.useMemo(
|
||||
() => parseStatsConfig(currentHostConfig?.statsConfig),
|
||||
[currentHostConfig?.statsConfig],
|
||||
);
|
||||
const metricsEnabled = statsConfig.metricsEnabled !== false;
|
||||
const statusCheckEnabled = statsConfig.statusCheckEnabled !== false;
|
||||
|
||||
const hostId = currentHostConfig?.id ?? null;
|
||||
const { layout, setLayout } = useHostMetricsPreferences(hostId);
|
||||
|
||||
const metricsPrefs = useAreaPreferences("hostMetrics");
|
||||
|
||||
const effectiveLayout: HostMetricsLayout = React.useMemo(() => {
|
||||
// A saved layout is user-authored, so the preset never rewrites it -- it
|
||||
// only decides the shape of the first layout a host gets.
|
||||
if (layout) return layout;
|
||||
return defaultLayoutFromWidgets(
|
||||
statsConfig.enabledWidgets ?? [],
|
||||
metricsPrefs.columns,
|
||||
);
|
||||
}, [layout, statsConfig.enabledWidgets, metricsPrefs.columns]);
|
||||
|
||||
// Only render/keep cards that are implemented (metric cards in Phase A).
|
||||
const visibleSlots = React.useMemo(
|
||||
() => effectiveLayout.slots.filter((s) => getCardDefinition(s.id)),
|
||||
[effectiveLayout.slots],
|
||||
);
|
||||
|
||||
const cardCatalog: GridCardCatalogEntry[] = React.useMemo(
|
||||
() =>
|
||||
IMPLEMENTED_CARD_IDS.map((id) => ({
|
||||
id,
|
||||
label: t(CARD_DEFINITIONS[id].labelKey),
|
||||
defaultColSpan: defaultColSpanFor(id),
|
||||
defaultHeight: defaultHeightFor(id),
|
||||
})),
|
||||
[t],
|
||||
);
|
||||
|
||||
const cardLabel = React.useCallback(
|
||||
(id: string) => {
|
||||
const def = getCardDefinition(id);
|
||||
return def ? t(def.labelKey) : id;
|
||||
},
|
||||
[t],
|
||||
);
|
||||
|
||||
const renderCard = React.useCallback(
|
||||
(id: string) => {
|
||||
const def = getCardDefinition(id);
|
||||
if (!def) return null;
|
||||
return def.render({ metrics, histories, hostId });
|
||||
},
|
||||
[metrics, histories, hostId],
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
const onVis = () => setIsPageVisible(!document.hidden);
|
||||
document.addEventListener("visibilitychange", onVis);
|
||||
return () => document.removeEventListener("visibilitychange", onVis);
|
||||
}, []);
|
||||
|
||||
const isActuallyVisible = isVisible && isPageVisible;
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!viewerSessionId || !isActuallyVisible) return;
|
||||
const interval = setInterval(() => {
|
||||
sendMetricsHeartbeat(viewerSessionId).catch(() => {});
|
||||
}, 30000);
|
||||
return () => clearInterval(interval);
|
||||
}, [viewerSessionId, isActuallyVisible]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (hostConfig?.id !== currentHostConfig?.id) {
|
||||
setServerStatus("offline");
|
||||
setMetrics(null);
|
||||
setHistories({ cpu: [], memory: [], disk: [], gpu: {} });
|
||||
}
|
||||
setCurrentHostConfig(hostConfig);
|
||||
}, [hostConfig?.id]);
|
||||
|
||||
const logServerActivity = async () => {
|
||||
if (
|
||||
!currentHostConfig?.id ||
|
||||
activityLoggedRef.current ||
|
||||
activityLoggingRef.current
|
||||
) {
|
||||
return;
|
||||
}
|
||||
activityLoggingRef.current = true;
|
||||
activityLoggedRef.current = true;
|
||||
try {
|
||||
const hostName =
|
||||
currentHostConfig.name ||
|
||||
`${currentHostConfig.username}@${currentHostConfig.ip}`;
|
||||
await logActivity("server_stats", currentHostConfig.id, hostName);
|
||||
} catch {
|
||||
activityLoggedRef.current = false;
|
||||
} finally {
|
||||
activityLoggingRef.current = false;
|
||||
}
|
||||
};
|
||||
|
||||
const pushHistory = React.useCallback((data: ServerMetrics) => {
|
||||
setHistories((prev) => {
|
||||
const add = (arr: number[], v: number | null | undefined) =>
|
||||
[...arr, v ?? 0].slice(-HISTORY_LEN);
|
||||
return {
|
||||
cpu: add(prev.cpu, data.cpu?.percent),
|
||||
memory: add(prev.memory, data.memory?.percent),
|
||||
disk: add(prev.disk, data.disk?.percent),
|
||||
gpu: appendGpuHistories(prev.gpu, data.gpu?.gpus, HISTORY_LEN),
|
||||
};
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleTOTPSubmit = async (totpCode: string) => {
|
||||
if (!totpSessionId || !currentHostConfig) return;
|
||||
try {
|
||||
const result = await submitMetricsTOTP(totpSessionId, totpCode);
|
||||
if (result.success) {
|
||||
setTotpRequired(false);
|
||||
setTotpSessionId(null);
|
||||
setTotpVerified(true);
|
||||
if (result.viewerSessionId) setViewerSessionId(result.viewerSessionId);
|
||||
} else {
|
||||
toast.error(t("hostMetrics.totpFailed"));
|
||||
}
|
||||
} catch {
|
||||
toast.error(t("hostMetrics.totpFailed"));
|
||||
}
|
||||
};
|
||||
|
||||
const handleTOTPCancel = async () => {
|
||||
setTotpRequired(false);
|
||||
if (currentHostConfig?.id) {
|
||||
await stopMetricsPolling(currentHostConfig.id).catch(() => {});
|
||||
}
|
||||
if (currentTab !== null) removeTab(currentTab);
|
||||
};
|
||||
|
||||
React.useEffect(() => {
|
||||
const fetchLatest = async () => {
|
||||
if (!hostConfig?.id) return;
|
||||
try {
|
||||
const hosts = await getSSHHosts();
|
||||
const updated = hosts.find((h) => h.id === hostConfig.id);
|
||||
if (updated) setCurrentHostConfig(updated as unknown as HostConfig);
|
||||
} catch {
|
||||
toast.error(t("hostMetrics.failedToFetchHostConfig"));
|
||||
}
|
||||
};
|
||||
fetchLatest();
|
||||
const onChanged = () => fetchLatest();
|
||||
window.addEventListener("ssh-hosts:changed", onChanged);
|
||||
return () => window.removeEventListener("ssh-hosts:changed", onChanged);
|
||||
}, [hostConfig?.id]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!statusCheckEnabled || !currentHostConfig?.id || !isActuallyVisible) {
|
||||
if (!statusCheckEnabled) setServerStatus("offline");
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
let lastStatus = serverStatus;
|
||||
const fetchStatus = async () => {
|
||||
try {
|
||||
const res = await getServerStatusById(currentHostConfig.id);
|
||||
const nextStatus = res?.status === "online" ? "online" : "offline";
|
||||
if (!cancelled) {
|
||||
setServerStatus(nextStatus);
|
||||
}
|
||||
const changed = nextStatus !== lastStatus;
|
||||
lastStatus = nextStatus;
|
||||
return changed;
|
||||
} catch {
|
||||
if (!cancelled) setServerStatus("offline");
|
||||
throw new Error("Host status check failed");
|
||||
}
|
||||
};
|
||||
const minIntervalMs = statsConfig.statusCheckInterval * 1000;
|
||||
const stop = runAdaptivePolling(fetchStatus, {
|
||||
minIntervalMs,
|
||||
maxIntervalMs: Math.min(120_000, minIntervalMs * 6),
|
||||
stablePollsPerStep: 3,
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
stop();
|
||||
};
|
||||
}, [
|
||||
currentHostConfig?.id,
|
||||
statusCheckEnabled,
|
||||
statsConfig.statusCheckInterval,
|
||||
isActuallyVisible,
|
||||
]);
|
||||
|
||||
const stopMetricsPollingRef = React.useRef<(() => void) | null>(null);
|
||||
|
||||
const fetchMetrics = React.useCallback(async (): Promise<void> => {
|
||||
if (!currentHostConfig?.id) return;
|
||||
if (currentHostConfig.authType === "none") {
|
||||
toast.error(t("hostMetrics.noneAuthNotSupported"));
|
||||
if (currentTab !== null) removeTab(currentTab);
|
||||
throw new Error(t("hostMetrics.noneAuthNotSupported"));
|
||||
}
|
||||
|
||||
if (!totpVerified) {
|
||||
addLog({
|
||||
type: "info",
|
||||
stage: "stats_connecting",
|
||||
message: `Connecting to ${currentHostConfig.username}@${currentHostConfig.ip}:${currentHostConfig.port}`,
|
||||
});
|
||||
const result = await startMetricsPolling(currentHostConfig.id);
|
||||
result?.connectionLogs?.forEach((log) =>
|
||||
addLog(log as ConnectionLogPayload),
|
||||
);
|
||||
if (result.requires_totp) {
|
||||
setTotpRequired(true);
|
||||
setTotpSessionId(result.sessionId || null);
|
||||
setTotpPrompt(result.prompt || "Verification code");
|
||||
// The TOTP dialog gates further progress; retry loop pauses via `enabled`.
|
||||
return;
|
||||
}
|
||||
if (result.viewerSessionId) setViewerSessionId(result.viewerSessionId);
|
||||
}
|
||||
|
||||
// The connect above only opens the SSH session; the first real sample is
|
||||
// collected asynchronously on the backend (status check, then metrics
|
||||
// exec), so it isn't ready the instant the connection succeeds. Give it
|
||||
// a few short retries before treating the initial fetch as a failure.
|
||||
let data = await getServerMetricsById(currentHostConfig.id);
|
||||
for (let i = 0; !data && i < 5; i++) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 1500));
|
||||
data = await getServerMetricsById(currentHostConfig.id);
|
||||
}
|
||||
if (!data) {
|
||||
throw new Error(t("hostMetrics.connectionFailed"));
|
||||
}
|
||||
|
||||
setMetrics(data);
|
||||
pushHistory(data);
|
||||
setServerStatus("online");
|
||||
logServerActivity();
|
||||
addLog({
|
||||
type: "success",
|
||||
stage: "connected",
|
||||
message: t("terminal.connected"),
|
||||
});
|
||||
|
||||
let signature = metricsChangeKey(data);
|
||||
const minIntervalMs = statsConfig.metricsInterval * 1000;
|
||||
stopMetricsPollingRef.current?.();
|
||||
stopMetricsPollingRef.current = runAdaptivePolling(
|
||||
async () => {
|
||||
const next = await getServerMetricsById(currentHostConfig.id);
|
||||
if (!next) throw new Error(t("hostMetrics.connectionFailed"));
|
||||
const nextSignature = metricsChangeKey(next);
|
||||
const changed = nextSignature !== signature;
|
||||
signature = nextSignature;
|
||||
setMetrics(next);
|
||||
pushHistory(next);
|
||||
return changed;
|
||||
},
|
||||
{
|
||||
minIntervalMs,
|
||||
maxIntervalMs: Math.min(120_000, minIntervalMs * 6),
|
||||
stablePollsPerStep: 3,
|
||||
},
|
||||
{ runImmediately: false },
|
||||
);
|
||||
}, [
|
||||
currentHostConfig,
|
||||
totpVerified,
|
||||
statsConfig.metricsInterval,
|
||||
addLog,
|
||||
t,
|
||||
currentTab,
|
||||
removeTab,
|
||||
pushHistory,
|
||||
]);
|
||||
|
||||
const metricsRetry = useConnectionRetry({
|
||||
connect: async () => {
|
||||
try {
|
||||
await fetchMetrics();
|
||||
if (!totpRequired) metricsRetry.markConnected();
|
||||
} catch (error: unknown) {
|
||||
const logError = error as ConnectionLogError;
|
||||
if (logError.connectionLogs) {
|
||||
logError.connectionLogs.forEach((log) => addLog(log));
|
||||
} else {
|
||||
addLog({
|
||||
type: "error",
|
||||
stage: "connection",
|
||||
message:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: t("hostMetrics.connectionFailed"),
|
||||
});
|
||||
}
|
||||
metricsRetry.markFailed();
|
||||
}
|
||||
},
|
||||
enabled:
|
||||
isPageVisible &&
|
||||
metricsEnabled &&
|
||||
!totpRequired &&
|
||||
!!currentHostConfig?.id,
|
||||
autoStart: false,
|
||||
});
|
||||
|
||||
const metricsRetryRef = React.useRef(metricsRetry);
|
||||
metricsRetryRef.current = metricsRetry;
|
||||
|
||||
// Connects once per host and stays connected while this tab exists, even
|
||||
// when the user switches to another tab and back. Only the browser tab
|
||||
// going into the background (isPageVisible) pauses/resumes it -- switching
|
||||
// between Termix tabs must not tear down and reconnect the session.
|
||||
React.useEffect(() => {
|
||||
if (!metricsEnabled || !currentHostConfig?.id) return;
|
||||
|
||||
let cancelled = false;
|
||||
|
||||
const stopMetrics = async () => {
|
||||
stopMetricsPollingRef.current?.();
|
||||
stopMetricsPollingRef.current = null;
|
||||
if (currentHostConfig?.id) {
|
||||
await stopMetricsPolling(
|
||||
currentHostConfig.id,
|
||||
viewerSessionId || undefined,
|
||||
).catch(() => {});
|
||||
}
|
||||
};
|
||||
|
||||
const debounce = setTimeout(() => {
|
||||
if (cancelled) return;
|
||||
if (isPageVisible) {
|
||||
clearLogs();
|
||||
metricsRetryRef.current.reset();
|
||||
metricsRetryRef.current.retryNow();
|
||||
} else {
|
||||
stopMetrics();
|
||||
}
|
||||
}, 500);
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
clearTimeout(debounce);
|
||||
stopMetricsPollingRef.current?.();
|
||||
stopMetricsPollingRef.current = null;
|
||||
if (currentHostConfig?.id) {
|
||||
stopMetricsPolling(currentHostConfig.id).catch(() => {});
|
||||
}
|
||||
};
|
||||
}, [currentHostConfig?.id, isPageVisible, metricsEnabled]);
|
||||
|
||||
// After a successful TOTP submit, resume the connect flow immediately.
|
||||
React.useEffect(() => {
|
||||
if (totpVerified && !totpRequired) {
|
||||
metricsRetryRef.current.reset();
|
||||
metricsRetryRef.current.retryNow();
|
||||
}
|
||||
}, [totpVerified, totpRequired]);
|
||||
|
||||
const wrapperStyle: React.CSSProperties = embedded
|
||||
? { opacity: isVisible ? 1 : 0, height: "100%", width: "100%" }
|
||||
: {
|
||||
opacity: isVisible ? 1 : 0,
|
||||
margin: isTopbarOpen ? "74px 17px 8px 8px" : "16px 17px 8px 8px",
|
||||
height: isTopbarOpen ? "calc(100vh - 82px)" : "calc(100vh - 24px)",
|
||||
};
|
||||
|
||||
const handleRefresh = async () => {
|
||||
if (!currentHostConfig?.id) return;
|
||||
if (metricsRetry.status !== "connected") {
|
||||
metricsRetry.retryNow();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
setIsRefreshing(true);
|
||||
const res = await getServerStatusById(currentHostConfig.id);
|
||||
setServerStatus(res?.status === "online" ? "online" : "offline");
|
||||
const data = await getServerMetricsById(currentHostConfig.id);
|
||||
if (data) {
|
||||
setMetrics(data);
|
||||
pushHistory(data);
|
||||
}
|
||||
} catch {
|
||||
setServerStatus("offline");
|
||||
} finally {
|
||||
setIsRefreshing(false);
|
||||
}
|
||||
};
|
||||
|
||||
async function executeQuickAction(
|
||||
action: QuickAction,
|
||||
inputValues: Record<string, string>,
|
||||
) {
|
||||
if (!currentHostConfig) return;
|
||||
setExecutingActions((prev) => new Set(prev).add(action.snippetId));
|
||||
toast.loading(
|
||||
t("hostMetrics.executingQuickAction", { name: action.name }),
|
||||
{
|
||||
id: `quick-action-${action.snippetId}`,
|
||||
},
|
||||
);
|
||||
try {
|
||||
const result = await executeSnippet(
|
||||
action.snippetId,
|
||||
currentHostConfig.id,
|
||||
Object.keys(inputValues).length > 0 ? inputValues : undefined,
|
||||
);
|
||||
if (result.success) {
|
||||
toast.success(
|
||||
t("hostMetrics.quickActionSuccess", { name: action.name }),
|
||||
{
|
||||
id: `quick-action-${action.snippetId}`,
|
||||
description: result.output?.substring(0, 200),
|
||||
duration: 5000,
|
||||
},
|
||||
);
|
||||
} else {
|
||||
toast.error(t("hostMetrics.quickActionFailed", { name: action.name }), {
|
||||
id: `quick-action-${action.snippetId}`,
|
||||
description: result.error || result.output,
|
||||
duration: 5000,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
toast.error(t("hostMetrics.quickActionError", { name: action.name }), {
|
||||
id: `quick-action-${action.snippetId}`,
|
||||
description: getErrorMessage(error),
|
||||
duration: 5000,
|
||||
});
|
||||
} finally {
|
||||
setExecutingActions((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.delete(action.snippetId);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function runQuickActionWithConfirm(
|
||||
action: QuickAction,
|
||||
inputValues: Record<string, string>,
|
||||
) {
|
||||
const shouldConfirm =
|
||||
localStorage.getItem("confirmSnippetExecution") === "true";
|
||||
const run = () => void executeQuickAction(action, inputValues);
|
||||
if (!shouldConfirm) {
|
||||
run();
|
||||
return;
|
||||
}
|
||||
confirmWithToast(
|
||||
t("newUi.sidebar.snippets.confirmRunMessage", { name: action.name }),
|
||||
run,
|
||||
t("newUi.sidebar.snippets.confirmRunButton"),
|
||||
t("newUi.sidebar.snippets.cancel"),
|
||||
{ confirmOnEnter: true, duration: 6000 },
|
||||
);
|
||||
}
|
||||
|
||||
async function runQuickAction(action: QuickAction) {
|
||||
if (!currentHostConfig) return;
|
||||
try {
|
||||
if (!snippetsCacheRef.current) {
|
||||
snippetsCacheRef.current =
|
||||
(await getSnippets()) as unknown as Snippet[];
|
||||
}
|
||||
const snippet = snippetsCacheRef.current?.find(
|
||||
(s) => s.id === action.snippetId,
|
||||
);
|
||||
if (snippet && hasSnippetInputs(snippet.content)) {
|
||||
setRunningAction({ action, snippet });
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// fall through and run with no inputs if the snippet lookup fails
|
||||
}
|
||||
runQuickActionWithConfirm(action, {});
|
||||
}
|
||||
|
||||
const showCards =
|
||||
metricsEnabled && metricsRetry.status === "connected" && metrics;
|
||||
const showOffline =
|
||||
metricsEnabled &&
|
||||
metricsRetry.status !== "connecting" &&
|
||||
!metrics &&
|
||||
serverStatus === "offline";
|
||||
|
||||
return (
|
||||
<div
|
||||
style={wrapperStyle}
|
||||
className="relative flex flex-col overflow-hidden"
|
||||
>
|
||||
<div className="flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||
<div className="flex flex-1 flex-col overflow-x-hidden overflow-y-auto">
|
||||
{!totpRequired &&
|
||||
(metricsRetry.status === "connected" || showOffline) && (
|
||||
<div className="mx-3 mt-3 flex shrink-0 items-center justify-between border border-border bg-card px-3 py-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex size-10 shrink-0 items-center justify-center border border-border bg-muted">
|
||||
<Server className="size-5 text-accent-brand" />
|
||||
</div>
|
||||
<h1 className="text-lg font-bold md:text-2xl">{title}</h1>
|
||||
</div>
|
||||
<div className="flex items-center gap-0">
|
||||
{currentHostConfig?.quickActions &&
|
||||
currentHostConfig.quickActions.length > 0 && (
|
||||
<>
|
||||
<div className="mr-3 flex flex-wrap gap-2">
|
||||
{currentHostConfig.quickActions.map(
|
||||
(action, index) => {
|
||||
const isExecuting = executingActions.has(
|
||||
action.snippetId,
|
||||
);
|
||||
return (
|
||||
<Button
|
||||
key={index}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-8 text-xs font-semibold"
|
||||
disabled={isExecuting}
|
||||
onClick={() => void runQuickAction(action)}
|
||||
>
|
||||
{isExecuting ? (
|
||||
<>
|
||||
<RefreshCw className="mr-1 size-3 animate-spin" />
|
||||
{action.name}
|
||||
</>
|
||||
) : (
|
||||
action.name
|
||||
)}
|
||||
</Button>
|
||||
);
|
||||
},
|
||||
)}
|
||||
</div>
|
||||
<Separator
|
||||
orientation="vertical"
|
||||
className="mx-3 h-8"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{editMode && (
|
||||
<>
|
||||
<ColumnCountStepper
|
||||
columns={effectiveLayout.columns}
|
||||
onChange={(columns) =>
|
||||
setLayout({ ...effectiveLayout, columns })
|
||||
}
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="ml-2 text-xs text-muted-foreground"
|
||||
onClick={() =>
|
||||
setLayout(
|
||||
defaultLayoutFromWidgets(
|
||||
statsConfig.enabledWidgets ?? [],
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
{t("hostMetrics.reset")}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<Button
|
||||
variant={editMode ? "default" : "ghost"}
|
||||
size="icon"
|
||||
className="ml-1"
|
||||
title={t("hostMetrics.customize")}
|
||||
onClick={() => setEditMode((v) => !v)}
|
||||
>
|
||||
<LayoutDashboard className="size-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="default"
|
||||
onClick={handleRefresh}
|
||||
disabled={isRefreshing}
|
||||
className="ml-1 gap-2 font-semibold"
|
||||
>
|
||||
<RefreshCw
|
||||
className={`size-3.5 ${isRefreshing ? "animate-spin" : ""}`}
|
||||
/>
|
||||
{t("hostMetrics.refresh")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{editMode && (
|
||||
<div className="mx-3 mt-3 flex shrink-0 items-center gap-2 border border-dashed border-accent-brand/40 bg-accent-brand/5 px-4 py-2">
|
||||
<LayoutDashboard className="size-3.5 shrink-0 text-accent-brand" />
|
||||
<span className="text-xs font-semibold text-accent-brand">
|
||||
{t("hostMetrics.editModeInstructions")}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showCards && (
|
||||
<div className="px-3 pt-3 pb-3">
|
||||
<CardGridCanvas
|
||||
slots={visibleSlots}
|
||||
columns={effectiveLayout.columns}
|
||||
editMode={editMode}
|
||||
renderCard={renderCard}
|
||||
cardCatalog={cardCatalog}
|
||||
cardLabel={cardLabel}
|
||||
onChange={(slots, columns) =>
|
||||
setLayout({
|
||||
slots: slots as HostMetricsLayout["slots"],
|
||||
columns,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{metricsEnabled && !totpRequired && (
|
||||
<ConnectionScreen
|
||||
status={showOffline ? "connected" : metricsRetry.status}
|
||||
message={t("hostMetrics.connecting")}
|
||||
attempt={metricsRetry.attempt}
|
||||
maxAttempts={metricsRetry.maxAttempts}
|
||||
nextRetryInMs={metricsRetry.nextRetryInMs}
|
||||
onManualRetry={metricsRetry.retryNow}
|
||||
logPosition={
|
||||
metricsRetry.status === "error" ||
|
||||
metricsRetry.status === "disconnected"
|
||||
? "top"
|
||||
: "bottom"
|
||||
}
|
||||
emptyState={
|
||||
showOffline ? (
|
||||
<div className="text-center opacity-40">
|
||||
<Server className="mx-auto mb-4 size-16" />
|
||||
<p className="text-xl font-bold uppercase tracking-widest">
|
||||
{t("hostMetrics.serverOffline")}
|
||||
</p>
|
||||
<p className="text-sm font-semibold">
|
||||
{t("hostMetrics.cannotFetchMetrics")}
|
||||
</p>
|
||||
</div>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<TOTPDialog
|
||||
isOpen={totpRequired}
|
||||
prompt={totpPrompt}
|
||||
onSubmit={handleTOTPSubmit}
|
||||
onCancel={handleTOTPCancel}
|
||||
backgroundColor="var(--bg-canvas)"
|
||||
/>
|
||||
|
||||
{runningAction && (
|
||||
<SnippetVariablesDialog
|
||||
snippet={runningAction.snippet}
|
||||
host={
|
||||
currentHostConfig
|
||||
? {
|
||||
ip: currentHostConfig.ip,
|
||||
username: currentHostConfig.username,
|
||||
port: currentHostConfig.port,
|
||||
name: currentHostConfig.name,
|
||||
}
|
||||
: null
|
||||
}
|
||||
onCancel={() => setRunningAction(null)}
|
||||
onConfirm={(_resolvedContent, inputValues) => {
|
||||
const action = runningAction.action;
|
||||
setRunningAction(null);
|
||||
runQuickActionWithConfirm(action, inputValues);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function HostMetricsTab(props: HostMetricsProps): React.ReactElement {
|
||||
return (
|
||||
<ConnectionLogProvider>
|
||||
<HostMetricsInner {...props} />
|
||||
</ConnectionLogProvider>
|
||||
);
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
export type HistoryTab = "live" | "1h" | "6h" | "24h" | "7d";
|
||||
|
||||
const TABS: HistoryTab[] = ["live", "1h", "6h", "24h", "7d"];
|
||||
|
||||
export function CardTimeTabs({
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
value: HistoryTab;
|
||||
onChange: (tab: HistoryTab) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="flex items-center gap-0.5">
|
||||
{TABS.map((tab) => (
|
||||
<button
|
||||
key={tab}
|
||||
onClick={() => onChange(tab)}
|
||||
className={cn(
|
||||
"px-2 py-0.5 text-[10px] font-semibold uppercase tracking-widest transition-colors border",
|
||||
value === tab
|
||||
? "border-accent-brand bg-accent-brand/10 text-accent-brand"
|
||||
: "border-transparent text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
{tab === "live" ? t("hostMetrics.tabLive") : tab}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Cpu } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ServerMetrics } from "@/main-axios";
|
||||
import { RadialGauge, Sparkline, MiniStat } from "@/components/charts";
|
||||
import { MetricCard } from "./MetricCard";
|
||||
import { LineChart, type LineChartSeries } from "@/components/charts/LineChart";
|
||||
import {
|
||||
getMetricsHistory,
|
||||
type MetricsHistoryRow,
|
||||
} from "@/api/host-metrics-api";
|
||||
import { CardTimeTabs, type HistoryTab } from "./CardTimeTabs";
|
||||
|
||||
function computeChartData(rows: MetricsHistoryRow[]) {
|
||||
return {
|
||||
data: rows.map((r) => r.cpu_percent),
|
||||
timestamps: rows.map((r) => r.ts),
|
||||
};
|
||||
}
|
||||
|
||||
export function CpuCard({
|
||||
metrics,
|
||||
history,
|
||||
hostId,
|
||||
}: {
|
||||
metrics: ServerMetrics | null;
|
||||
history: number[];
|
||||
hostId: number | null;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [activeTab, setActiveTab] = useState<HistoryTab>("live");
|
||||
const [rows, setRows] = useState<MetricsHistoryRow[] | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (activeTab === "live" || hostId == null) return;
|
||||
let cancelled = false;
|
||||
setLoading(true);
|
||||
setRows(null);
|
||||
getMetricsHistory(hostId, { range: activeTab })
|
||||
.then((res) => {
|
||||
if (!cancelled) {
|
||||
setRows(res.rows);
|
||||
setLoading(false);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setLoading(false);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [activeTab, hostId]);
|
||||
|
||||
const percent = metrics?.cpu?.percent ?? null;
|
||||
const cores = metrics?.cpu?.cores ?? null;
|
||||
const load = metrics?.cpu?.load ?? null;
|
||||
|
||||
const series: LineChartSeries[] = [
|
||||
{
|
||||
key: "cpu",
|
||||
label: t("hostMetrics.cpuUsage"),
|
||||
color: "var(--accent-brand)",
|
||||
data: rows?.map((r) => r.cpu_percent) ?? [],
|
||||
},
|
||||
];
|
||||
const timestamps = rows?.map((r) => r.ts) ?? [];
|
||||
|
||||
return (
|
||||
<MetricCard
|
||||
title={t("hostMetrics.cpuUsage")}
|
||||
icon={<Cpu className="size-3.5" />}
|
||||
action={
|
||||
hostId != null ? (
|
||||
<CardTimeTabs value={activeTab} onChange={setActiveTab} />
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
<div className="flex flex-col gap-3">
|
||||
{activeTab === "live" && (
|
||||
<div className="flex items-center gap-4">
|
||||
<RadialGauge
|
||||
value={percent}
|
||||
caption={
|
||||
cores !== null
|
||||
? t("hostMetrics.cpuCores", { count: cores })
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-2">
|
||||
{load && (
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<MiniStat caption="1m" value={load[0].toFixed(2)} />
|
||||
<MiniStat caption="5m" value={load[1].toFixed(2)} />
|
||||
<MiniStat caption="15m" value={load[2].toFixed(2)} />
|
||||
</div>
|
||||
)}
|
||||
<Sparkline
|
||||
data={[...history, percent ?? 0]}
|
||||
domain={[0, 100]}
|
||||
height={48}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{activeTab !== "live" && (
|
||||
<>
|
||||
{loading && (
|
||||
<div className="flex h-36 items-center justify-center text-xs text-muted-foreground">
|
||||
{t("common.loading")}
|
||||
</div>
|
||||
)}
|
||||
{!loading && rows !== null && rows.length === 0 && (
|
||||
<div className="flex h-36 items-center justify-center text-xs text-muted-foreground">
|
||||
{t("metricsHistory.noData")}
|
||||
</div>
|
||||
)}
|
||||
{!loading && rows !== null && rows.length > 0 && (
|
||||
<LineChart
|
||||
series={series}
|
||||
timestamps={timestamps}
|
||||
domain={[0, 100]}
|
||||
yFormatter={(v) => `${v.toFixed(0)}%`}
|
||||
height={160}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</MetricCard>
|
||||
);
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { HardDrive } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ServerMetrics } from "@/main-axios";
|
||||
import { FilesystemPicker } from "./FilesystemPicker";
|
||||
import { RadialGauge, Sparkline, MiniStat } from "@/components/charts";
|
||||
import { MetricCard } from "./MetricCard";
|
||||
import { LineChart, type LineChartSeries } from "@/components/charts/LineChart";
|
||||
import {
|
||||
getMetricsHistory,
|
||||
type MetricsHistoryRow,
|
||||
} from "@/api/host-metrics-api";
|
||||
import { CardTimeTabs, type HistoryTab } from "./CardTimeTabs";
|
||||
|
||||
export function DiskCard({
|
||||
metrics,
|
||||
history,
|
||||
hostId,
|
||||
}: {
|
||||
metrics: ServerMetrics | null;
|
||||
history: number[];
|
||||
hostId: number | null;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [activeTab, setActiveTab] = useState<HistoryTab>("live");
|
||||
const [rows, setRows] = useState<MetricsHistoryRow[] | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (activeTab === "live" || hostId == null) return;
|
||||
let cancelled = false;
|
||||
setLoading(true);
|
||||
setRows(null);
|
||||
getMetricsHistory(hostId, { range: activeTab })
|
||||
.then((res) => {
|
||||
if (!cancelled) {
|
||||
setRows(res.rows);
|
||||
setLoading(false);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setLoading(false);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [activeTab, hostId]);
|
||||
|
||||
const filesystems = useMemo(
|
||||
() => metrics?.disk?.filesystems ?? [],
|
||||
[metrics?.disk?.filesystems],
|
||||
);
|
||||
const defaultMount = metrics?.disk?.mount ?? null;
|
||||
const [selectedMount, setSelectedMount] = useState<string | null>(null);
|
||||
|
||||
// Drop a stale selection if the mount disappears between polls, so the card
|
||||
// falls back to the primary filesystem instead of rendering nothing.
|
||||
useEffect(() => {
|
||||
if (
|
||||
selectedMount !== null &&
|
||||
filesystems.length > 0 &&
|
||||
!filesystems.some((fs) => fs.mount === selectedMount)
|
||||
) {
|
||||
setSelectedMount(null);
|
||||
}
|
||||
}, [filesystems, selectedMount]);
|
||||
|
||||
const activeMount = selectedMount ?? defaultMount;
|
||||
const activeFs = filesystems.find((fs) => fs.mount === activeMount) ?? null;
|
||||
const isCustomMount = selectedMount !== null && activeFs !== null;
|
||||
|
||||
const percent = isCustomMount
|
||||
? activeFs.percent
|
||||
: (metrics?.disk?.percent ?? null);
|
||||
const usedHuman = isCustomMount
|
||||
? activeFs.usedHuman
|
||||
: (metrics?.disk?.usedHuman ?? null);
|
||||
const totalHuman = isCustomMount
|
||||
? activeFs.totalHuman
|
||||
: (metrics?.disk?.totalHuman ?? null);
|
||||
const availableHuman = isCustomMount
|
||||
? activeFs.availableHuman
|
||||
: (metrics?.disk?.availableHuman ?? null);
|
||||
|
||||
const series: LineChartSeries[] = [
|
||||
{
|
||||
key: "disk",
|
||||
label: t("hostMetrics.diskUsage"),
|
||||
color: "var(--chart-4)",
|
||||
data: rows?.map((r) => r.disk_percent) ?? [],
|
||||
},
|
||||
];
|
||||
const timestamps = rows?.map((r) => r.ts) ?? [];
|
||||
|
||||
return (
|
||||
<MetricCard
|
||||
title={t("hostMetrics.diskUsage")}
|
||||
icon={<HardDrive className="size-3.5" />}
|
||||
action={
|
||||
<div className="flex items-center gap-1.5">
|
||||
{activeTab === "live" && (
|
||||
<FilesystemPicker
|
||||
filesystems={filesystems}
|
||||
value={activeMount}
|
||||
onChange={setSelectedMount}
|
||||
/>
|
||||
)}
|
||||
{hostId != null && (
|
||||
<CardTimeTabs value={activeTab} onChange={setActiveTab} />
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="flex flex-col gap-3">
|
||||
{activeTab === "live" && (
|
||||
<div className="flex items-center gap-4">
|
||||
<RadialGauge value={percent} />
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-2">
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<MiniStat
|
||||
caption={activeMount ?? t("hostMetrics.disk")}
|
||||
value={
|
||||
usedHuman && totalHuman
|
||||
? `${usedHuman}/${totalHuman}`
|
||||
: "N/A"
|
||||
}
|
||||
/>
|
||||
<MiniStat
|
||||
caption={t("hostMetrics.available")}
|
||||
value={availableHuman ?? "N/A"}
|
||||
/>
|
||||
</div>
|
||||
<Sparkline
|
||||
data={[...history, percent ?? 0]}
|
||||
domain={[0, 100]}
|
||||
height={48}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{activeTab !== "live" && (
|
||||
<>
|
||||
{loading && (
|
||||
<div className="flex h-36 items-center justify-center text-xs text-muted-foreground">
|
||||
{t("common.loading")}
|
||||
</div>
|
||||
)}
|
||||
{!loading && rows !== null && rows.length === 0 && (
|
||||
<div className="flex h-36 items-center justify-center text-xs text-muted-foreground">
|
||||
{t("metricsHistory.noData")}
|
||||
</div>
|
||||
)}
|
||||
{!loading && rows !== null && rows.length > 0 && (
|
||||
<LineChart
|
||||
series={series}
|
||||
timestamps={timestamps}
|
||||
domain={[0, 100]}
|
||||
yFormatter={(v) => `${v.toFixed(0)}%`}
|
||||
height={160}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</MetricCard>
|
||||
);
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
import { ChevronDown, Check } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { DiskFilesystem } from "@/main-axios";
|
||||
import { cn } from "@/lib/utils";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
} from "@/components/dropdown-menu";
|
||||
|
||||
export function FilesystemPicker({
|
||||
filesystems,
|
||||
value,
|
||||
onChange,
|
||||
align = "end",
|
||||
className,
|
||||
}: {
|
||||
filesystems: DiskFilesystem[];
|
||||
value: string | null;
|
||||
onChange: (mount: string) => void;
|
||||
align?: "start" | "end";
|
||||
className?: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (filesystems.length <= 1) return null;
|
||||
|
||||
const selected = filesystems.find((fs) => fs.mount === value);
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
className={cn(
|
||||
"flex max-w-[160px] items-center gap-1 border border-border px-2 py-0.5 text-[10px] font-semibold uppercase tracking-widest text-muted-foreground transition-colors hover:text-foreground",
|
||||
className,
|
||||
)}
|
||||
title={t("hostMetrics.selectFilesystem")}
|
||||
>
|
||||
<span className="truncate">
|
||||
{selected?.label || selected?.mount || value || "-"}
|
||||
</span>
|
||||
<ChevronDown className="size-3 shrink-0" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent
|
||||
align={align}
|
||||
className="w-auto min-w-[220px] max-w-[min(360px,calc(100vw-2rem))]"
|
||||
>
|
||||
{filesystems.map((fs) => (
|
||||
<DropdownMenuItem
|
||||
key={fs.mount}
|
||||
onSelect={() => onChange(fs.mount)}
|
||||
className="gap-3"
|
||||
>
|
||||
<Check
|
||||
className={cn(
|
||||
"size-3 shrink-0",
|
||||
fs.mount === value ? "opacity-100" : "opacity-0",
|
||||
)}
|
||||
/>
|
||||
<span className="min-w-0 flex-1 truncate font-medium">
|
||||
{fs.label || fs.mount}
|
||||
</span>
|
||||
{fs.label && (
|
||||
<span className="max-w-24 truncate font-mono text-[10px] text-muted-foreground">
|
||||
{fs.mount}
|
||||
</span>
|
||||
)}
|
||||
<span className="ml-auto shrink-0 whitespace-nowrap text-[10px] tabular-nums text-muted-foreground">
|
||||
{fs.usedHuman && fs.totalHuman
|
||||
? `${fs.usedHuman}/${fs.totalHuman}`
|
||||
: "N/A"}
|
||||
{fs.percent != null ? ` · ${fs.percent}%` : ""}
|
||||
</span>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
import { ShieldCheck } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ServerMetrics } from "@/main-axios";
|
||||
import { MetricCard } from "./MetricCard";
|
||||
|
||||
export function FirewallCard({ metrics }: { metrics: ServerMetrics | null }) {
|
||||
const { t } = useTranslation();
|
||||
const fw = metrics?.firewall;
|
||||
|
||||
const totalRules =
|
||||
fw?.chains?.reduce((sum, c) => sum + (c.rules?.length ?? 0), 0) ?? 0;
|
||||
|
||||
return (
|
||||
<MetricCard
|
||||
title={t("hostMetrics.firewall.title")}
|
||||
icon={<ShieldCheck className="size-3.5" />}
|
||||
>
|
||||
{!fw || fw.type === "none" ? (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{t("hostMetrics.firewall.noData")}
|
||||
</span>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<span
|
||||
className={`text-xs font-semibold uppercase tracking-wide ${
|
||||
fw.status === "active"
|
||||
? "text-accent-brand"
|
||||
: "text-muted-foreground"
|
||||
}`}
|
||||
>
|
||||
{fw.status === "inactive"
|
||||
? t("hostMetrics.firewall.inactive")
|
||||
: fw.status}
|
||||
</span>
|
||||
<span className="font-mono text-xs text-muted-foreground">
|
||||
{fw.type}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-4 text-xs text-muted-foreground">
|
||||
<span>
|
||||
<span className="font-bold text-foreground">
|
||||
{fw.chains?.length ?? 0}
|
||||
</span>{" "}
|
||||
{t("hostMetrics.firewall.chains")}
|
||||
</span>
|
||||
<span>
|
||||
<span className="font-bold text-foreground">{totalRules}</span>{" "}
|
||||
{t("hostMetrics.firewall.rules")}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</MetricCard>
|
||||
);
|
||||
}
|
||||
@@ -1,205 +0,0 @@
|
||||
import { useId } from "react";
|
||||
import { Gpu } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ServerMetrics } from "@/main-axios";
|
||||
import type { GpuDevice, GpuProcess } from "@/types/stats-widgets";
|
||||
import { MiniStat, RadialGauge, Sparkline, StatRow } from "@/components/charts";
|
||||
import { MetricCard } from "./MetricCard";
|
||||
import type { GpuHistories, GpuHistory } from "./gpu-history";
|
||||
|
||||
const NA = "N/A";
|
||||
const EMPTY_HISTORY: GpuHistory = { utilization: [], memory: [] };
|
||||
|
||||
function formatGiB(mib: number | null): string {
|
||||
return mib === null ? NA : (mib / 1024).toFixed(1);
|
||||
}
|
||||
|
||||
function formatVram(gpu: GpuDevice): string {
|
||||
return gpu.memoryUsedMiB === null || gpu.memoryTotalMiB === null
|
||||
? NA
|
||||
: `${formatGiB(gpu.memoryUsedMiB)}/${formatGiB(gpu.memoryTotalMiB)}G`;
|
||||
}
|
||||
|
||||
function formatWhole(value: number | null, unit: string): string {
|
||||
return value === null ? NA : `${Math.round(value)}${unit}`;
|
||||
}
|
||||
|
||||
function formatPower(gpu: GpuDevice): string {
|
||||
if (gpu.powerDrawWatts === null && gpu.powerLimitWatts === null) return NA;
|
||||
return `${formatWhole(gpu.powerDrawWatts, "")}/${formatWhole(gpu.powerLimitWatts, "")}W`;
|
||||
}
|
||||
|
||||
function processVram(process: GpuProcess): string {
|
||||
const vram =
|
||||
process.memoryUsedMiB === null
|
||||
? NA
|
||||
: `${formatGiB(process.memoryUsedMiB)}G`;
|
||||
return process.gpuIndex === null ? vram : `${vram} · GPU ${process.gpuIndex}`;
|
||||
}
|
||||
|
||||
function executableName(path: string): string {
|
||||
return path.split(/[\\/]/).pop() || path;
|
||||
}
|
||||
|
||||
/** A captioned 0-100% sparkline, so the two trends under each GPU are told apart. */
|
||||
function TrendSparkline({
|
||||
caption,
|
||||
data,
|
||||
colorClassName,
|
||||
}: {
|
||||
caption: string;
|
||||
data: number[];
|
||||
colorClassName?: string;
|
||||
}) {
|
||||
const captionId = useId();
|
||||
|
||||
return (
|
||||
<figure aria-labelledby={captionId} className="flex min-w-0 flex-col gap-1">
|
||||
<figcaption
|
||||
id={captionId}
|
||||
className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground"
|
||||
>
|
||||
{caption}
|
||||
</figcaption>
|
||||
<Sparkline
|
||||
data={data}
|
||||
domain={[0, 100]}
|
||||
height={36}
|
||||
colorClassName={colorClassName}
|
||||
/>
|
||||
</figure>
|
||||
);
|
||||
}
|
||||
|
||||
function GpuDeviceRow({
|
||||
gpu,
|
||||
history,
|
||||
}: {
|
||||
gpu: GpuDevice;
|
||||
history: GpuHistory;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex min-w-0 items-baseline gap-1.5 text-xs">
|
||||
<span className="font-mono text-muted-foreground">#{gpu.index}</span>
|
||||
<span className="truncate font-semibold">{gpu.name}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-4">
|
||||
<RadialGauge
|
||||
value={gpu.utilizationPercent}
|
||||
size={96}
|
||||
caption={t("hostMetrics.gpu.utilization")}
|
||||
/>
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-2">
|
||||
<div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
|
||||
<MiniStat
|
||||
caption={t("hostMetrics.gpu.memory")}
|
||||
value={formatVram(gpu)}
|
||||
/>
|
||||
<MiniStat
|
||||
caption={t("hostMetrics.gpu.temperature")}
|
||||
value={formatWhole(gpu.temperatureCelsius, "°C")}
|
||||
/>
|
||||
<MiniStat
|
||||
caption={t("hostMetrics.gpu.power")}
|
||||
value={formatPower(gpu)}
|
||||
/>
|
||||
<MiniStat
|
||||
caption={t("hostMetrics.gpu.fan")}
|
||||
value={formatWhole(gpu.fanPercent, "%")}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<TrendSparkline
|
||||
caption={t("hostMetrics.gpu.utilization")}
|
||||
data={[...history.utilization, gpu.utilizationPercent ?? 0]}
|
||||
/>
|
||||
<TrendSparkline
|
||||
caption={t("hostMetrics.gpu.memory")}
|
||||
data={[...history.memory, gpu.memoryPercent ?? 0]}
|
||||
colorClassName="text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function GpuCard({
|
||||
metrics,
|
||||
gpuHistories,
|
||||
}: {
|
||||
metrics: ServerMetrics | null;
|
||||
gpuHistories: GpuHistories;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const gpus = metrics?.gpu?.gpus ?? [];
|
||||
const processes = metrics?.gpu?.processes ?? [];
|
||||
const driverVersion = gpus[0]?.driverVersion;
|
||||
|
||||
return (
|
||||
<MetricCard
|
||||
title={t("hostMetrics.gpu.title")}
|
||||
icon={<Gpu className="size-3.5" />}
|
||||
action={
|
||||
driverVersion ? (
|
||||
<span className="font-mono text-[10px] text-muted-foreground">
|
||||
{t("hostMetrics.gpu.driver", { version: driverVersion })}
|
||||
</span>
|
||||
) : undefined
|
||||
}
|
||||
scroll={gpus.length > 2 || processes.length > 6}
|
||||
scrollMax={520}
|
||||
>
|
||||
{gpus.length === 0 ? (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{t("hostMetrics.gpu.noDevice")}
|
||||
</span>
|
||||
) : (
|
||||
<div className="flex flex-col gap-4">
|
||||
{gpus.map((gpu) => (
|
||||
<GpuDeviceRow
|
||||
key={gpu.index}
|
||||
gpu={gpu}
|
||||
history={gpuHistories[gpu.index] ?? EMPTY_HISTORY}
|
||||
/>
|
||||
))}
|
||||
|
||||
<div className="flex flex-col">
|
||||
<span className="mb-1 text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
|
||||
{t("hostMetrics.gpu.processes")}
|
||||
</span>
|
||||
{processes.length === 0 ? (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{t("hostMetrics.gpu.noProcesses")}
|
||||
</span>
|
||||
) : (
|
||||
<div className="flex flex-col divide-y divide-border">
|
||||
{processes.map((process) => (
|
||||
<StatRow
|
||||
key={`${process.gpuIndex}-${process.pid}`}
|
||||
label={
|
||||
<span className="flex items-baseline gap-1.5">
|
||||
<span title={process.name} className="text-foreground">
|
||||
{executableName(process.name)}
|
||||
</span>
|
||||
<span className="font-mono text-[10px]">
|
||||
{process.pid}
|
||||
</span>
|
||||
</span>
|
||||
}
|
||||
value={processVram(process)}
|
||||
mono
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</MetricCard>
|
||||
);
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
import { UserCheck, UserX } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ServerMetrics } from "@/main-axios";
|
||||
import { MetricCard } from "./MetricCard";
|
||||
|
||||
export function LoginStatsCard({ metrics }: { metrics: ServerMetrics | null }) {
|
||||
const { t } = useTranslation();
|
||||
const loginStats = metrics?.login_stats;
|
||||
const recentLogins = loginStats?.recentLogins ?? [];
|
||||
const failedLogins = loginStats?.failedLogins ?? [];
|
||||
|
||||
const allLogins = [
|
||||
...recentLogins.map((l) => ({ ...l, status: "success" as const })),
|
||||
...failedLogins.map((l) => ({ ...l, status: "failed" as const })),
|
||||
]
|
||||
.sort((a, b) => new Date(b.time).getTime() - new Date(a.time).getTime())
|
||||
.slice(0, 10);
|
||||
|
||||
return (
|
||||
<MetricCard
|
||||
title={t("hostMetrics.loginStats")}
|
||||
icon={<UserCheck className="size-3.5" />}
|
||||
scroll
|
||||
>
|
||||
{allLogins.length === 0 ? (
|
||||
<span className="py-2 text-xs italic text-muted-foreground">
|
||||
{t("hostMetrics.noRecentLoginData")}
|
||||
</span>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{allLogins.map((login, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className={`flex items-center justify-between border p-2 ${login.status === "success" ? "border-border bg-muted/30" : "border-destructive/30 bg-destructive/5"}`}
|
||||
>
|
||||
<div className="flex min-w-0 flex-col">
|
||||
<div className="flex items-center gap-1.5">
|
||||
{login.status === "failed" ? (
|
||||
<UserX className="size-3 shrink-0 text-destructive" />
|
||||
) : (
|
||||
<UserCheck className="size-3 shrink-0 text-accent-brand" />
|
||||
)}
|
||||
<span
|
||||
className={`truncate text-xs font-bold ${login.status === "failed" ? "text-destructive" : ""}`}
|
||||
>
|
||||
{login.user}
|
||||
</span>
|
||||
</div>
|
||||
<span className="truncate font-mono text-[10px] text-muted-foreground">
|
||||
{login.ip}
|
||||
</span>
|
||||
</div>
|
||||
<span className="shrink-0 text-[10px] text-muted-foreground">
|
||||
{new Date(login.time).toLocaleTimeString()}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</MetricCard>
|
||||
);
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { MemoryStick } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ServerMetrics } from "@/main-axios";
|
||||
import { RadialGauge, Sparkline, MiniStat } from "@/components/charts";
|
||||
import { MetricCard } from "./MetricCard";
|
||||
import { LineChart, type LineChartSeries } from "@/components/charts/LineChart";
|
||||
import {
|
||||
getMetricsHistory,
|
||||
type MetricsHistoryRow,
|
||||
} from "@/api/host-metrics-api";
|
||||
import { CardTimeTabs, type HistoryTab } from "./CardTimeTabs";
|
||||
|
||||
export function MemoryCard({
|
||||
metrics,
|
||||
history,
|
||||
hostId,
|
||||
}: {
|
||||
metrics: ServerMetrics | null;
|
||||
history: number[];
|
||||
hostId: number | null;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [activeTab, setActiveTab] = useState<HistoryTab>("live");
|
||||
const [rows, setRows] = useState<MetricsHistoryRow[] | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (activeTab === "live" || hostId == null) return;
|
||||
let cancelled = false;
|
||||
setLoading(true);
|
||||
setRows(null);
|
||||
getMetricsHistory(hostId, { range: activeTab })
|
||||
.then((res) => {
|
||||
if (!cancelled) {
|
||||
setRows(res.rows);
|
||||
setLoading(false);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setLoading(false);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [activeTab, hostId]);
|
||||
|
||||
const percent = metrics?.memory?.percent ?? null;
|
||||
const usedGiB = metrics?.memory?.usedGiB ?? null;
|
||||
const totalGiB = metrics?.memory?.totalGiB ?? null;
|
||||
const freeGiB =
|
||||
usedGiB !== null && totalGiB !== null ? totalGiB - usedGiB : null;
|
||||
|
||||
const series: LineChartSeries[] = [
|
||||
{
|
||||
key: "mem",
|
||||
label: t("hostMetrics.memoryUsage"),
|
||||
color: "var(--chart-3)",
|
||||
data: rows?.map((r) => r.mem_percent) ?? [],
|
||||
},
|
||||
];
|
||||
const timestamps = rows?.map((r) => r.ts) ?? [];
|
||||
|
||||
return (
|
||||
<MetricCard
|
||||
title={t("hostMetrics.memoryUsage")}
|
||||
icon={<MemoryStick className="size-3.5" />}
|
||||
action={
|
||||
hostId != null ? (
|
||||
<CardTimeTabs value={activeTab} onChange={setActiveTab} />
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
<div className="flex flex-col gap-3">
|
||||
{activeTab === "live" && (
|
||||
<div className="flex items-center gap-4">
|
||||
<RadialGauge value={percent} />
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-2">
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<MiniStat
|
||||
caption={t("hostMetrics.memory")}
|
||||
value={
|
||||
usedGiB !== null && totalGiB !== null
|
||||
? `${usedGiB.toFixed(1)}/${totalGiB.toFixed(1)}G`
|
||||
: "N/A"
|
||||
}
|
||||
/>
|
||||
<MiniStat
|
||||
caption={t("hostMetrics.free")}
|
||||
value={freeGiB !== null ? `${freeGiB.toFixed(1)}G` : "N/A"}
|
||||
/>
|
||||
</div>
|
||||
<Sparkline
|
||||
data={[...history, percent ?? 0]}
|
||||
domain={[0, 100]}
|
||||
height={48}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{activeTab !== "live" && (
|
||||
<>
|
||||
{loading && (
|
||||
<div className="flex h-36 items-center justify-center text-xs text-muted-foreground">
|
||||
{t("common.loading")}
|
||||
</div>
|
||||
)}
|
||||
{!loading && rows !== null && rows.length === 0 && (
|
||||
<div className="flex h-36 items-center justify-center text-xs text-muted-foreground">
|
||||
{t("metricsHistory.noData")}
|
||||
</div>
|
||||
)}
|
||||
{!loading && rows !== null && rows.length > 0 && (
|
||||
<LineChart
|
||||
series={series}
|
||||
timestamps={timestamps}
|
||||
domain={[0, 100]}
|
||||
yFormatter={(v) => `${v.toFixed(0)}%`}
|
||||
height={160}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</MetricCard>
|
||||
);
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/** Default cap (px) for a scrollable card body before it scrolls. */
|
||||
const DEFAULT_SCROLL_MAX = 360;
|
||||
|
||||
/**
|
||||
* Card shell for Host Metrics tiles. In the masonry grid tiles are
|
||||
* content-sized (auto height), so the card grows to fit its content. Scrollable
|
||||
* cards (long lists/logs) cap their body at `scrollMax` px and scroll beyond,
|
||||
* which keeps the masonry tidy while short cards stay compact.
|
||||
*/
|
||||
export function MetricCard({
|
||||
title,
|
||||
icon,
|
||||
action,
|
||||
children,
|
||||
bodyClassName,
|
||||
scroll = false,
|
||||
scrollMax = DEFAULT_SCROLL_MAX,
|
||||
}: {
|
||||
title: string;
|
||||
icon: ReactNode;
|
||||
action?: ReactNode;
|
||||
children: ReactNode;
|
||||
bodyClassName?: string;
|
||||
/** When true the body caps its height and scrolls instead of growing. */
|
||||
scroll?: boolean;
|
||||
/** Max body height in px for scrollable cards. */
|
||||
scrollMax?: number;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex min-h-0 flex-col overflow-hidden border border-border bg-card">
|
||||
<div className="flex shrink-0 items-center gap-2 border-b border-border px-4 py-2.5">
|
||||
<span className="text-muted-foreground">{icon}</span>
|
||||
<span className="flex-1 truncate text-xs font-semibold uppercase tracking-widest text-muted-foreground">
|
||||
{title}
|
||||
</span>
|
||||
{action && <div className="ml-auto shrink-0">{action}</div>}
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
"min-h-0 flex-1 px-3 py-3 md:px-4",
|
||||
scroll ? "overflow-y-auto thin-scrollbar" : "overflow-hidden",
|
||||
bodyClassName,
|
||||
)}
|
||||
style={scroll ? { maxHeight: scrollMax } : undefined}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,206 +0,0 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Cable, Container, Network, Wifi, WifiOff } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ServerMetrics } from "@/main-axios";
|
||||
import { MetricCard } from "./MetricCard";
|
||||
import { LineChart, type LineChartSeries } from "@/components/charts/LineChart";
|
||||
import {
|
||||
getMetricsHistory,
|
||||
type MetricsHistoryRow,
|
||||
} from "@/api/host-metrics-api";
|
||||
import { CardTimeTabs, type HistoryTab } from "./CardTimeTabs";
|
||||
|
||||
function ifaceIcon(name: string) {
|
||||
if (/^(wl|wlan|wifi|ath)/.test(name))
|
||||
return <Wifi className="size-3 text-muted-foreground/60" />;
|
||||
if (/^(eth|en|enp|eno|ens)/.test(name))
|
||||
return <Cable className="size-3 text-muted-foreground/60" />;
|
||||
if (/^(docker|br-|veth|virbr|vlan|bond|tun|tap|wg|lo)/.test(name))
|
||||
return <Container className="size-3 text-muted-foreground/60" />;
|
||||
return <Network className="size-3 text-muted-foreground/60" />;
|
||||
}
|
||||
|
||||
function computeNetRates(rows: MetricsHistoryRow[]): {
|
||||
rxRates: Array<number | null>;
|
||||
txRates: Array<number | null>;
|
||||
} {
|
||||
const rxRates: Array<number | null> = [];
|
||||
const txRates: Array<number | null> = [];
|
||||
for (let i = 0; i < rows.length; i++) {
|
||||
if (i === 0) {
|
||||
rxRates.push(null);
|
||||
txRates.push(null);
|
||||
continue;
|
||||
}
|
||||
const prev = rows[i - 1];
|
||||
const curr = rows[i];
|
||||
const dtSec =
|
||||
(new Date(curr.ts).getTime() - new Date(prev.ts).getTime()) / 1000;
|
||||
if (
|
||||
dtSec < 0.5 ||
|
||||
prev.net_rx_bytes == null ||
|
||||
curr.net_rx_bytes == null ||
|
||||
prev.net_tx_bytes == null ||
|
||||
curr.net_tx_bytes == null
|
||||
) {
|
||||
rxRates.push(null);
|
||||
txRates.push(null);
|
||||
continue;
|
||||
}
|
||||
const rxDelta = curr.net_rx_bytes - prev.net_rx_bytes;
|
||||
const txDelta = curr.net_tx_bytes - prev.net_tx_bytes;
|
||||
rxRates.push(rxDelta < 0 ? null : rxDelta / dtSec);
|
||||
txRates.push(txDelta < 0 ? null : txDelta / dtSec);
|
||||
}
|
||||
return { rxRates, txRates };
|
||||
}
|
||||
|
||||
function formatBytes(bps: number): string {
|
||||
if (bps >= 1024 * 1024) return `${(bps / 1024 / 1024).toFixed(1)} MB/s`;
|
||||
if (bps >= 1024) return `${(bps / 1024).toFixed(1)} KB/s`;
|
||||
return `${Math.round(bps)} B/s`;
|
||||
}
|
||||
|
||||
export function NetworkCard({
|
||||
metrics,
|
||||
hostId,
|
||||
}: {
|
||||
metrics: ServerMetrics | null;
|
||||
hostId: number | null;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [activeTab, setActiveTab] = useState<HistoryTab>("live");
|
||||
const [rows, setRows] = useState<MetricsHistoryRow[] | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (activeTab === "live" || hostId == null) return;
|
||||
let cancelled = false;
|
||||
setLoading(true);
|
||||
setRows(null);
|
||||
getMetricsHistory(hostId, { range: activeTab })
|
||||
.then((res) => {
|
||||
if (!cancelled) {
|
||||
setRows(res.rows);
|
||||
setLoading(false);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setLoading(false);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [activeTab, hostId]);
|
||||
|
||||
const interfaces = metrics?.network?.interfaces ?? [];
|
||||
|
||||
const { rxRates, txRates } = rows
|
||||
? computeNetRates(rows)
|
||||
: { rxRates: [], txRates: [] };
|
||||
const netMax = Math.max(
|
||||
rxRates.reduce<number>((m, v) => (v != null && v > m ? v : m), 0),
|
||||
txRates.reduce<number>((m, v) => (v != null && v > m ? v : m), 0),
|
||||
1024,
|
||||
);
|
||||
const timestamps = rows?.map((r) => r.ts) ?? [];
|
||||
const hasNetData = rxRates.some((v) => v !== null);
|
||||
|
||||
const rxSeries: LineChartSeries = {
|
||||
key: "rx",
|
||||
label: t("metricsHistory.download"),
|
||||
color: "var(--chart-2)",
|
||||
data: rxRates,
|
||||
};
|
||||
const txSeries: LineChartSeries = {
|
||||
key: "tx",
|
||||
label: t("metricsHistory.upload"),
|
||||
color: "var(--chart-5)",
|
||||
data: txRates,
|
||||
};
|
||||
|
||||
return (
|
||||
<MetricCard
|
||||
title={t("hostMetrics.networkInterfaces")}
|
||||
icon={<Network className="size-3.5" />}
|
||||
scroll={activeTab === "live"}
|
||||
action={
|
||||
hostId != null ? (
|
||||
<CardTimeTabs value={activeTab} onChange={setActiveTab} />
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
{activeTab === "live" &&
|
||||
(interfaces.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center gap-2 py-6 text-muted-foreground">
|
||||
<WifiOff className="size-6 opacity-40" />
|
||||
<span className="text-xs">
|
||||
{t("hostMetrics.noInterfacesFound")}
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{interfaces.map((iface, i) => (
|
||||
<div
|
||||
key={`${iface.name}-${i}`}
|
||||
className="flex flex-col gap-1 border border-border bg-muted/30 p-2"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
{ifaceIcon(iface.name)}
|
||||
<span
|
||||
className={`size-1.5 rounded-full ${iface.state === "UP" ? "bg-accent-brand" : "bg-muted-foreground/50"}`}
|
||||
/>
|
||||
<span className="font-mono text-sm font-bold">
|
||||
{iface.name}
|
||||
</span>
|
||||
</div>
|
||||
<span className="border border-border px-1.5 py-px text-[10px] font-semibold uppercase text-muted-foreground">
|
||||
{iface.state}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between font-mono text-[10px] text-muted-foreground">
|
||||
<span className="truncate">{iface.ip}</span>
|
||||
{(iface.rxRateBps != null || iface.txRateBps != null) && (
|
||||
<span className="shrink-0">
|
||||
↓{" "}
|
||||
{iface.rxRateBps == null
|
||||
? "—"
|
||||
: formatBytes(iface.rxRateBps)}{" "}
|
||||
/ ↑{" "}
|
||||
{iface.txRateBps == null
|
||||
? "—"
|
||||
: formatBytes(iface.txRateBps)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
{activeTab !== "live" && (
|
||||
<>
|
||||
{loading && (
|
||||
<div className="flex h-36 items-center justify-center text-xs text-muted-foreground">
|
||||
{t("common.loading")}
|
||||
</div>
|
||||
)}
|
||||
{!loading && rows !== null && !hasNetData && (
|
||||
<div className="flex h-36 items-center justify-center text-xs text-muted-foreground">
|
||||
{t("metricsHistory.noData")}
|
||||
</div>
|
||||
)}
|
||||
{!loading && hasNetData && (
|
||||
<LineChart
|
||||
series={[rxSeries, txSeries]}
|
||||
timestamps={timestamps}
|
||||
domain={[0, netMax]}
|
||||
yFormatter={formatBytes}
|
||||
height={160}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</MetricCard>
|
||||
);
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { Unplug, Search } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ServerMetrics, ListeningPort } from "@/main-axios";
|
||||
import { MetricCard } from "./MetricCard";
|
||||
import { Select2 } from "@/components/select2";
|
||||
|
||||
function formatAddress(addr: string) {
|
||||
return addr === "0.0.0.0" || addr === "*" || addr === "::" ? "*" : addr;
|
||||
}
|
||||
|
||||
function PortRow({ port }: { port: ListeningPort }) {
|
||||
return (
|
||||
<div className="grid grid-cols-[3.5rem_3rem_1fr_4rem] gap-2 overflow-hidden border-b border-border/50 py-1 font-mono text-xs last:border-0">
|
||||
<span className="truncate font-bold text-accent-brand">
|
||||
{port.localPort}
|
||||
</span>
|
||||
<span className="truncate text-muted-foreground">
|
||||
{port.protocol.toUpperCase()}
|
||||
</span>
|
||||
<span className="truncate font-semibold">
|
||||
{port.process ?? (port.pid ? `PID:${port.pid}` : "—")}
|
||||
</span>
|
||||
<span className="truncate text-right text-muted-foreground">
|
||||
{formatAddress(port.localAddress)}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function PortsCard({ metrics }: { metrics: ServerMetrics | null }) {
|
||||
const { t } = useTranslation();
|
||||
const [query, setQuery] = useState("");
|
||||
const [proto, setProto] = useState<"all" | "tcp" | "udp">("all");
|
||||
const ports = useMemo(() => metrics?.ports?.ports ?? [], [metrics]);
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
const q = query.toLowerCase();
|
||||
return ports.filter((p) => {
|
||||
if (proto !== "all" && p.protocol.toLowerCase() !== proto) return false;
|
||||
if (!q) return true;
|
||||
return (
|
||||
String(p.localPort).includes(q) ||
|
||||
(p.process ?? "").toLowerCase().includes(q) ||
|
||||
String(p.pid ?? "").includes(q) ||
|
||||
p.localAddress.toLowerCase().includes(q)
|
||||
);
|
||||
});
|
||||
}, [ports, query, proto]);
|
||||
|
||||
return (
|
||||
<MetricCard
|
||||
title={t("hostMetrics.ports.title")}
|
||||
icon={<Unplug className="size-3.5" />}
|
||||
scroll
|
||||
>
|
||||
<div className="mb-2 flex items-center gap-1.5">
|
||||
<div className="relative flex-1">
|
||||
<Search className="pointer-events-none absolute left-2 top-1/2 size-3 -translate-y-1/2 text-muted-foreground/60" />
|
||||
<input
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder={t("hostMetrics.ports.search")}
|
||||
className="h-7 w-full border border-border bg-background pl-7 pr-2 text-xs outline-none focus:ring-1 focus:ring-ring"
|
||||
/>
|
||||
</div>
|
||||
<Select2
|
||||
value={proto}
|
||||
onChange={(e) => setProto(e.target.value as "all" | "tcp" | "udp")}
|
||||
className="h-7 border border-border bg-background px-1 text-xs"
|
||||
>
|
||||
<option value="all">{t("hostMetrics.ports.allProtocols")}</option>
|
||||
<option value="tcp">TCP</option>
|
||||
<option value="udp">UDP</option>
|
||||
</Select2>
|
||||
<span className="shrink-0 text-[10px] tabular-nums text-muted-foreground">
|
||||
{filtered.length}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex flex-col">
|
||||
<div className="grid grid-cols-[3.5rem_3rem_1fr_4rem] gap-2 border-b border-border pb-1 text-[10px] font-bold uppercase text-muted-foreground">
|
||||
<span>{t("hostMetrics.ports.port")}</span>
|
||||
<span>{t("hostMetrics.ports.protocol")}</span>
|
||||
<span>{t("hostMetrics.ports.process")}</span>
|
||||
<span className="text-right">{t("hostMetrics.ports.address")}</span>
|
||||
</div>
|
||||
{filtered.length === 0 ? (
|
||||
<span className="py-2 text-xs italic text-muted-foreground">
|
||||
{t("hostMetrics.ports.noData")}
|
||||
</span>
|
||||
) : (
|
||||
filtered.map((port, i) => (
|
||||
<PortRow
|
||||
key={`${port.protocol}-${port.localPort}-${i}`}
|
||||
port={port}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</MetricCard>
|
||||
);
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
import { Cpu } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ServerMetrics } from "@/main-axios";
|
||||
import { StatRow } from "@/components/charts";
|
||||
import { MetricCard } from "./MetricCard";
|
||||
|
||||
export function ProcessesCard({ metrics }: { metrics: ServerMetrics | null }) {
|
||||
const { t } = useTranslation();
|
||||
const procs = metrics?.processes;
|
||||
const top = procs?.top ?? [];
|
||||
|
||||
return (
|
||||
<MetricCard
|
||||
title={t("hostMetrics.processes")}
|
||||
icon={<Cpu className="size-3.5" />}
|
||||
scroll
|
||||
>
|
||||
<div className="mb-2 flex items-center gap-4 text-xs">
|
||||
{procs?.total != null && (
|
||||
<span>
|
||||
<span className="font-bold text-foreground">{procs.total}</span>{" "}
|
||||
<span className="text-muted-foreground">
|
||||
{t("hostMetrics.processesTotal")}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
{procs?.running != null && (
|
||||
<span>
|
||||
<span className="font-bold text-accent-brand">{procs.running}</span>{" "}
|
||||
<span className="text-muted-foreground">
|
||||
{t("hostMetrics.processesRunning")}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{top.length === 0 ? (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{t("hostMetrics.noProcessesFound")}
|
||||
</span>
|
||||
) : (
|
||||
<div className="flex flex-col divide-y divide-border">
|
||||
{top.slice(0, 10).map((p) => (
|
||||
<StatRow
|
||||
key={p.pid}
|
||||
label={p.command}
|
||||
value={`${p.cpu}% cpu · ${p.mem}% mem`}
|
||||
mono
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</MetricCard>
|
||||
);
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
import { Server } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ServerMetrics } from "@/main-axios";
|
||||
import { StatRow } from "@/components/charts";
|
||||
import { MetricCard } from "./MetricCard";
|
||||
|
||||
export function SystemCard({ metrics }: { metrics: ServerMetrics | null }) {
|
||||
const { t } = useTranslation();
|
||||
const system = metrics?.system;
|
||||
const uptime = metrics?.uptime;
|
||||
|
||||
const rows = [
|
||||
{ label: t("hostMetrics.hostname"), value: system?.hostname },
|
||||
{ label: t("hostMetrics.operatingSystem"), value: system?.os },
|
||||
{ label: t("hostMetrics.kernel"), value: system?.kernel },
|
||||
{ label: t("hostMetrics.architecture"), value: system?.arch },
|
||||
{ label: t("hostMetrics.uptime"), value: uptime?.formatted },
|
||||
].filter((r) => r.value);
|
||||
|
||||
return (
|
||||
<MetricCard
|
||||
title={t("hostMetrics.systemInfo")}
|
||||
icon={<Server className="size-3.5" />}
|
||||
scroll
|
||||
>
|
||||
{rows.length === 0 ? (
|
||||
<span className="text-xs text-muted-foreground">N/A</span>
|
||||
) : (
|
||||
<div className="flex flex-col divide-y divide-border">
|
||||
{rows.map(({ label, value }) => (
|
||||
<StatRow key={label} label={label} value={value} mono />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</MetricCard>
|
||||
);
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
import { Thermometer } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ServerMetrics } from "@/main-axios";
|
||||
import { StatRow } from "@/components/charts";
|
||||
import { MetricCard } from "./MetricCard";
|
||||
import { useEffect, useState } from "react";
|
||||
import {
|
||||
selectTemperatureSensor,
|
||||
temperaturePreferenceKey,
|
||||
} from "../temperature-preference";
|
||||
|
||||
function formatTemperature(value: number | null | undefined): string {
|
||||
return typeof value === "number" && Number.isFinite(value)
|
||||
? `${value.toFixed(1)}°C`
|
||||
: "N/A";
|
||||
}
|
||||
|
||||
export function TemperatureCard({
|
||||
metrics,
|
||||
hostId,
|
||||
}: {
|
||||
metrics: ServerMetrics | null;
|
||||
hostId: number | null;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const temperature = metrics?.temperature;
|
||||
const sensors = temperature?.sensors ?? [];
|
||||
const [preferredLabel, setPreferredLabel] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
setPreferredLabel(
|
||||
hostId === null
|
||||
? ""
|
||||
: (localStorage.getItem(temperaturePreferenceKey(hostId)) ?? ""),
|
||||
);
|
||||
}, [hostId]);
|
||||
|
||||
const preferredSensor = selectTemperatureSensor(sensors, preferredLabel);
|
||||
const displayedTemperature =
|
||||
preferredSensor?.celsius ?? temperature?.highestCelsius;
|
||||
const displayedLabel =
|
||||
preferredSensor?.label ?? t("hostMetrics.highestTemperature");
|
||||
|
||||
const chooseSensor = (label: string) => {
|
||||
setPreferredLabel(label);
|
||||
if (hostId === null) return;
|
||||
const key = temperaturePreferenceKey(hostId);
|
||||
if (label) localStorage.setItem(key, label);
|
||||
else localStorage.removeItem(key);
|
||||
};
|
||||
|
||||
return (
|
||||
<MetricCard
|
||||
title={t("hostMetrics.temperature")}
|
||||
icon={<Thermometer className="size-3.5" />}
|
||||
scroll={sensors.length > 4}
|
||||
scrollMax={220}
|
||||
>
|
||||
<div className="flex flex-col gap-3">
|
||||
<div>
|
||||
<div className="text-3xl font-semibold tabular-nums">
|
||||
{formatTemperature(displayedTemperature)}
|
||||
</div>
|
||||
<div className="mt-1 text-xs text-muted-foreground">
|
||||
{displayedLabel}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{sensors.length > 1 && (
|
||||
<label className="flex flex-col gap-1 text-xs text-muted-foreground">
|
||||
<span>{t("hostMetrics.primaryTemperatureSensor")}</span>
|
||||
<select
|
||||
value={preferredSensor?.label ?? ""}
|
||||
onChange={(event) => chooseSensor(event.target.value)}
|
||||
className="h-8 border border-border bg-background px-2 text-xs text-foreground outline-none focus:ring-1 focus:ring-ring"
|
||||
>
|
||||
<option value="">{t("hostMetrics.highestTemperature")}</option>
|
||||
{sensors.map((sensor) => (
|
||||
<option key={sensor.label} value={sensor.label}>
|
||||
{sensor.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
|
||||
{sensors.length === 0 ? (
|
||||
<span className="text-xs text-muted-foreground">N/A</span>
|
||||
) : (
|
||||
<div className="flex flex-col divide-y divide-border">
|
||||
{sensors.map((sensor) => (
|
||||
<StatRow
|
||||
key={`${sensor.label}-${sensor.celsius}`}
|
||||
label={sensor.label}
|
||||
value={formatTemperature(sensor.celsius)}
|
||||
mono
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</MetricCard>
|
||||
);
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
import { Clock } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ServerMetrics } from "@/main-axios";
|
||||
import { MetricCard } from "./MetricCard";
|
||||
|
||||
export function UptimeCard({ metrics }: { metrics: ServerMetrics | null }) {
|
||||
const { t } = useTranslation();
|
||||
const uptime = metrics?.uptime;
|
||||
|
||||
return (
|
||||
<MetricCard
|
||||
title={t("hostMetrics.uptime")}
|
||||
icon={<Clock className="size-3.5" />}
|
||||
>
|
||||
<div className="flex h-full flex-col justify-center gap-2">
|
||||
<span className="text-2xl font-bold leading-none text-accent-brand md:text-3xl">
|
||||
{uptime?.formatted ?? "N/A"}
|
||||
</span>
|
||||
{uptime?.seconds != null && (
|
||||
<span className="font-mono text-xs text-muted-foreground">
|
||||
{Math.floor(uptime.seconds).toLocaleString()}{" "}
|
||||
{t("hostMetrics.seconds")}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</MetricCard>
|
||||
);
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
import type { GpuDevice } from "@/types/stats-widgets";
|
||||
|
||||
export interface GpuHistory {
|
||||
utilization: number[];
|
||||
memory: number[];
|
||||
}
|
||||
|
||||
/** Live sparkline series keyed by GPU index. */
|
||||
export type GpuHistories = Record<number, GpuHistory>;
|
||||
|
||||
/**
|
||||
* Appends one poll's readings to each GPU's series. GPUs missing from the poll
|
||||
* lose their series so a re-enumerated device never inherits stale samples.
|
||||
*/
|
||||
export function appendGpuHistories(
|
||||
prev: GpuHistories,
|
||||
gpus: GpuDevice[] | undefined,
|
||||
maxLength: number,
|
||||
): GpuHistories {
|
||||
const add = (arr: number[] | undefined, v: number | null) =>
|
||||
[...(arr ?? []), v ?? 0].slice(-maxLength);
|
||||
|
||||
const next: GpuHistories = {};
|
||||
for (const gpu of gpus ?? []) {
|
||||
next[gpu.index] = {
|
||||
utilization: add(prev[gpu.index]?.utilization, gpu.utilizationPercent),
|
||||
memory: add(prev[gpu.index]?.memory, gpu.memoryPercent),
|
||||
};
|
||||
}
|
||||
return next;
|
||||
}
|
||||
@@ -1,227 +0,0 @@
|
||||
import type { ComponentType, ReactNode } from "react";
|
||||
import type { ServerMetrics } from "@/main-axios";
|
||||
import {
|
||||
defaultColSpanFor,
|
||||
defaultHeightFor,
|
||||
type HostMetricsCardId,
|
||||
} from "@/types/host-metrics";
|
||||
import { CpuCard } from "./CpuCard";
|
||||
import { MemoryCard } from "./MemoryCard";
|
||||
import { DiskCard } from "./DiskCard";
|
||||
import { NetworkCard } from "./NetworkCard";
|
||||
import { UptimeCard } from "./UptimeCard";
|
||||
import { SystemCard } from "./SystemCard";
|
||||
import { LoginStatsCard } from "./LoginStatsCard";
|
||||
import { PortsCard } from "./PortsCard";
|
||||
import { ProcessesCard } from "./ProcessesCard";
|
||||
import { FirewallCard } from "./FirewallCard";
|
||||
import { TemperatureCard } from "./TemperatureCard";
|
||||
import { GpuCard } from "./GpuCard";
|
||||
import type { GpuHistories } from "./gpu-history";
|
||||
import { ServiceManagerCard } from "./managers/ServiceManagerCard";
|
||||
import { ProcessInspectorCard } from "./managers/ProcessInspectorCard";
|
||||
import { PackageManagerCard } from "./managers/PackageManagerCard";
|
||||
import { CronManagerCard } from "./managers/CronManagerCard";
|
||||
import { SslManagerCard } from "./managers/SslManagerCard";
|
||||
import { FirewallManagerCard } from "./managers/FirewallManagerCard";
|
||||
import { UserManagerCard } from "./managers/UserManagerCard";
|
||||
import { HealthCheckCard } from "./managers/HealthCheckCard";
|
||||
import { LogViewerCard } from "./managers/LogViewerCard";
|
||||
import {
|
||||
TopMemoryCard,
|
||||
SystemdTimersCard,
|
||||
DiskBreakdownCard,
|
||||
} from "./managers/SimpleManagerCards";
|
||||
import { WireGuardManagerCard } from "./managers/WireGuardManagerCard";
|
||||
import { TailscaleManagerCard } from "./managers/TailscaleManagerCard";
|
||||
|
||||
export interface MetricCardHistories {
|
||||
cpu: number[];
|
||||
memory: number[];
|
||||
disk: number[];
|
||||
gpu: GpuHistories;
|
||||
}
|
||||
|
||||
export interface CardRenderContext {
|
||||
metrics: ServerMetrics | null;
|
||||
histories: MetricCardHistories;
|
||||
hostId: number | null;
|
||||
}
|
||||
|
||||
export interface CardDefinition {
|
||||
id: HostMetricsCardId;
|
||||
/** i18n key for the card's display label. */
|
||||
labelKey: string;
|
||||
kind: "metric" | "manager";
|
||||
render: (ctx: CardRenderContext) => ReactNode;
|
||||
}
|
||||
|
||||
type SimpleMetricCard = ComponentType<{
|
||||
metrics: ServerMetrics | null;
|
||||
hostId: number | null;
|
||||
}>;
|
||||
type HistoryMetricCard = ComponentType<{
|
||||
metrics: ServerMetrics | null;
|
||||
history: number[];
|
||||
hostId: number | null;
|
||||
}>;
|
||||
|
||||
function metricCard(
|
||||
id: HostMetricsCardId,
|
||||
labelKey: string,
|
||||
Comp: SimpleMetricCard,
|
||||
): CardDefinition {
|
||||
return {
|
||||
id,
|
||||
labelKey,
|
||||
kind: "metric",
|
||||
render: ({ metrics, hostId }) => <Comp metrics={metrics} hostId={hostId} />,
|
||||
};
|
||||
}
|
||||
|
||||
function historyCard(
|
||||
id: HostMetricsCardId,
|
||||
labelKey: string,
|
||||
Comp: HistoryMetricCard,
|
||||
series: "cpu" | "memory" | "disk",
|
||||
): CardDefinition {
|
||||
return {
|
||||
id,
|
||||
labelKey,
|
||||
kind: "metric",
|
||||
render: ({ metrics, histories, hostId }) => (
|
||||
<Comp metrics={metrics} history={histories[series]} hostId={hostId} />
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
type ManagerCardComp = ComponentType<{ hostId: number | null }>;
|
||||
|
||||
function managerCard(
|
||||
id: HostMetricsCardId,
|
||||
labelKey: string,
|
||||
Comp: ManagerCardComp,
|
||||
): CardDefinition {
|
||||
return {
|
||||
id,
|
||||
labelKey,
|
||||
kind: "manager",
|
||||
render: ({ hostId }) => <Comp hostId={hostId} />,
|
||||
};
|
||||
}
|
||||
|
||||
export const CARD_DEFINITIONS: Record<string, CardDefinition> = {
|
||||
cpu: historyCard("cpu", "hostMetrics.cpuUsage", CpuCard, "cpu"),
|
||||
memory: historyCard(
|
||||
"memory",
|
||||
"hostMetrics.memoryUsage",
|
||||
MemoryCard,
|
||||
"memory",
|
||||
),
|
||||
disk: historyCard("disk", "hostMetrics.diskUsage", DiskCard, "disk"),
|
||||
network: metricCard("network", "hostMetrics.networkInterfaces", NetworkCard),
|
||||
uptime: metricCard("uptime", "hostMetrics.uptime", UptimeCard),
|
||||
system: metricCard("system", "hostMetrics.systemInfo", SystemCard),
|
||||
login_stats: metricCard(
|
||||
"login_stats",
|
||||
"hostMetrics.loginStats",
|
||||
LoginStatsCard,
|
||||
),
|
||||
ports: metricCard("ports", "hostMetrics.ports.title", PortsCard),
|
||||
processes: metricCard("processes", "hostMetrics.processes", ProcessesCard),
|
||||
firewall: metricCard("firewall", "hostMetrics.firewall.title", FirewallCard),
|
||||
temperature: metricCard(
|
||||
"temperature",
|
||||
"hostMetrics.temperature",
|
||||
TemperatureCard,
|
||||
),
|
||||
gpu: {
|
||||
id: "gpu",
|
||||
labelKey: "hostMetrics.gpu.title",
|
||||
kind: "metric",
|
||||
render: ({ metrics, histories }) => (
|
||||
<GpuCard metrics={metrics} gpuHistories={histories.gpu} />
|
||||
),
|
||||
},
|
||||
service_manager: managerCard(
|
||||
"service_manager",
|
||||
"hostMetrics.managers.services",
|
||||
ServiceManagerCard,
|
||||
),
|
||||
process_inspector: managerCard(
|
||||
"process_inspector",
|
||||
"hostMetrics.managers.processInspector",
|
||||
ProcessInspectorCard,
|
||||
),
|
||||
log_viewer: managerCard(
|
||||
"log_viewer",
|
||||
"hostMetrics.managers.logViewer",
|
||||
LogViewerCard,
|
||||
),
|
||||
cron_manager: managerCard(
|
||||
"cron_manager",
|
||||
"hostMetrics.managers.cron",
|
||||
CronManagerCard,
|
||||
),
|
||||
package_manager: managerCard(
|
||||
"package_manager",
|
||||
"hostMetrics.managers.packages",
|
||||
PackageManagerCard,
|
||||
),
|
||||
ssl_manager: managerCard(
|
||||
"ssl_manager",
|
||||
"hostMetrics.managers.ssl",
|
||||
SslManagerCard,
|
||||
),
|
||||
firewall_manager: managerCard(
|
||||
"firewall_manager",
|
||||
"hostMetrics.managers.firewall",
|
||||
FirewallManagerCard,
|
||||
),
|
||||
user_manager: managerCard(
|
||||
"user_manager",
|
||||
"hostMetrics.managers.users",
|
||||
UserManagerCard,
|
||||
),
|
||||
health_check: managerCard(
|
||||
"health_check",
|
||||
"hostMetrics.managers.healthCheck",
|
||||
HealthCheckCard,
|
||||
),
|
||||
disk_breakdown: managerCard(
|
||||
"disk_breakdown",
|
||||
"hostMetrics.managers.diskBreakdown",
|
||||
DiskBreakdownCard,
|
||||
),
|
||||
systemd_timers: managerCard(
|
||||
"systemd_timers",
|
||||
"hostMetrics.managers.systemdTimers",
|
||||
SystemdTimersCard,
|
||||
),
|
||||
top_memory: managerCard(
|
||||
"top_memory",
|
||||
"hostMetrics.managers.topMemory",
|
||||
TopMemoryCard,
|
||||
),
|
||||
wireguard_manager: managerCard(
|
||||
"wireguard_manager",
|
||||
"hostMetrics.managers.wireguard",
|
||||
WireGuardManagerCard,
|
||||
),
|
||||
tailscale_manager: managerCard(
|
||||
"tailscale_manager",
|
||||
"hostMetrics.managers.tailscale",
|
||||
TailscaleManagerCard,
|
||||
),
|
||||
};
|
||||
|
||||
/** All card ids implemented and available in the Add tray. */
|
||||
export const IMPLEMENTED_CARD_IDS = Object.keys(
|
||||
CARD_DEFINITIONS,
|
||||
) as HostMetricsCardId[];
|
||||
|
||||
export function getCardDefinition(id: string): CardDefinition | undefined {
|
||||
return CARD_DEFINITIONS[id];
|
||||
}
|
||||
|
||||
export { defaultColSpanFor, defaultHeightFor };
|
||||
@@ -1,162 +0,0 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Clock4, Plus, Trash2, Save } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/button";
|
||||
import { managerPost } from "@/main-axios";
|
||||
import { useManagerData, extractError } from "./useManagerData";
|
||||
import { ManagerCardShell } from "./ManagerCardShell";
|
||||
import { ManagerSearch } from "./ManagerToolbar";
|
||||
|
||||
interface CronEntry {
|
||||
raw: string;
|
||||
enabled: boolean;
|
||||
schedule: string;
|
||||
command: string;
|
||||
}
|
||||
|
||||
export function CronManagerCard({ hostId }: { hostId: number | null }) {
|
||||
const { t } = useTranslation();
|
||||
const { data, loading, error, refresh } = useManagerData<{
|
||||
entries: CronEntry[];
|
||||
}>(hostId, "cron");
|
||||
const [entries, setEntries] = useState<CronEntry[]>([]);
|
||||
const [dirty, setDirty] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [query, setQuery] = useState("");
|
||||
|
||||
// Keep the real array index so edits/removes target the right entry even when
|
||||
// the list is filtered by the search box.
|
||||
const visible = useMemo(() => {
|
||||
const q = query.toLowerCase();
|
||||
return entries
|
||||
.map((entry, index) => ({ entry, index }))
|
||||
.filter(
|
||||
({ entry }) =>
|
||||
!q ||
|
||||
entry.schedule.toLowerCase().includes(q) ||
|
||||
entry.command.toLowerCase().includes(q),
|
||||
);
|
||||
}, [entries, query]);
|
||||
|
||||
useEffect(() => {
|
||||
if (data?.entries) {
|
||||
setEntries(data.entries);
|
||||
setDirty(false);
|
||||
}
|
||||
}, [data]);
|
||||
|
||||
const update = (i: number, patch: Partial<CronEntry>) => {
|
||||
setEntries((prev) =>
|
||||
prev.map((e, idx) => (idx === i ? { ...e, ...patch } : e)),
|
||||
);
|
||||
setDirty(true);
|
||||
};
|
||||
const remove = (i: number) => {
|
||||
setEntries((prev) => prev.filter((_, idx) => idx !== i));
|
||||
setDirty(true);
|
||||
};
|
||||
const add = () => {
|
||||
setEntries((prev) => [
|
||||
...prev,
|
||||
{ raw: "", enabled: true, schedule: "0 * * * *", command: "" },
|
||||
]);
|
||||
setDirty(true);
|
||||
};
|
||||
|
||||
const save = async () => {
|
||||
if (hostId == null) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const res = await managerPost<{ success: boolean; output: string }>(
|
||||
hostId,
|
||||
"cron",
|
||||
{ entries },
|
||||
);
|
||||
if (res.success) {
|
||||
toast.success(t("hostMetrics.managers.cronSaved"));
|
||||
setDirty(false);
|
||||
refresh();
|
||||
} else {
|
||||
toast.error(res.output || t("hostMetrics.managers.actionFailed"));
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(extractError(e).message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<ManagerCardShell
|
||||
title={t("hostMetrics.managers.cron")}
|
||||
icon={<Clock4 className="size-3.5" />}
|
||||
loading={loading}
|
||||
error={error}
|
||||
onRefresh={refresh}
|
||||
headerExtra={
|
||||
<>
|
||||
<Button variant="ghost" size="xs" onClick={add}>
|
||||
<Plus className="size-3" />
|
||||
</Button>
|
||||
{dirty && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="xs"
|
||||
disabled={saving}
|
||||
onClick={save}
|
||||
>
|
||||
<Save className="size-3" />
|
||||
{t("hostMetrics.managers.save")}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
empty={!loading && entries.length === 0}
|
||||
>
|
||||
{entries.length > 5 && (
|
||||
<ManagerSearch
|
||||
value={query}
|
||||
onChange={setQuery}
|
||||
count={visible.length}
|
||||
/>
|
||||
)}
|
||||
<div className="flex flex-col gap-2">
|
||||
{visible.map(({ entry: e, index: i }) => (
|
||||
<div
|
||||
key={i}
|
||||
className="flex flex-col gap-1 border border-border bg-muted/20 p-2"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={e.enabled}
|
||||
onChange={(ev) => update(i, { enabled: ev.target.checked })}
|
||||
className="accent-accent-brand"
|
||||
title={t("hostMetrics.managers.enabled")}
|
||||
/>
|
||||
<input
|
||||
value={e.schedule}
|
||||
onChange={(ev) => update(i, { schedule: ev.target.value })}
|
||||
placeholder="0 * * * *"
|
||||
className="h-6 w-28 border border-border bg-background px-1.5 font-mono text-[11px] outline-none focus:ring-1 focus:ring-ring"
|
||||
/>
|
||||
<button
|
||||
onClick={() => remove(i)}
|
||||
className="ml-auto text-muted-foreground hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
<input
|
||||
value={e.command}
|
||||
onChange={(ev) => update(i, { command: ev.target.value })}
|
||||
placeholder={t("hostMetrics.managers.command")}
|
||||
className="h-6 w-full border border-border bg-background px-1.5 font-mono text-[11px] outline-none focus:ring-1 focus:ring-ring"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ManagerCardShell>
|
||||
);
|
||||
}
|
||||
@@ -1,230 +0,0 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { ShieldCheck, Plus, Trash2, Save } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/button";
|
||||
import { managerPost, type FirewallChain } from "@/main-axios";
|
||||
import { useManagerData, extractError } from "./useManagerData";
|
||||
import { ManagerCardShell } from "./ManagerCardShell";
|
||||
import { ManagerSearch } from "./ManagerToolbar";
|
||||
import { Select2 } from "@/components/select2";
|
||||
|
||||
interface FirewallData {
|
||||
type: "iptables" | "nftables" | "none";
|
||||
status: string;
|
||||
chains: FirewallChain[];
|
||||
}
|
||||
|
||||
export function FirewallManagerCard({ hostId }: { hostId: number | null }) {
|
||||
const { t } = useTranslation();
|
||||
const { data, loading, error, refresh } = useManagerData<FirewallData>(
|
||||
hostId,
|
||||
"firewall",
|
||||
);
|
||||
const [proto, setProto] = useState<"tcp" | "udp">("tcp");
|
||||
const [port, setPort] = useState("");
|
||||
const [target, setTarget] = useState<"ACCEPT" | "DROP" | "REJECT">("ACCEPT");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [query, setQuery] = useState("");
|
||||
|
||||
const rule = async (op: "add" | "delete") => {
|
||||
if (hostId == null) return;
|
||||
const portNum = Number(port);
|
||||
if (!Number.isInteger(portNum) || portNum < 1 || portNum > 65535) {
|
||||
toast.error(t("hostMetrics.managers.invalidPort"));
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await managerPost<{ success: boolean; output: string }>(
|
||||
hostId,
|
||||
"firewall",
|
||||
{ op, protocol: proto, port: portNum, target },
|
||||
"rule",
|
||||
);
|
||||
if (res.success) {
|
||||
toast.success(t("hostMetrics.managers.ruleApplied"));
|
||||
refresh();
|
||||
} else {
|
||||
toast.error(res.output || t("hostMetrics.managers.actionFailed"));
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(extractError(e).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const persist = async () => {
|
||||
if (hostId == null) return;
|
||||
setBusy(true);
|
||||
toast.loading(t("hostMetrics.managers.working"), { id: "fw-persist" });
|
||||
try {
|
||||
const res = await managerPost<{ success: boolean; output: string }>(
|
||||
hostId,
|
||||
"firewall",
|
||||
{},
|
||||
"persist",
|
||||
);
|
||||
toast[res.success ? "success" : "error"](
|
||||
res.success
|
||||
? t("hostMetrics.managers.firewallPersisted")
|
||||
: t("hostMetrics.managers.actionFailed"),
|
||||
{ id: "fw-persist", description: res.output?.slice(-200) },
|
||||
);
|
||||
} catch (e) {
|
||||
toast.error(extractError(e).message, { id: "fw-persist" });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const chains = useMemo(() => {
|
||||
const q = query.toLowerCase();
|
||||
return (data?.chains ?? [])
|
||||
.map((c) => ({
|
||||
...c,
|
||||
rules: c.rules.filter(
|
||||
(r) =>
|
||||
!q ||
|
||||
r.target.toLowerCase().includes(q) ||
|
||||
(r.dport ?? "").includes(q) ||
|
||||
r.protocol.toLowerCase().includes(q) ||
|
||||
r.source.toLowerCase().includes(q),
|
||||
),
|
||||
}))
|
||||
.filter((c) => c.rules.length > 0 || !q);
|
||||
}, [data?.chains, query]);
|
||||
|
||||
return (
|
||||
<ManagerCardShell
|
||||
title={t("hostMetrics.managers.firewall")}
|
||||
icon={<ShieldCheck className="size-3.5" />}
|
||||
loading={loading}
|
||||
error={error}
|
||||
onRefresh={refresh}
|
||||
headerExtra={
|
||||
<>
|
||||
<span className="text-[10px] uppercase tracking-widest text-muted-foreground">
|
||||
{data?.type ?? ""}
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
disabled={busy || data?.type === "none"}
|
||||
onClick={persist}
|
||||
title={t("hostMetrics.managers.firewallPersist")}
|
||||
>
|
||||
<Save className="size-3" />
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="mb-3 flex flex-col gap-2 border border-dashed border-border p-2">
|
||||
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
|
||||
{t("hostMetrics.managers.addInputRule")}
|
||||
</span>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Select2
|
||||
value={proto}
|
||||
onChange={(e) => setProto(e.target.value as "tcp" | "udp")}
|
||||
className="h-7 border border-border bg-background px-1 text-xs"
|
||||
>
|
||||
<option value="tcp">tcp</option>
|
||||
<option value="udp">udp</option>
|
||||
</Select2>
|
||||
<input
|
||||
value={port}
|
||||
onChange={(e) => setPort(e.target.value)}
|
||||
placeholder={t("hostMetrics.ports.port")}
|
||||
className="h-7 w-16 border border-border bg-background px-1.5 text-xs outline-none focus:ring-1 focus:ring-ring"
|
||||
/>
|
||||
<Select2
|
||||
value={target}
|
||||
onChange={(e) =>
|
||||
setTarget(e.target.value as "ACCEPT" | "DROP" | "REJECT")
|
||||
}
|
||||
className="h-7 border border-border bg-background px-1 text-xs"
|
||||
>
|
||||
<option>ACCEPT</option>
|
||||
<option>DROP</option>
|
||||
<option>REJECT</option>
|
||||
</Select2>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="xs"
|
||||
disabled={busy}
|
||||
onClick={() => rule("add")}
|
||||
>
|
||||
<Plus className="size-3" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
disabled={busy}
|
||||
onClick={() => rule("delete")}
|
||||
>
|
||||
<Trash2 className="size-3" />
|
||||
</Button>
|
||||
</div>
|
||||
<span className="text-[10px] text-yellow-500">
|
||||
{t("hostMetrics.managers.firewallWarning")}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<ManagerSearch value={query} onChange={setQuery} />
|
||||
|
||||
{chains.length === 0 ? (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{t("hostMetrics.firewall.noData")}
|
||||
</span>
|
||||
) : (
|
||||
<div className="flex flex-col gap-3">
|
||||
{chains.map((chain) => (
|
||||
<div key={chain.name} className="flex flex-col">
|
||||
<div className="mb-1 flex items-center justify-between">
|
||||
<span className="text-[10px] font-bold uppercase tracking-widest text-foreground">
|
||||
{chain.name}
|
||||
</span>
|
||||
{chain.policy && (
|
||||
<span className="text-[10px] text-muted-foreground">
|
||||
{t("hostMetrics.firewall.policy")}: {chain.policy}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{chain.rules.length === 0 ? (
|
||||
<span className="text-[10px] italic text-muted-foreground/60">
|
||||
{t("hostMetrics.firewall.noRules")}
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
<div className="grid grid-cols-4 gap-2 border-b border-border pb-1 text-[10px] font-bold uppercase text-muted-foreground">
|
||||
<span>{t("hostMetrics.firewall.action")}</span>
|
||||
<span>{t("hostMetrics.firewall.protocol")}</span>
|
||||
<span>{t("hostMetrics.firewall.port")}</span>
|
||||
<span>{t("hostMetrics.firewall.source")}</span>
|
||||
</div>
|
||||
{chain.rules.map((r, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="grid grid-cols-4 gap-2 border-b border-border/50 py-1 font-mono text-xs last:border-0"
|
||||
>
|
||||
<span className="font-bold">{r.target}</span>
|
||||
<span className="text-muted-foreground">
|
||||
{r.protocol.toUpperCase()}
|
||||
</span>
|
||||
<span>{r.dport ?? "—"}</span>
|
||||
<span className="truncate text-muted-foreground">
|
||||
{r.source}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</ManagerCardShell>
|
||||
);
|
||||
}
|
||||
@@ -1,311 +0,0 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
HeartPulse,
|
||||
CheckCircle2,
|
||||
XCircle,
|
||||
Plus,
|
||||
Trash2,
|
||||
Play,
|
||||
Pencil,
|
||||
} from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/button";
|
||||
import { Sparkline } from "@/components/charts";
|
||||
import { managerPost } from "@/main-axios";
|
||||
import { useManagerData, extractError } from "./useManagerData";
|
||||
import { ManagerCardShell } from "./ManagerCardShell";
|
||||
import { Select2 } from "@/components/select2";
|
||||
|
||||
interface HealthCheck {
|
||||
id: string;
|
||||
name: string;
|
||||
type: "tcp" | "http";
|
||||
target: string;
|
||||
port?: number;
|
||||
path?: string;
|
||||
}
|
||||
interface HealthResult {
|
||||
checkId: string;
|
||||
ok: boolean;
|
||||
latencyMs: number | null;
|
||||
detail: string;
|
||||
}
|
||||
interface HistoryRow {
|
||||
checkId: string;
|
||||
ts: string;
|
||||
ok: boolean;
|
||||
latencyMs: number | null;
|
||||
}
|
||||
interface HealthData {
|
||||
checks: HealthCheck[];
|
||||
results: HealthResult[];
|
||||
history: HistoryRow[];
|
||||
}
|
||||
|
||||
function newCheck(): HealthCheck {
|
||||
return {
|
||||
id: `c_${Math.random().toString(36).slice(2, 9)}`,
|
||||
name: "",
|
||||
type: "tcp",
|
||||
target: "",
|
||||
port: 80,
|
||||
};
|
||||
}
|
||||
|
||||
export function HealthCheckCard({ hostId }: { hostId: number | null }) {
|
||||
const { t } = useTranslation();
|
||||
const { data, loading, error, refresh } = useManagerData<HealthData>(
|
||||
hostId,
|
||||
"health",
|
||||
);
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [draft, setDraft] = useState<HealthCheck[]>([]);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [running, setRunning] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (data?.checks && !editing) setDraft(data.checks);
|
||||
}, [data?.checks, editing]);
|
||||
|
||||
const byCheck = useMemo(() => {
|
||||
const map = new Map<string, HistoryRow[]>();
|
||||
for (const h of data?.history ?? []) {
|
||||
const arr = map.get(h.checkId) ?? [];
|
||||
arr.push(h);
|
||||
map.set(h.checkId, arr);
|
||||
}
|
||||
return map;
|
||||
}, [data?.history]);
|
||||
|
||||
const save = async () => {
|
||||
if (hostId == null) return;
|
||||
for (const c of draft) {
|
||||
if (!c.name.trim() || !c.target.trim()) {
|
||||
toast.error(t("hostMetrics.managers.healthMissingFields"));
|
||||
return;
|
||||
}
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
const res = await managerPost<{ success: boolean }>(
|
||||
hostId,
|
||||
"health",
|
||||
{ checks: draft },
|
||||
"config",
|
||||
);
|
||||
if (res.success) {
|
||||
toast.success(t("hostMetrics.managers.healthSaved"));
|
||||
setEditing(false);
|
||||
refresh();
|
||||
} else {
|
||||
toast.error(t("hostMetrics.managers.actionFailed"));
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(extractError(e).message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const runNow = async () => {
|
||||
if (hostId == null) return;
|
||||
setRunning(true);
|
||||
try {
|
||||
await managerPost(hostId, "health", {}, "run");
|
||||
refresh();
|
||||
} catch (e) {
|
||||
toast.error(extractError(e).message);
|
||||
} finally {
|
||||
setRunning(false);
|
||||
}
|
||||
};
|
||||
|
||||
const updateDraft = (id: string, patch: Partial<HealthCheck>) =>
|
||||
setDraft((d) => d.map((c) => (c.id === id ? { ...c, ...patch } : c)));
|
||||
|
||||
return (
|
||||
<ManagerCardShell
|
||||
title={t("hostMetrics.managers.healthCheck")}
|
||||
icon={<HeartPulse className="size-3.5" />}
|
||||
loading={loading}
|
||||
error={error}
|
||||
onRefresh={refresh}
|
||||
headerExtra={
|
||||
editing ? (
|
||||
<>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
onClick={() => {
|
||||
setEditing(false);
|
||||
setDraft(data?.checks ?? []);
|
||||
}}
|
||||
>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="xs"
|
||||
disabled={saving}
|
||||
onClick={save}
|
||||
>
|
||||
{t("common.save")}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
disabled={running || (data?.checks?.length ?? 0) === 0}
|
||||
onClick={runNow}
|
||||
>
|
||||
<Play className="size-3" />
|
||||
{t("hostMetrics.managers.healthRun")}
|
||||
</Button>
|
||||
<Button variant="ghost" size="xs" onClick={() => setEditing(true)}>
|
||||
<Pencil className="size-3" />
|
||||
{t("common.edit")}
|
||||
</Button>
|
||||
</>
|
||||
)
|
||||
}
|
||||
>
|
||||
{editing ? (
|
||||
<div className="flex flex-col gap-2">
|
||||
{draft.map((c) => (
|
||||
<div
|
||||
key={c.id}
|
||||
className="flex flex-col gap-1.5 border border-border bg-muted/20 p-2"
|
||||
>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<input
|
||||
value={c.name}
|
||||
onChange={(e) => updateDraft(c.id, { name: e.target.value })}
|
||||
placeholder={t("hostMetrics.managers.healthName")}
|
||||
className="h-7 flex-1 border border-border bg-background px-2 text-xs outline-none focus:ring-1 focus:ring-ring"
|
||||
/>
|
||||
<Select2
|
||||
value={c.type}
|
||||
onChange={(e) =>
|
||||
updateDraft(c.id, {
|
||||
type: e.target.value as "tcp" | "http",
|
||||
})
|
||||
}
|
||||
className="h-7 border border-border bg-background px-1 text-xs"
|
||||
>
|
||||
<option value="tcp">TCP</option>
|
||||
<option value="http">HTTP</option>
|
||||
</Select2>
|
||||
<button
|
||||
onClick={() =>
|
||||
setDraft((d) => d.filter((x) => x.id !== c.id))
|
||||
}
|
||||
className="flex size-7 items-center justify-center text-muted-foreground hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<input
|
||||
value={c.target}
|
||||
onChange={(e) =>
|
||||
updateDraft(c.id, { target: e.target.value })
|
||||
}
|
||||
placeholder={t("hostMetrics.managers.healthTarget")}
|
||||
className="h-7 flex-1 border border-border bg-background px-2 font-mono text-xs outline-none focus:ring-1 focus:ring-ring"
|
||||
/>
|
||||
{c.type === "tcp" ? (
|
||||
<input
|
||||
type="number"
|
||||
value={c.port ?? ""}
|
||||
onChange={(e) =>
|
||||
updateDraft(c.id, { port: Number(e.target.value) })
|
||||
}
|
||||
placeholder={t("hostMetrics.ports.port")}
|
||||
className="h-7 w-16 border border-border bg-background px-1.5 text-xs outline-none focus:ring-1 focus:ring-ring"
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
value={c.path ?? ""}
|
||||
onChange={(e) =>
|
||||
updateDraft(c.id, { path: e.target.value })
|
||||
}
|
||||
placeholder="/health"
|
||||
className="h-7 w-24 border border-border bg-background px-1.5 font-mono text-xs outline-none focus:ring-1 focus:ring-ring"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="self-start"
|
||||
onClick={() => setDraft((d) => [...d, newCheck()])}
|
||||
>
|
||||
<Plus className="size-3" />
|
||||
{t("hostMetrics.managers.healthAddCheck")}
|
||||
</Button>
|
||||
</div>
|
||||
) : (data?.checks?.length ?? 0) === 0 ? (
|
||||
<div className="flex flex-col items-center gap-2 py-6 text-center">
|
||||
<span className="text-xs text-muted-foreground/60">
|
||||
{t("hostMetrics.managers.noHealthChecks")}
|
||||
</span>
|
||||
<Button variant="outline" size="sm" onClick={() => setEditing(true)}>
|
||||
<Plus className="size-3" />
|
||||
{t("hostMetrics.managers.healthAddCheck")}
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-3">
|
||||
{(data?.checks ?? []).map((check) => {
|
||||
const result = data?.results?.find((r) => r.checkId === check.id);
|
||||
const hist = (byCheck.get(check.id) ?? []).slice().reverse();
|
||||
const upPct =
|
||||
hist.length > 0
|
||||
? Math.round(
|
||||
(hist.filter((h) => h.ok).length / hist.length) * 100,
|
||||
)
|
||||
: null;
|
||||
return (
|
||||
<div
|
||||
key={check.id}
|
||||
className="flex flex-col gap-1 border border-border bg-muted/20 p-2"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
{result?.ok ? (
|
||||
<CheckCircle2 className="size-3.5 text-accent-brand" />
|
||||
) : (
|
||||
<XCircle className="size-3.5 text-destructive" />
|
||||
)}
|
||||
<span className="text-xs font-semibold">{check.name}</span>
|
||||
<span className="font-mono text-[10px] text-muted-foreground/60">
|
||||
{check.type === "tcp"
|
||||
? `${check.target}:${check.port}`
|
||||
: check.target}
|
||||
</span>
|
||||
</div>
|
||||
<span className="font-mono text-[10px] text-muted-foreground">
|
||||
{result?.latencyMs != null ? `${result.latencyMs}ms` : "—"}
|
||||
{upPct != null ? ` · ${upPct}%` : ""}
|
||||
</span>
|
||||
</div>
|
||||
{hist.length > 1 && (
|
||||
<Sparkline
|
||||
data={hist.map((h) => h.latencyMs ?? 0)}
|
||||
height={28}
|
||||
showLastDot={false}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</ManagerCardShell>
|
||||
);
|
||||
}
|
||||
@@ -1,199 +0,0 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { ScrollText } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { managerGet, managerGetSub } from "@/main-axios";
|
||||
import { extractError } from "./useManagerData";
|
||||
import { ManagerCardShell } from "./ManagerCardShell";
|
||||
import { useAdaptivePolling } from "@/hooks/use-adaptive-polling";
|
||||
import { Select2 } from "@/components/select2";
|
||||
|
||||
interface LogFiles {
|
||||
common: string[];
|
||||
files: string[];
|
||||
}
|
||||
|
||||
type Mode = "file" | "unit";
|
||||
|
||||
export function LogViewerCard({ hostId }: { hostId: number | null }) {
|
||||
const { t } = useTranslation();
|
||||
const [mode, setMode] = useState<Mode>("file");
|
||||
const [path, setPath] = useState<string>("/var/log/syslog");
|
||||
const [unit, setUnit] = useState<string>("");
|
||||
const [customPath, setCustomPath] = useState("");
|
||||
const [lines, setLines] = useState(300);
|
||||
const [content, setContent] = useState("");
|
||||
const [grep, setGrep] = useState("");
|
||||
const [follow, setFollow] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [files, setFiles] = useState<string[]>([]);
|
||||
const bodyRef = useRef<HTMLPreElement | null>(null);
|
||||
const contentRef = useRef(content);
|
||||
contentRef.current = content;
|
||||
|
||||
// Load the host's actual log files once.
|
||||
useEffect(() => {
|
||||
if (hostId == null) return;
|
||||
managerGetSub<LogFiles>(hostId, "logs", "files")
|
||||
.then((res) => {
|
||||
const merged = Array.from(
|
||||
new Set([...(res.common ?? []), ...(res.files ?? [])]),
|
||||
);
|
||||
setFiles(merged);
|
||||
if (merged.length && !merged.includes(path)) setPath(merged[0]);
|
||||
})
|
||||
.catch(() => {});
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [hostId]);
|
||||
|
||||
const fetchLog = useCallback(async () => {
|
||||
if (hostId == null) return false;
|
||||
const params: Record<string, string | number> = { lines };
|
||||
if (mode === "unit") {
|
||||
if (!unit.trim()) return false;
|
||||
params.unit = unit.trim();
|
||||
} else {
|
||||
const p = customPath.trim() || path;
|
||||
if (!p) return false;
|
||||
params.path = p;
|
||||
}
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await managerGet<{ content: string }>(hostId, "logs", params);
|
||||
const next = res.content || "";
|
||||
const changed = next !== contentRef.current;
|
||||
if (changed) {
|
||||
contentRef.current = next;
|
||||
setContent(next);
|
||||
requestAnimationFrame(() => {
|
||||
if (bodyRef.current)
|
||||
bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
|
||||
});
|
||||
}
|
||||
return changed;
|
||||
} catch (e) {
|
||||
setError(extractError(e).message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [customPath, hostId, lines, mode, path, unit]);
|
||||
|
||||
useEffect(() => {
|
||||
void fetchLog();
|
||||
// Custom paths are applied on blur/manual refresh, not on every keystroke.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [hostId, mode, path, unit, lines]);
|
||||
|
||||
useAdaptivePolling(
|
||||
fetchLog,
|
||||
{
|
||||
minIntervalMs: 3_000,
|
||||
maxIntervalMs: 18_000,
|
||||
stablePollsPerStep: 2,
|
||||
maxRequestDutyCycle: 0.2,
|
||||
},
|
||||
follow,
|
||||
{ runImmediately: false },
|
||||
);
|
||||
|
||||
const shown = useMemo(() => {
|
||||
if (!grep) return content;
|
||||
const needle = grep.toLowerCase();
|
||||
return content
|
||||
.split("\n")
|
||||
.filter((l) => l.toLowerCase().includes(needle))
|
||||
.join("\n");
|
||||
}, [content, grep]);
|
||||
|
||||
return (
|
||||
<ManagerCardShell
|
||||
title={t("hostMetrics.managers.logViewer")}
|
||||
icon={<ScrollText className="size-3.5" />}
|
||||
loading={loading}
|
||||
error={error ? { message: error } : null}
|
||||
onRefresh={fetchLog}
|
||||
headerExtra={
|
||||
<label className="flex items-center gap-1 text-[10px] text-muted-foreground">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={follow}
|
||||
onChange={(e) => setFollow(e.target.checked)}
|
||||
className="accent-accent-brand"
|
||||
/>
|
||||
{t("hostMetrics.managers.follow")}
|
||||
</label>
|
||||
}
|
||||
>
|
||||
<div className="mb-2 flex items-center gap-1.5">
|
||||
<Select2
|
||||
value={mode}
|
||||
onChange={(e) => setMode(e.target.value as Mode)}
|
||||
className="h-7 border border-border bg-background px-1 text-[11px]"
|
||||
>
|
||||
<option value="file">{t("hostMetrics.managers.logFile")}</option>
|
||||
<option value="unit">{t("hostMetrics.managers.logUnit")}</option>
|
||||
</Select2>
|
||||
{mode === "file" ? (
|
||||
<Select2
|
||||
value={customPath ? "" : path}
|
||||
onChange={(e) => {
|
||||
setCustomPath("");
|
||||
setPath(e.target.value);
|
||||
}}
|
||||
className="h-7 flex-1 border border-border bg-background px-2 font-mono text-[11px] outline-none focus:ring-1 focus:ring-ring"
|
||||
>
|
||||
{files.map((f) => (
|
||||
<option key={f} value={f}>
|
||||
{f}
|
||||
</option>
|
||||
))}
|
||||
</Select2>
|
||||
) : (
|
||||
<input
|
||||
value={unit}
|
||||
onChange={(e) => setUnit(e.target.value)}
|
||||
onBlur={fetchLog}
|
||||
placeholder="nginx.service"
|
||||
className="h-7 flex-1 border border-border bg-background px-2 font-mono text-[11px] outline-none focus:ring-1 focus:ring-ring"
|
||||
/>
|
||||
)}
|
||||
<Select2
|
||||
value={lines}
|
||||
onChange={(e) => setLines(Number(e.target.value))}
|
||||
className="h-7 border border-border bg-background px-1 text-[11px]"
|
||||
>
|
||||
{[100, 300, 500, 1000, 2000].map((n) => (
|
||||
<option key={n} value={n}>
|
||||
{n}
|
||||
</option>
|
||||
))}
|
||||
</Select2>
|
||||
</div>
|
||||
|
||||
{mode === "file" && (
|
||||
<input
|
||||
value={customPath}
|
||||
onChange={(e) => setCustomPath(e.target.value)}
|
||||
onBlur={() => customPath && fetchLog()}
|
||||
placeholder={t("hostMetrics.managers.logCustomPath")}
|
||||
className="mb-2 h-7 w-full border border-border bg-background px-2 font-mono text-[11px] outline-none focus:ring-1 focus:ring-ring"
|
||||
/>
|
||||
)}
|
||||
|
||||
<input
|
||||
value={grep}
|
||||
onChange={(e) => setGrep(e.target.value)}
|
||||
placeholder={t("hostMetrics.managers.logGrep")}
|
||||
className="mb-2 h-7 w-full border border-border bg-background px-2 text-[11px] outline-none focus:ring-1 focus:ring-ring"
|
||||
/>
|
||||
|
||||
<pre
|
||||
ref={bodyRef}
|
||||
className="max-h-[320px] overflow-auto whitespace-pre-wrap break-all border border-border/50 bg-muted/20 p-2 font-mono text-[10px] leading-relaxed"
|
||||
>
|
||||
{shown || t("hostMetrics.managers.noLogData")}
|
||||
</pre>
|
||||
</ManagerCardShell>
|
||||
);
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { RefreshCw, AlertTriangle } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Button } from "@/components/button";
|
||||
import { MetricCard } from "../MetricCard";
|
||||
import type { ManagerError } from "./useManagerData";
|
||||
|
||||
export function ManagerCardShell({
|
||||
title,
|
||||
icon,
|
||||
loading,
|
||||
error,
|
||||
onRefresh,
|
||||
empty,
|
||||
emptyMessage,
|
||||
children,
|
||||
headerExtra,
|
||||
}: {
|
||||
title: string;
|
||||
icon: ReactNode;
|
||||
loading: boolean;
|
||||
error: ManagerError | null;
|
||||
onRefresh: () => void;
|
||||
empty?: boolean;
|
||||
emptyMessage?: string;
|
||||
children: ReactNode;
|
||||
headerExtra?: ReactNode;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<MetricCard
|
||||
title={title}
|
||||
icon={icon}
|
||||
scroll
|
||||
action={
|
||||
<div className="flex items-center gap-1">
|
||||
{headerExtra}
|
||||
<button
|
||||
onClick={onRefresh}
|
||||
className="flex size-6 items-center justify-center text-muted-foreground transition-colors hover:text-foreground"
|
||||
title={t("hostMetrics.refresh")}
|
||||
>
|
||||
<RefreshCw className={`size-3 ${loading ? "animate-spin" : ""}`} />
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{error ? (
|
||||
<div className="flex flex-col items-center gap-2 py-6 text-center">
|
||||
<AlertTriangle className="size-6 text-yellow-500" />
|
||||
<span className="text-xs text-muted-foreground">{error.message}</span>
|
||||
{error.code === "SUDO_REQUIRED" && (
|
||||
<span className="text-[10px] text-muted-foreground">
|
||||
{t("hostMetrics.managers.sudoHint")}
|
||||
</span>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={onRefresh}
|
||||
className="mt-1"
|
||||
>
|
||||
{t("hostMetrics.retry")}
|
||||
</Button>
|
||||
</div>
|
||||
) : empty ? (
|
||||
<div className="flex items-center justify-center py-8 text-xs text-muted-foreground/50">
|
||||
{emptyMessage ?? t("hostMetrics.managers.noData")}
|
||||
</div>
|
||||
) : (
|
||||
children
|
||||
)}
|
||||
</MetricCard>
|
||||
);
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { Search } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
/**
|
||||
* Compact search row shared by manager cards. Optional `extra` renders to the
|
||||
* right (filters, action buttons) and `count` shows a result tally.
|
||||
*/
|
||||
export function ManagerSearch({
|
||||
value,
|
||||
onChange,
|
||||
placeholder,
|
||||
count,
|
||||
extra,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (v: string) => void;
|
||||
placeholder?: string;
|
||||
count?: number;
|
||||
extra?: ReactNode;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="mb-2 flex items-center gap-1.5">
|
||||
<div className="relative flex-1">
|
||||
<Search className="pointer-events-none absolute left-2 top-1/2 size-3 -translate-y-1/2 text-muted-foreground/60" />
|
||||
<input
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
placeholder={placeholder ?? t("hostMetrics.managers.filter")}
|
||||
className="h-7 w-full border border-border bg-background pl-7 pr-2 text-xs outline-none focus:ring-1 focus:ring-ring"
|
||||
/>
|
||||
</div>
|
||||
{count != null && (
|
||||
<span className="shrink-0 text-[10px] tabular-nums text-muted-foreground">
|
||||
{count}
|
||||
</span>
|
||||
)}
|
||||
{extra}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { Package, ArrowUpCircle } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/button";
|
||||
import { managerPost } from "@/main-axios";
|
||||
import { useManagerData, extractError } from "./useManagerData";
|
||||
import { ManagerCardShell } from "./ManagerCardShell";
|
||||
import { ManagerSearch } from "./ManagerToolbar";
|
||||
|
||||
interface UpgradablePackage {
|
||||
name: string;
|
||||
currentVersion?: string;
|
||||
newVersion?: string;
|
||||
}
|
||||
|
||||
export function PackageManagerCard({ hostId }: { hostId: number | null }) {
|
||||
const { t } = useTranslation();
|
||||
const { data, loading, error, refresh } = useManagerData<{
|
||||
pkg: string | null;
|
||||
upgradable: UpgradablePackage[];
|
||||
}>(hostId, "packages");
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const [filter, setFilter] = useState("");
|
||||
const all = useMemo(() => data?.upgradable ?? [], [data?.upgradable]);
|
||||
const pkgs = useMemo(
|
||||
() =>
|
||||
all.filter(
|
||||
(p) => !filter || p.name.toLowerCase().includes(filter.toLowerCase()),
|
||||
),
|
||||
[all, filter],
|
||||
);
|
||||
|
||||
const run = async (action: string, pkg?: string) => {
|
||||
if (hostId == null) return;
|
||||
setBusy(pkg ?? action);
|
||||
toast.loading(t("hostMetrics.managers.working"), { id: "pkg-op" });
|
||||
try {
|
||||
const res = await managerPost<{ success: boolean; output: string }>(
|
||||
hostId,
|
||||
"packages",
|
||||
{ action, pkg },
|
||||
"action",
|
||||
);
|
||||
toast[res.success ? "success" : "error"](
|
||||
res.success
|
||||
? t("hostMetrics.managers.actionDone", { name: pkg ?? "upgrade" })
|
||||
: t("hostMetrics.managers.actionFailed"),
|
||||
{ id: "pkg-op", description: res.output?.slice(-200) },
|
||||
);
|
||||
if (res.success) refresh();
|
||||
} catch (e) {
|
||||
toast.error(extractError(e).message, { id: "pkg-op" });
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<ManagerCardShell
|
||||
title={t("hostMetrics.managers.packages")}
|
||||
icon={<Package className="size-3.5" />}
|
||||
loading={loading}
|
||||
error={error}
|
||||
onRefresh={refresh}
|
||||
empty={!loading && all.length === 0}
|
||||
emptyMessage={t("hostMetrics.managers.allUpToDate")}
|
||||
headerExtra={
|
||||
all.length > 0 ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="xs"
|
||||
disabled={!!busy}
|
||||
onClick={() => run("upgrade-all")}
|
||||
>
|
||||
<ArrowUpCircle className="size-3" />
|
||||
{t("hostMetrics.managers.upgradeAll")}
|
||||
</Button>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
{all.length > 5 && (
|
||||
<ManagerSearch
|
||||
value={filter}
|
||||
onChange={setFilter}
|
||||
count={pkgs.length}
|
||||
/>
|
||||
)}
|
||||
<div className="flex flex-col">
|
||||
{pkgs.map((p) => (
|
||||
<div
|
||||
key={p.name}
|
||||
className="flex items-center justify-between gap-2 border-b border-border/50 py-1.5 last:border-0"
|
||||
>
|
||||
<div className="flex min-w-0 flex-col">
|
||||
<span className="truncate text-xs font-semibold">{p.name}</span>
|
||||
<span className="truncate font-mono text-[10px] text-muted-foreground">
|
||||
{p.currentVersion ? `${p.currentVersion} → ` : ""}
|
||||
{p.newVersion ?? ""}
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
disabled={busy === p.name}
|
||||
onClick={() => run("install", p.name)}
|
||||
>
|
||||
{t("hostMetrics.managers.update")}
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ManagerCardShell>
|
||||
);
|
||||
}
|
||||
@@ -1,192 +0,0 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { ListTree, X, Skull } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { managerPost } from "@/main-axios";
|
||||
import { useManagerData, extractError } from "./useManagerData";
|
||||
import { ManagerCardShell } from "./ManagerCardShell";
|
||||
import { ManagerSearch } from "./ManagerToolbar";
|
||||
import { Select2 } from "@/components/select2";
|
||||
|
||||
interface ProcessRow {
|
||||
pid: number;
|
||||
ppid: number;
|
||||
user: string;
|
||||
cpu: number;
|
||||
mem: number;
|
||||
command: string;
|
||||
args: string;
|
||||
}
|
||||
|
||||
type SortKey = "cpu" | "mem" | "pid";
|
||||
type Signal = "TERM" | "KILL";
|
||||
|
||||
export function ProcessInspectorCard({ hostId }: { hostId: number | null }) {
|
||||
const { t } = useTranslation();
|
||||
const { data, loading, error, refresh } = useManagerData<{
|
||||
processes: ProcessRow[];
|
||||
}>(hostId, "processes");
|
||||
const [filter, setFilter] = useState("");
|
||||
const [sort, setSort] = useState<SortKey>("cpu");
|
||||
const [tree, setTree] = useState(false);
|
||||
const [busy, setBusy] = useState<number | null>(null);
|
||||
|
||||
const all = useMemo(() => data?.processes ?? [], [data?.processes]);
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
const q = filter.toLowerCase();
|
||||
const list = all.filter(
|
||||
(p) =>
|
||||
!q ||
|
||||
p.args.toLowerCase().includes(q) ||
|
||||
p.command.toLowerCase().includes(q) ||
|
||||
String(p.pid).includes(q) ||
|
||||
p.user.toLowerCase().includes(q),
|
||||
);
|
||||
return [...list].sort((a, b) => {
|
||||
if (sort === "pid") return a.pid - b.pid;
|
||||
return b[sort] - a[sort];
|
||||
});
|
||||
}, [all, filter, sort]);
|
||||
|
||||
// Build a depth map for the tree view from ppid links (only among visible).
|
||||
const treeRows = useMemo(() => {
|
||||
if (!tree) return null;
|
||||
const byId = new Map(filtered.map((p) => [p.pid, p]));
|
||||
const children = new Map<number, ProcessRow[]>();
|
||||
const roots: ProcessRow[] = [];
|
||||
for (const p of filtered) {
|
||||
if (p.ppid && byId.has(p.ppid)) {
|
||||
const arr = children.get(p.ppid) ?? [];
|
||||
arr.push(p);
|
||||
children.set(p.ppid, arr);
|
||||
} else {
|
||||
roots.push(p);
|
||||
}
|
||||
}
|
||||
const out: Array<{ proc: ProcessRow; depth: number }> = [];
|
||||
const walk = (p: ProcessRow, depth: number) => {
|
||||
out.push({ proc: p, depth });
|
||||
for (const c of children.get(p.pid) ?? []) walk(c, depth + 1);
|
||||
};
|
||||
roots.forEach((r) => walk(r, 0));
|
||||
return out;
|
||||
}, [tree, filtered]);
|
||||
|
||||
const kill = async (pid: number, signal: Signal) => {
|
||||
if (hostId == null) return;
|
||||
setBusy(pid);
|
||||
try {
|
||||
const res = await managerPost<{ success: boolean; output: string }>(
|
||||
hostId,
|
||||
"processes",
|
||||
{ pid, signal },
|
||||
"signal",
|
||||
);
|
||||
if (res.success) {
|
||||
toast.success(t("hostMetrics.managers.signalSent", { pid }));
|
||||
refresh();
|
||||
} else {
|
||||
toast.error(res.output || t("hostMetrics.managers.actionFailed"));
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(extractError(e).message);
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
const rows = treeRows
|
||||
? treeRows.slice(0, 200)
|
||||
: filtered.slice(0, 200).map((proc) => ({ proc, depth: 0 }));
|
||||
|
||||
return (
|
||||
<ManagerCardShell
|
||||
title={t("hostMetrics.managers.processInspector")}
|
||||
icon={<ListTree className="size-3.5" />}
|
||||
loading={loading}
|
||||
error={error}
|
||||
onRefresh={refresh}
|
||||
empty={!loading && filtered.length === 0}
|
||||
headerExtra={
|
||||
<>
|
||||
<button
|
||||
onClick={() => setTree((v) => !v)}
|
||||
className={`flex h-6 items-center gap-1 border px-1.5 text-[10px] transition-colors ${
|
||||
tree
|
||||
? "border-accent-brand/40 bg-accent-brand/10 text-accent-brand"
|
||||
: "border-border text-muted-foreground hover:text-foreground"
|
||||
}`}
|
||||
>
|
||||
<ListTree className="size-3" />
|
||||
{t("hostMetrics.managers.tree")}
|
||||
</button>
|
||||
<Select2
|
||||
value={sort}
|
||||
onChange={(e) => setSort(e.target.value as SortKey)}
|
||||
disabled={tree}
|
||||
className="h-6 border border-border bg-background px-1 text-[10px] disabled:opacity-40"
|
||||
>
|
||||
<option value="cpu">CPU</option>
|
||||
<option value="mem">MEM</option>
|
||||
<option value="pid">PID</option>
|
||||
</Select2>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<ManagerSearch
|
||||
value={filter}
|
||||
onChange={setFilter}
|
||||
count={filtered.length}
|
||||
/>
|
||||
<div className="flex flex-col">
|
||||
<div className="grid grid-cols-[3rem_2.5rem_2.5rem_1fr_1.5rem] gap-2 border-b border-border pb-1 text-[10px] font-bold uppercase text-muted-foreground">
|
||||
<span>PID</span>
|
||||
<span>CPU</span>
|
||||
<span>MEM</span>
|
||||
<span>CMD</span>
|
||||
<span />
|
||||
</div>
|
||||
{rows.map(({ proc: p, depth }) => (
|
||||
<div
|
||||
key={p.pid}
|
||||
className="relative grid grid-cols-[3rem_2.5rem_2.5rem_1fr_1.5rem] items-center gap-2 border-b border-border/50 py-1 font-mono text-xs last:border-0"
|
||||
>
|
||||
<span className="text-muted-foreground">{p.pid}</span>
|
||||
<span className="font-bold text-accent-brand">
|
||||
{p.cpu.toFixed(0)}%
|
||||
</span>
|
||||
<span>{p.mem.toFixed(0)}%</span>
|
||||
<span
|
||||
className="truncate"
|
||||
title={`${p.user} · ${p.args}`}
|
||||
style={depth ? { paddingLeft: depth * 12 } : undefined}
|
||||
>
|
||||
{depth > 0 && (
|
||||
<span className="text-muted-foreground/40">└ </span>
|
||||
)}
|
||||
{/* `comm` is capped at 15 chars by the kernel; the full command line is in args. */}
|
||||
{p.args || p.command}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => kill(p.pid, "TERM")}
|
||||
onContextMenu={(e) => {
|
||||
e.preventDefault();
|
||||
kill(p.pid, "KILL");
|
||||
}}
|
||||
disabled={busy === p.pid}
|
||||
title={t("hostMetrics.managers.killHint")}
|
||||
className="flex size-5 items-center justify-center text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive disabled:opacity-40"
|
||||
>
|
||||
{busy === p.pid ? (
|
||||
<Skull className="size-3" />
|
||||
) : (
|
||||
<X className="size-3" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ManagerCardShell>
|
||||
);
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { Cog, Play, Square, RotateCw, Power } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { managerPost } from "@/main-axios";
|
||||
import { useManagerData, extractError } from "./useManagerData";
|
||||
import { ManagerCardShell } from "./ManagerCardShell";
|
||||
import { ManagerSearch } from "./ManagerToolbar";
|
||||
|
||||
interface SystemdService {
|
||||
unit: string;
|
||||
active: string;
|
||||
sub: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export function ServiceManagerCard({ hostId }: { hostId: number | null }) {
|
||||
const { t } = useTranslation();
|
||||
const { data, loading, error, refresh } = useManagerData<{
|
||||
services: SystemdService[];
|
||||
}>(hostId, "services");
|
||||
const [filter, setFilter] = useState("");
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
|
||||
const services = useMemo(
|
||||
() =>
|
||||
(data?.services ?? []).filter(
|
||||
(s) =>
|
||||
!filter ||
|
||||
s.unit.toLowerCase().includes(filter.toLowerCase()) ||
|
||||
s.description.toLowerCase().includes(filter.toLowerCase()),
|
||||
),
|
||||
[data?.services, filter],
|
||||
);
|
||||
|
||||
const act = async (unit: string, action: string) => {
|
||||
if (hostId == null) return;
|
||||
setBusy(`${unit}:${action}`);
|
||||
try {
|
||||
const res = await managerPost<{ success: boolean; output: string }>(
|
||||
hostId,
|
||||
"services",
|
||||
{ unit, action },
|
||||
"action",
|
||||
);
|
||||
if (res.success) {
|
||||
toast.success(t("hostMetrics.managers.actionDone", { name: unit }));
|
||||
refresh();
|
||||
} else {
|
||||
toast.error(res.output || t("hostMetrics.managers.actionFailed"));
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(extractError(e).message);
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<ManagerCardShell
|
||||
title={t("hostMetrics.managers.services")}
|
||||
icon={<Cog className="size-3.5" />}
|
||||
loading={loading}
|
||||
error={error}
|
||||
onRefresh={refresh}
|
||||
empty={!loading && services.length === 0}
|
||||
>
|
||||
<ManagerSearch
|
||||
value={filter}
|
||||
onChange={setFilter}
|
||||
count={services.length}
|
||||
/>
|
||||
<div className="flex flex-col">
|
||||
{services.map((s) => (
|
||||
<div
|
||||
key={s.unit}
|
||||
className="flex items-center justify-between gap-2 border-b border-border/50 py-1.5 last:border-0"
|
||||
>
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<span
|
||||
className={`size-1.5 shrink-0 rounded-full ${s.active === "active" ? "bg-accent-brand" : "bg-muted-foreground/40"}`}
|
||||
/>
|
||||
<div className="flex min-w-0 flex-col">
|
||||
<span className="truncate text-xs font-semibold" title={s.unit}>
|
||||
{s.unit.replace(/\.service$/, "")}
|
||||
</span>
|
||||
<span className="truncate text-[10px] text-muted-foreground">
|
||||
{s.sub}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-0.5">
|
||||
<ActionBtn
|
||||
onClick={() => act(s.unit, "start")}
|
||||
busy={busy === `${s.unit}:start`}
|
||||
title={t("hostMetrics.managers.start")}
|
||||
>
|
||||
<Play className="size-3" />
|
||||
</ActionBtn>
|
||||
<ActionBtn
|
||||
onClick={() => act(s.unit, "restart")}
|
||||
busy={busy === `${s.unit}:restart`}
|
||||
title={t("hostMetrics.managers.restart")}
|
||||
>
|
||||
<RotateCw className="size-3" />
|
||||
</ActionBtn>
|
||||
<ActionBtn
|
||||
onClick={() => act(s.unit, "stop")}
|
||||
busy={busy === `${s.unit}:stop`}
|
||||
title={t("hostMetrics.managers.stop")}
|
||||
>
|
||||
<Square className="size-3" />
|
||||
</ActionBtn>
|
||||
<ActionBtn
|
||||
onClick={() =>
|
||||
act(s.unit, s.sub === "running" ? "disable" : "enable")
|
||||
}
|
||||
busy={
|
||||
busy === `${s.unit}:enable` || busy === `${s.unit}:disable`
|
||||
}
|
||||
title={t("hostMetrics.managers.enableDisable")}
|
||||
>
|
||||
<Power className="size-3" />
|
||||
</ActionBtn>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ManagerCardShell>
|
||||
);
|
||||
}
|
||||
|
||||
function ActionBtn({
|
||||
onClick,
|
||||
busy,
|
||||
title,
|
||||
children,
|
||||
}: {
|
||||
onClick: () => void;
|
||||
busy: boolean;
|
||||
title: string;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
onClick={onClick}
|
||||
disabled={busy}
|
||||
title={title}
|
||||
className="flex size-6 items-center justify-center text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40"
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -1,165 +0,0 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { MemoryStick, Timer, HardDrive } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { BarSeries, StatRow } from "@/components/charts";
|
||||
import { useManagerData } from "./useManagerData";
|
||||
import { ManagerCardShell } from "./ManagerCardShell";
|
||||
import { ManagerSearch } from "./ManagerToolbar";
|
||||
|
||||
interface MemProc {
|
||||
pid: number;
|
||||
user: string;
|
||||
mem: number;
|
||||
rss: number;
|
||||
command: string;
|
||||
}
|
||||
interface TimerRow {
|
||||
unit: string;
|
||||
activates: string;
|
||||
next: string;
|
||||
}
|
||||
interface MountUsage {
|
||||
filesystem: string;
|
||||
usePct: number;
|
||||
usedKb: number;
|
||||
sizeKb: number;
|
||||
mount: string;
|
||||
}
|
||||
|
||||
function fmtGiB(kb: number): string {
|
||||
return `${(kb / 1024 / 1024).toFixed(1)}G`;
|
||||
}
|
||||
|
||||
export function TopMemoryCard({ hostId }: { hostId: number | null }) {
|
||||
const { t } = useTranslation();
|
||||
const { data, loading, error, refresh } = useManagerData<{
|
||||
processes: MemProc[];
|
||||
}>(hostId, "top-memory");
|
||||
const [query, setQuery] = useState("");
|
||||
const all = useMemo(() => data?.processes ?? [], [data?.processes]);
|
||||
const procs = useMemo(() => {
|
||||
const q = query.toLowerCase();
|
||||
return all.filter(
|
||||
(p) =>
|
||||
!q ||
|
||||
p.command.toLowerCase().includes(q) ||
|
||||
String(p.pid).includes(q) ||
|
||||
p.user.toLowerCase().includes(q),
|
||||
);
|
||||
}, [all, query]);
|
||||
|
||||
return (
|
||||
<ManagerCardShell
|
||||
title={t("hostMetrics.managers.topMemory")}
|
||||
icon={<MemoryStick className="size-3.5" />}
|
||||
loading={loading}
|
||||
error={error}
|
||||
onRefresh={refresh}
|
||||
empty={!loading && all.length === 0}
|
||||
>
|
||||
{all.length > 5 && (
|
||||
<ManagerSearch value={query} onChange={setQuery} count={procs.length} />
|
||||
)}
|
||||
<BarSeries
|
||||
items={procs.map((p) => ({
|
||||
label: `${p.command} (${p.pid})`,
|
||||
value: p.mem,
|
||||
valueLabel: `${p.mem.toFixed(1)}%`,
|
||||
}))}
|
||||
max={Math.max(1, ...procs.map((p) => p.mem))}
|
||||
/>
|
||||
</ManagerCardShell>
|
||||
);
|
||||
}
|
||||
|
||||
export function SystemdTimersCard({ hostId }: { hostId: number | null }) {
|
||||
const { t } = useTranslation();
|
||||
const { data, loading, error, refresh } = useManagerData<{
|
||||
timers: TimerRow[];
|
||||
}>(hostId, "timers");
|
||||
const [query, setQuery] = useState("");
|
||||
const all = useMemo(() => data?.timers ?? [], [data?.timers]);
|
||||
const timers = useMemo(() => {
|
||||
const q = query.toLowerCase();
|
||||
return all.filter(
|
||||
(tm) =>
|
||||
!q ||
|
||||
tm.unit.toLowerCase().includes(q) ||
|
||||
tm.activates.toLowerCase().includes(q),
|
||||
);
|
||||
}, [all, query]);
|
||||
|
||||
return (
|
||||
<ManagerCardShell
|
||||
title={t("hostMetrics.managers.systemdTimers")}
|
||||
icon={<Timer className="size-3.5" />}
|
||||
loading={loading}
|
||||
error={error}
|
||||
onRefresh={refresh}
|
||||
empty={!loading && all.length === 0}
|
||||
>
|
||||
{all.length > 5 && (
|
||||
<ManagerSearch
|
||||
value={query}
|
||||
onChange={setQuery}
|
||||
count={timers.length}
|
||||
/>
|
||||
)}
|
||||
<div className="flex flex-col divide-y divide-border">
|
||||
{timers.map((tm) => (
|
||||
<StatRow
|
||||
key={tm.unit}
|
||||
label={tm.unit.replace(/\.timer$/, "")}
|
||||
value={tm.activates}
|
||||
mono
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</ManagerCardShell>
|
||||
);
|
||||
}
|
||||
|
||||
export function DiskBreakdownCard({ hostId }: { hostId: number | null }) {
|
||||
const { t } = useTranslation();
|
||||
const { data, loading, error, refresh } = useManagerData<{
|
||||
mounts: MountUsage[];
|
||||
}>(hostId, "disk-breakdown");
|
||||
const [query, setQuery] = useState("");
|
||||
const all = useMemo(() => data?.mounts ?? [], [data?.mounts]);
|
||||
const mounts = useMemo(() => {
|
||||
const q = query.toLowerCase();
|
||||
return all.filter(
|
||||
(m) =>
|
||||
!q ||
|
||||
m.mount.toLowerCase().includes(q) ||
|
||||
m.filesystem.toLowerCase().includes(q),
|
||||
);
|
||||
}, [all, query]);
|
||||
|
||||
return (
|
||||
<ManagerCardShell
|
||||
title={t("hostMetrics.managers.diskBreakdown")}
|
||||
icon={<HardDrive className="size-3.5" />}
|
||||
loading={loading}
|
||||
error={error}
|
||||
onRefresh={refresh}
|
||||
empty={!loading && all.length === 0}
|
||||
>
|
||||
{all.length > 5 && (
|
||||
<ManagerSearch
|
||||
value={query}
|
||||
onChange={setQuery}
|
||||
count={mounts.length}
|
||||
/>
|
||||
)}
|
||||
<BarSeries
|
||||
items={mounts.map((m) => ({
|
||||
label: `${m.mount} (${fmtGiB(m.usedKb)}/${fmtGiB(m.sizeKb)})`,
|
||||
value: m.usePct,
|
||||
valueLabel: `${m.usePct}%`,
|
||||
}))}
|
||||
max={100}
|
||||
/>
|
||||
</ManagerCardShell>
|
||||
);
|
||||
}
|
||||
@@ -1,302 +0,0 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { ShieldCheck, RefreshCw, Plus, X, Trash2 } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Button } from "@/components/button";
|
||||
import { managerPost } from "@/main-axios";
|
||||
import {
|
||||
useManagerData,
|
||||
useManagerAction,
|
||||
extractError,
|
||||
} from "./useManagerData";
|
||||
import { ManagerCardShell } from "./ManagerCardShell";
|
||||
import { Select2 } from "@/components/select2";
|
||||
|
||||
interface CertInfo {
|
||||
client: string;
|
||||
name: string;
|
||||
domains: string[];
|
||||
expiry: string | null;
|
||||
}
|
||||
interface SslData {
|
||||
clients: { certbot: boolean; acmeSh: boolean };
|
||||
certs: CertInfo[];
|
||||
}
|
||||
|
||||
type Challenge = "http-standalone" | "http-webroot" | "dns";
|
||||
|
||||
/** Days until the given expiry string, or null if unparseable. */
|
||||
function daysUntil(expiry: string | null): number | null {
|
||||
if (!expiry) return null;
|
||||
const ts = Date.parse(expiry);
|
||||
if (Number.isNaN(ts)) return null;
|
||||
return Math.round((ts - Date.now()) / 86400000);
|
||||
}
|
||||
|
||||
function ExpiryBadge({ expiry }: { expiry: string | null }) {
|
||||
const { t } = useTranslation();
|
||||
const days = daysUntil(expiry);
|
||||
if (days == null)
|
||||
return <span className="text-muted-foreground">{expiry ?? "—"}</span>;
|
||||
const tone =
|
||||
days < 0
|
||||
? "text-destructive"
|
||||
: days < 14
|
||||
? "text-yellow-500"
|
||||
: "text-accent-brand";
|
||||
return (
|
||||
<span className={tone} title={expiry ?? undefined}>
|
||||
{days < 0
|
||||
? t("hostMetrics.managers.sslExpired")
|
||||
: t("hostMetrics.managers.sslInDays", { days })}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function SslManagerCard({ hostId }: { hostId: number | null }) {
|
||||
const { t } = useTranslation();
|
||||
const { data, loading, error, refresh } = useManagerData<SslData>(
|
||||
hostId,
|
||||
"ssl",
|
||||
);
|
||||
const { busy, run } = useManagerAction(hostId);
|
||||
const [showIssue, setShowIssue] = useState(false);
|
||||
const [domains, setDomains] = useState("");
|
||||
const [challenge, setChallenge] = useState<Challenge>("http-standalone");
|
||||
const [webroot, setWebroot] = useState("");
|
||||
const [dnsProvider, setDnsProvider] = useState("");
|
||||
const [issuing, setIssuing] = useState(false);
|
||||
|
||||
const clients = data?.clients;
|
||||
const activeClient: "certbot" | "acme.sh" | null = clients?.certbot
|
||||
? "certbot"
|
||||
: clients?.acmeSh
|
||||
? "acme.sh"
|
||||
: null;
|
||||
|
||||
const certs = useMemo(() => data?.certs ?? [], [data?.certs]);
|
||||
|
||||
const renew = (dryRun: boolean) => {
|
||||
if (!activeClient) return;
|
||||
run(
|
||||
"ssl",
|
||||
{ client: activeClient, dryRun },
|
||||
{
|
||||
action: "renew",
|
||||
toastId: "ssl-op",
|
||||
loadingMsg: t("hostMetrics.managers.working"),
|
||||
successMsg: t("hostMetrics.managers.actionDone", { name: "renew" }),
|
||||
failMsg: t("hostMetrics.managers.actionFailed"),
|
||||
onDone: refresh,
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const revoke = (cert: CertInfo) => {
|
||||
if (cert.client !== "certbot" && cert.client !== "acme.sh") return;
|
||||
if (
|
||||
!window.confirm(
|
||||
t("hostMetrics.managers.sslRevokeConfirm", { name: cert.name }),
|
||||
)
|
||||
)
|
||||
return;
|
||||
run(
|
||||
"ssl",
|
||||
{ client: cert.client, name: cert.name },
|
||||
{
|
||||
action: "revoke",
|
||||
toastId: "ssl-op",
|
||||
loadingMsg: t("hostMetrics.managers.working"),
|
||||
successMsg: t("hostMetrics.managers.sslRevoked"),
|
||||
failMsg: t("hostMetrics.managers.actionFailed"),
|
||||
onDone: refresh,
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const issue = async () => {
|
||||
if (hostId == null || !activeClient) return;
|
||||
const list = domains
|
||||
.split(/[\s,]+/)
|
||||
.map((d) => d.trim())
|
||||
.filter(Boolean);
|
||||
if (list.length === 0) {
|
||||
const { toast } = await import("sonner");
|
||||
toast.error(t("hostMetrics.managers.sslNeedDomain"));
|
||||
return;
|
||||
}
|
||||
setIssuing(true);
|
||||
const { toast } = await import("sonner");
|
||||
toast.loading(t("hostMetrics.managers.working"), { id: "ssl-issue" });
|
||||
try {
|
||||
const res = await managerPost<{ success: boolean; output: string }>(
|
||||
hostId,
|
||||
"ssl",
|
||||
{
|
||||
client: activeClient,
|
||||
domains: list,
|
||||
challenge,
|
||||
webroot: challenge === "http-webroot" ? webroot : undefined,
|
||||
dnsProvider: challenge === "dns" ? dnsProvider : undefined,
|
||||
},
|
||||
"issue",
|
||||
);
|
||||
toast[res.success ? "success" : "error"](
|
||||
res.success
|
||||
? t("hostMetrics.managers.sslIssued")
|
||||
: t("hostMetrics.managers.actionFailed"),
|
||||
{ id: "ssl-issue", description: res.output?.slice(-200) },
|
||||
);
|
||||
if (res.success) {
|
||||
setShowIssue(false);
|
||||
setDomains("");
|
||||
refresh();
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(extractError(e).message, { id: "ssl-issue" });
|
||||
} finally {
|
||||
setIssuing(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<ManagerCardShell
|
||||
title={t("hostMetrics.managers.ssl")}
|
||||
icon={<ShieldCheck className="size-3.5" />}
|
||||
loading={loading}
|
||||
error={error}
|
||||
onRefresh={refresh}
|
||||
empty={!loading && certs.length === 0 && !activeClient}
|
||||
emptyMessage={t("hostMetrics.managers.noAcmeClient")}
|
||||
headerExtra={
|
||||
activeClient ? (
|
||||
<>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
disabled={busy}
|
||||
onClick={() => renew(true)}
|
||||
>
|
||||
{t("hostMetrics.managers.dryRun")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="xs"
|
||||
disabled={busy}
|
||||
onClick={() => renew(false)}
|
||||
>
|
||||
<RefreshCw className="size-3" />
|
||||
{t("hostMetrics.managers.renew")}
|
||||
</Button>
|
||||
</>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
<div className="mb-2 flex items-center justify-between text-[10px] uppercase tracking-widest text-muted-foreground">
|
||||
<div className="flex items-center gap-2">
|
||||
<span>{t("hostMetrics.managers.clients")}:</span>
|
||||
<span className={clients?.certbot ? "text-accent-brand" : ""}>
|
||||
certbot
|
||||
</span>
|
||||
<span className={clients?.acmeSh ? "text-accent-brand" : ""}>
|
||||
acme.sh
|
||||
</span>
|
||||
</div>
|
||||
{activeClient && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
onClick={() => setShowIssue((v) => !v)}
|
||||
>
|
||||
{showIssue ? <X className="size-3" /> : <Plus className="size-3" />}
|
||||
{t("hostMetrics.managers.sslIssueCert")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{showIssue && activeClient && (
|
||||
<div className="mb-3 flex flex-col gap-2 border border-dashed border-border p-2">
|
||||
<input
|
||||
value={domains}
|
||||
onChange={(e) => setDomains(e.target.value)}
|
||||
placeholder={t("hostMetrics.managers.sslDomainsPlaceholder")}
|
||||
className="h-7 w-full border border-border bg-background px-2 text-xs outline-none focus:ring-1 focus:ring-ring"
|
||||
/>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Select2
|
||||
value={challenge}
|
||||
onChange={(e) => setChallenge(e.target.value as Challenge)}
|
||||
className="h-7 flex-1 border border-border bg-background px-1 text-xs"
|
||||
>
|
||||
<option value="http-standalone">
|
||||
{t("hostMetrics.managers.sslHttpStandalone")}
|
||||
</option>
|
||||
<option value="http-webroot">
|
||||
{t("hostMetrics.managers.sslHttpWebroot")}
|
||||
</option>
|
||||
<option value="dns">{t("hostMetrics.managers.sslDns")}</option>
|
||||
</Select2>
|
||||
</div>
|
||||
{challenge === "http-webroot" && (
|
||||
<input
|
||||
value={webroot}
|
||||
onChange={(e) => setWebroot(e.target.value)}
|
||||
placeholder="/var/www/html"
|
||||
className="h-7 w-full border border-border bg-background px-2 font-mono text-xs outline-none focus:ring-1 focus:ring-ring"
|
||||
/>
|
||||
)}
|
||||
{challenge === "dns" && (
|
||||
<input
|
||||
value={dnsProvider}
|
||||
onChange={(e) => setDnsProvider(e.target.value)}
|
||||
placeholder={t("hostMetrics.managers.sslDnsProvider")}
|
||||
className="h-7 w-full border border-border bg-background px-2 text-xs outline-none focus:ring-1 focus:ring-ring"
|
||||
/>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={issuing}
|
||||
onClick={issue}
|
||||
className="self-start"
|
||||
>
|
||||
{t("hostMetrics.managers.sslIssueCert")}
|
||||
</Button>
|
||||
<span className="text-[10px] text-muted-foreground/70">
|
||||
{t("hostMetrics.managers.sslIssueHint")}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-col divide-y divide-border">
|
||||
{certs.map((c) => (
|
||||
<div
|
||||
key={`${c.client}-${c.name}`}
|
||||
className="flex items-center justify-between gap-2 py-1.5 text-xs"
|
||||
>
|
||||
<span
|
||||
className="truncate font-semibold"
|
||||
title={c.domains.join(", ")}
|
||||
>
|
||||
{c.name}
|
||||
</span>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<span className="font-mono text-[11px]">
|
||||
<ExpiryBadge expiry={c.expiry} />
|
||||
</span>
|
||||
{(c.client === "certbot" || c.client === "acme.sh") && (
|
||||
<button
|
||||
onClick={() => revoke(c)}
|
||||
disabled={busy}
|
||||
title={t("hostMetrics.managers.sslRevoke")}
|
||||
className="text-muted-foreground transition-colors hover:text-destructive disabled:opacity-40"
|
||||
>
|
||||
<Trash2 className="size-3.5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ManagerCardShell>
|
||||
);
|
||||
}
|
||||
@@ -1,171 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import { Power } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useManagerData, useManagerAction } from "./useManagerData";
|
||||
import { ManagerCardShell } from "./ManagerCardShell";
|
||||
import { ManagerSearch } from "./ManagerToolbar";
|
||||
|
||||
interface TailscalePeer {
|
||||
hostname: string;
|
||||
tailscaleIPs: string[];
|
||||
online: boolean;
|
||||
isExitNode: boolean;
|
||||
}
|
||||
|
||||
interface TailscaleData {
|
||||
installed: boolean;
|
||||
running: boolean;
|
||||
tailscaleIPs: string[];
|
||||
hostname: string | null;
|
||||
peers: TailscalePeer[];
|
||||
exitNodeInUse: boolean;
|
||||
}
|
||||
|
||||
export function TailscaleManagerCard({ hostId }: { hostId: number | null }) {
|
||||
const { t } = useTranslation();
|
||||
const { data, loading, error, refresh } = useManagerData<TailscaleData>(
|
||||
hostId,
|
||||
"tailscale",
|
||||
);
|
||||
const { busy, run } = useManagerAction(hostId);
|
||||
const [query, setQuery] = useState("");
|
||||
|
||||
const handleToggle = async () => {
|
||||
if (!data) return;
|
||||
const action = data.running ? "down" : "up";
|
||||
await run(
|
||||
"tailscale",
|
||||
{ action },
|
||||
{
|
||||
action: "action",
|
||||
loadingMsg: data.running
|
||||
? t("hostMetrics.managers.tsDisabling")
|
||||
: t("hostMetrics.managers.tsEnabling"),
|
||||
successMsg: data.running
|
||||
? t("hostMetrics.managers.tsDisabled")
|
||||
: t("hostMetrics.managers.tsEnabled"),
|
||||
onDone: refresh,
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const filteredPeers = (data?.peers ?? []).filter(
|
||||
(p) =>
|
||||
!query ||
|
||||
p.hostname.toLowerCase().includes(query.toLowerCase()) ||
|
||||
p.tailscaleIPs.some((ip) => ip.includes(query)),
|
||||
);
|
||||
|
||||
const isNotInstalled = data && !data.installed;
|
||||
|
||||
return (
|
||||
<ManagerCardShell
|
||||
title={t("hostMetrics.managers.tailscale")}
|
||||
icon={<Power className="size-3.5" />}
|
||||
loading={loading}
|
||||
error={error}
|
||||
onRefresh={refresh}
|
||||
empty={!!isNotInstalled}
|
||||
emptyMessage={t("hostMetrics.managers.tsNotInstalled")}
|
||||
>
|
||||
{data && (
|
||||
<div className="flex flex-col">
|
||||
{/* Status + toggle row */}
|
||||
<div className="flex items-center justify-between border-b border-border/50 py-1.5">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<span
|
||||
className={`size-1.5 shrink-0 rounded-full ${data.running ? "bg-accent-brand" : "bg-muted-foreground/40"}`}
|
||||
/>
|
||||
<div className="flex min-w-0 flex-col">
|
||||
<span className="text-xs font-semibold">
|
||||
{data.running
|
||||
? t("hostMetrics.managers.tsRunning")
|
||||
: t("hostMetrics.managers.tsStopped")}
|
||||
</span>
|
||||
{data.hostname && (
|
||||
<span className="truncate font-mono text-[10px] text-muted-foreground">
|
||||
{data.hostname}
|
||||
</span>
|
||||
)}
|
||||
{data.tailscaleIPs.map((ip) => (
|
||||
<span
|
||||
key={ip}
|
||||
className="truncate font-mono text-[10px] text-muted-foreground/60"
|
||||
>
|
||||
{ip}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center">
|
||||
<button
|
||||
onClick={handleToggle}
|
||||
disabled={busy || !data.installed}
|
||||
title={
|
||||
data.running
|
||||
? t("hostMetrics.managers.tsDisable")
|
||||
: t("hostMetrics.managers.tsEnable")
|
||||
}
|
||||
className={`flex size-6 items-center justify-center transition-colors disabled:opacity-40 ${
|
||||
data.running
|
||||
? "text-accent-brand hover:bg-muted hover:text-destructive"
|
||||
: "text-muted-foreground hover:bg-muted hover:text-accent-brand"
|
||||
}`}
|
||||
>
|
||||
<Power className="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Exit node badge */}
|
||||
{data.exitNodeInUse && (
|
||||
<div className="border-b border-border/50 px-0 py-1.5">
|
||||
<span className="text-[10px] text-blue-500">
|
||||
{t("hostMetrics.managers.tsExitNodeActive")}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Peers */}
|
||||
{(data.peers?.length ?? 0) > 5 && (
|
||||
<ManagerSearch
|
||||
value={query}
|
||||
onChange={setQuery}
|
||||
count={filteredPeers.length}
|
||||
/>
|
||||
)}
|
||||
{filteredPeers.map((peer) => (
|
||||
<div
|
||||
key={peer.hostname}
|
||||
className="flex items-center justify-between gap-2 border-b border-border/50 py-1.5 last:border-0"
|
||||
>
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<span
|
||||
className={`size-1.5 shrink-0 rounded-full ${peer.online ? "bg-accent-brand" : "bg-muted-foreground/40"}`}
|
||||
/>
|
||||
<div className="flex min-w-0 flex-col">
|
||||
<span className="truncate text-xs font-semibold">
|
||||
{peer.hostname}
|
||||
</span>
|
||||
{peer.tailscaleIPs.map((ip) => (
|
||||
<span
|
||||
key={ip}
|
||||
className="truncate font-mono text-[10px] text-muted-foreground"
|
||||
>
|
||||
{ip}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{peer.isExitNode && (
|
||||
<span className="shrink-0 text-[10px] text-blue-500">
|
||||
{t("hostMetrics.managers.tsExitNode")}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</ManagerCardShell>
|
||||
);
|
||||
}
|
||||
@@ -1,145 +0,0 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { Users, Plus, Trash2, ShieldCheck, Shield } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/button";
|
||||
import { managerPost } from "@/main-axios";
|
||||
import { useManagerData, extractError } from "./useManagerData";
|
||||
import { ManagerCardShell } from "./ManagerCardShell";
|
||||
import { ManagerSearch } from "./ManagerToolbar";
|
||||
|
||||
interface SystemUser {
|
||||
name: string;
|
||||
uid: number;
|
||||
shell: string;
|
||||
}
|
||||
interface UsersData {
|
||||
users: SystemUser[];
|
||||
sudoers: string[];
|
||||
}
|
||||
|
||||
export function UserManagerCard({ hostId }: { hostId: number | null }) {
|
||||
const { t } = useTranslation();
|
||||
const { data, loading, error, refresh } = useManagerData<UsersData>(
|
||||
hostId,
|
||||
"users",
|
||||
);
|
||||
const [newUser, setNewUser] = useState("");
|
||||
const [filter, setFilter] = useState("");
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const sudoers = new Set(data?.sudoers ?? []);
|
||||
|
||||
const users = useMemo(
|
||||
() =>
|
||||
(data?.users ?? []).filter(
|
||||
(u) => !filter || u.name.toLowerCase().includes(filter.toLowerCase()),
|
||||
),
|
||||
[data?.users, filter],
|
||||
);
|
||||
|
||||
const action = async (act: string, username: string, group?: string) => {
|
||||
if (hostId == null) return;
|
||||
setBusy(username);
|
||||
try {
|
||||
const res = await managerPost<{ success: boolean; output: string }>(
|
||||
hostId,
|
||||
"users",
|
||||
{ action: act, username, group },
|
||||
"action",
|
||||
);
|
||||
if (res.success) {
|
||||
toast.success(t("hostMetrics.managers.actionDone", { name: username }));
|
||||
if (act === "create") setNewUser("");
|
||||
refresh();
|
||||
} else {
|
||||
toast.error(res.output || t("hostMetrics.managers.actionFailed"));
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(extractError(e).message);
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<ManagerCardShell
|
||||
title={t("hostMetrics.managers.users")}
|
||||
icon={<Users className="size-3.5" />}
|
||||
loading={loading}
|
||||
error={error}
|
||||
onRefresh={refresh}
|
||||
>
|
||||
<div className="mb-2 flex items-center gap-1.5">
|
||||
<input
|
||||
value={newUser}
|
||||
onChange={(e) => setNewUser(e.target.value)}
|
||||
placeholder={t("hostMetrics.managers.newUsername")}
|
||||
className="h-7 flex-1 border border-border bg-background px-2 text-xs outline-none focus:ring-1 focus:ring-ring"
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="xs"
|
||||
disabled={!newUser || busy === newUser}
|
||||
onClick={() => action("create", newUser)}
|
||||
>
|
||||
<Plus className="size-3" />
|
||||
{t("hostMetrics.managers.addUser")}
|
||||
</Button>
|
||||
</div>
|
||||
<ManagerSearch value={filter} onChange={setFilter} count={users.length} />
|
||||
<div className="flex flex-col">
|
||||
{users.map((u) => {
|
||||
const isSudoer = sudoers.has(u.name);
|
||||
return (
|
||||
<div
|
||||
key={u.name}
|
||||
className="flex items-center justify-between gap-2 border-b border-border/50 py-1.5 last:border-0"
|
||||
>
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<span className="truncate text-xs font-semibold">{u.name}</span>
|
||||
{isSudoer && (
|
||||
<ShieldCheck className="size-3 shrink-0 text-accent-brand" />
|
||||
)}
|
||||
<span className="truncate font-mono text-[10px] text-muted-foreground">
|
||||
{u.uid}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1">
|
||||
<button
|
||||
onClick={() =>
|
||||
action(
|
||||
isSudoer ? "removeFromGroup" : "addToGroup",
|
||||
u.name,
|
||||
"sudo",
|
||||
)
|
||||
}
|
||||
disabled={busy === u.name}
|
||||
title={
|
||||
isSudoer
|
||||
? t("hostMetrics.managers.revokeSudo")
|
||||
: t("hostMetrics.managers.grantSudo")
|
||||
}
|
||||
className={`disabled:opacity-40 ${
|
||||
isSudoer
|
||||
? "text-accent-brand hover:text-muted-foreground"
|
||||
: "text-muted-foreground hover:text-accent-brand"
|
||||
}`}
|
||||
>
|
||||
<Shield className="size-3.5" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => action("delete", u.name)}
|
||||
disabled={busy === u.name}
|
||||
title={t("hostMetrics.managers.deleteUser")}
|
||||
className="text-muted-foreground hover:text-destructive disabled:opacity-40"
|
||||
>
|
||||
<Trash2 className="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</ManagerCardShell>
|
||||
);
|
||||
}
|
||||
@@ -1,209 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import {
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
Network,
|
||||
ArrowUp,
|
||||
ArrowDown,
|
||||
} from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useManagerData, useManagerAction } from "./useManagerData";
|
||||
import { ManagerCardShell } from "./ManagerCardShell";
|
||||
|
||||
interface WireGuardPeer {
|
||||
publicKey: string;
|
||||
endpoint: string | null;
|
||||
allowedIPs: string[];
|
||||
latestHandshake: number | null;
|
||||
rxBytes: number;
|
||||
txBytes: number;
|
||||
}
|
||||
|
||||
interface WireGuardInterface {
|
||||
name: string;
|
||||
publicKey: string | null;
|
||||
listenPort: number | null;
|
||||
up: boolean;
|
||||
peers: WireGuardPeer[];
|
||||
}
|
||||
|
||||
interface WireGuardData {
|
||||
installed: boolean;
|
||||
interfaces: WireGuardInterface[];
|
||||
}
|
||||
|
||||
function fmtBytes(n: number): string {
|
||||
if (n >= 1024 * 1024 * 1024)
|
||||
return `${(n / 1024 / 1024 / 1024).toFixed(1)}GB`;
|
||||
if (n >= 1024 * 1024) return `${(n / 1024 / 1024).toFixed(1)}MB`;
|
||||
if (n >= 1024) return `${(n / 1024).toFixed(1)}KB`;
|
||||
return `${n}B`;
|
||||
}
|
||||
|
||||
function fmtHandshake(ts: number | null): string {
|
||||
if (!ts) return "";
|
||||
const diff = Math.floor(Date.now() / 1000) - ts;
|
||||
if (diff < 60) return `${diff}s ago`;
|
||||
if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
|
||||
if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
|
||||
return `${Math.floor(diff / 86400)}d ago`;
|
||||
}
|
||||
|
||||
function truncKey(key: string): string {
|
||||
return key.length > 12 ? `${key.slice(0, 12)}...` : key;
|
||||
}
|
||||
|
||||
export function WireGuardManagerCard({ hostId }: { hostId: number | null }) {
|
||||
const { t } = useTranslation();
|
||||
const { data, loading, error, refresh } = useManagerData<WireGuardData>(
|
||||
hostId,
|
||||
"wireguard",
|
||||
);
|
||||
const { busy, run } = useManagerAction(hostId);
|
||||
const [expanded, setExpanded] = useState<Set<string>>(new Set());
|
||||
|
||||
const toggleExpand = (name: string) => {
|
||||
setExpanded((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(name)) next.delete(name);
|
||||
else next.add(name);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const handleAction = async (iface: WireGuardInterface) => {
|
||||
const action = iface.up ? "down" : "up";
|
||||
await run(
|
||||
"wireguard",
|
||||
{ interface: iface.name, action },
|
||||
{
|
||||
action: "action",
|
||||
loadingMsg:
|
||||
action === "up"
|
||||
? t("hostMetrics.managers.wgBringingUp", { name: iface.name })
|
||||
: t("hostMetrics.managers.wgBringingDown", { name: iface.name }),
|
||||
successMsg:
|
||||
action === "up"
|
||||
? t("hostMetrics.managers.wgInterfaceUpDone", { name: iface.name })
|
||||
: t("hostMetrics.managers.wgInterfaceDownDone", {
|
||||
name: iface.name,
|
||||
}),
|
||||
onDone: refresh,
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const isNotInstalled = data && !data.installed;
|
||||
const isEmpty = data?.installed && data.interfaces.length === 0;
|
||||
|
||||
return (
|
||||
<ManagerCardShell
|
||||
title={t("hostMetrics.managers.wireguard")}
|
||||
icon={<Network className="size-3.5" />}
|
||||
loading={loading}
|
||||
error={error}
|
||||
onRefresh={refresh}
|
||||
empty={isNotInstalled || isEmpty}
|
||||
emptyMessage={
|
||||
isNotInstalled
|
||||
? t("hostMetrics.managers.wgNotInstalled")
|
||||
: t("hostMetrics.managers.wgNoInterfaces")
|
||||
}
|
||||
>
|
||||
<div className="flex flex-col">
|
||||
{data?.interfaces.map((iface) => (
|
||||
<div
|
||||
key={iface.name}
|
||||
className="border-b border-border/50 last:border-0"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-2 py-1.5">
|
||||
<button
|
||||
className="flex min-w-0 flex-1 items-center gap-2 text-left"
|
||||
onClick={() => toggleExpand(iface.name)}
|
||||
>
|
||||
{expanded.has(iface.name) ? (
|
||||
<ChevronDown className="size-3 shrink-0 text-muted-foreground" />
|
||||
) : (
|
||||
<ChevronRight className="size-3 shrink-0 text-muted-foreground" />
|
||||
)}
|
||||
<span
|
||||
className={`size-1.5 shrink-0 rounded-full ${iface.up ? "bg-accent-brand" : "bg-muted-foreground/40"}`}
|
||||
/>
|
||||
<div className="flex min-w-0 flex-col">
|
||||
<span className="text-xs font-semibold font-mono">
|
||||
{iface.name}
|
||||
</span>
|
||||
<span className="text-[10px] text-muted-foreground">
|
||||
{iface.up ? "up" : "down"}
|
||||
{iface.listenPort ? ` · :${iface.listenPort}` : ""}
|
||||
{iface.peers.length > 0 ? ` · ${iface.peers.length}p` : ""}
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleAction(iface)}
|
||||
disabled={busy}
|
||||
title={
|
||||
iface.up
|
||||
? t("hostMetrics.managers.wgInterfaceDown")
|
||||
: t("hostMetrics.managers.wgInterfaceUp")
|
||||
}
|
||||
className="flex size-6 shrink-0 items-center justify-center text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40"
|
||||
>
|
||||
{iface.up ? (
|
||||
<ArrowDown className="size-3" />
|
||||
) : (
|
||||
<ArrowUp className="size-3" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{expanded.has(iface.name) && (
|
||||
<div className="mb-1 ml-5 flex flex-col border-l border-border/50">
|
||||
{iface.peers.length === 0 ? (
|
||||
<span className="px-3 py-1 text-[10px] text-muted-foreground/50">
|
||||
No peers
|
||||
</span>
|
||||
) : (
|
||||
iface.peers.map((peer) => (
|
||||
<div
|
||||
key={peer.publicKey}
|
||||
className="flex flex-col gap-0.5 border-b border-border/30 px-3 py-1.5 last:border-0"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="font-mono text-[10px] text-muted-foreground">
|
||||
{truncKey(peer.publicKey)}
|
||||
</span>
|
||||
{peer.endpoint && (
|
||||
<span className="font-mono text-[10px] text-muted-foreground/60">
|
||||
{peer.endpoint}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{peer.allowedIPs.length > 0 && (
|
||||
<span className="text-[10px] text-muted-foreground/70">
|
||||
{peer.allowedIPs.join(", ")}
|
||||
</span>
|
||||
)}
|
||||
<div className="flex items-center gap-3 text-[10px] text-muted-foreground/50">
|
||||
<span>
|
||||
{t("hostMetrics.managers.wgLastHandshake")}:{" "}
|
||||
{peer.latestHandshake
|
||||
? fmtHandshake(peer.latestHandshake)
|
||||
: t("hostMetrics.managers.wgHandshakeNever")}
|
||||
</span>
|
||||
<span>
|
||||
{fmtBytes(peer.rxBytes)} / {fmtBytes(peer.txBytes)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ManagerCardShell>
|
||||
);
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { managerGet, managerPost } from "@/main-axios";
|
||||
|
||||
interface ManagerError {
|
||||
message: string;
|
||||
code?: string;
|
||||
}
|
||||
|
||||
function extractError(err: unknown): ManagerError {
|
||||
const e = err as {
|
||||
response?: { data?: { error?: string; code?: string } };
|
||||
message?: string;
|
||||
};
|
||||
return {
|
||||
message: e?.response?.data?.error || e?.message || "Request failed",
|
||||
code: e?.response?.data?.code,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a manager read resource on mount + manual refresh, with loading/error
|
||||
* state. `hostId` null disables fetching.
|
||||
*/
|
||||
export function useManagerData<T>(
|
||||
hostId: number | null,
|
||||
resource: string,
|
||||
params?: Record<string, string | number>,
|
||||
) {
|
||||
const [data, setData] = useState<T | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<ManagerError | null>(null);
|
||||
|
||||
const paramsKey = params ? JSON.stringify(params) : "";
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
if (hostId == null) return;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await managerGet<T>(hostId, resource, params);
|
||||
setData(res);
|
||||
} catch (err) {
|
||||
setError(extractError(err));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [hostId, resource, paramsKey]);
|
||||
|
||||
useEffect(() => {
|
||||
refresh();
|
||||
}, [refresh]);
|
||||
|
||||
return { data, loading, error, refresh, setData };
|
||||
}
|
||||
|
||||
interface ActionResult {
|
||||
success: boolean;
|
||||
output?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a manager POST action with consistent toast feedback (loading -> success
|
||||
* /error) and a busy flag. On success the optional `onDone` callback runs (e.g.
|
||||
* to refresh the card). Returns the result so callers can branch further.
|
||||
*/
|
||||
export function useManagerAction(hostId: number | null) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const run = useCallback(
|
||||
async <T extends ActionResult>(
|
||||
resource: string,
|
||||
body: unknown,
|
||||
opts: {
|
||||
action?: string;
|
||||
toastId?: string;
|
||||
loadingMsg?: string;
|
||||
successMsg?: string;
|
||||
failMsg?: string;
|
||||
onDone?: () => void;
|
||||
} = {},
|
||||
): Promise<T | null> => {
|
||||
if (hostId == null) return null;
|
||||
const id = opts.toastId ?? `${resource}-action`;
|
||||
setBusy(true);
|
||||
if (opts.loadingMsg) toast.loading(opts.loadingMsg, { id });
|
||||
try {
|
||||
const res = await managerPost<T>(hostId, resource, body, opts.action);
|
||||
if (res.success) {
|
||||
if (opts.successMsg)
|
||||
toast.success(opts.successMsg, {
|
||||
id,
|
||||
description: res.output?.slice(-200),
|
||||
});
|
||||
else toast.dismiss(id);
|
||||
opts.onDone?.();
|
||||
} else {
|
||||
toast.error(opts.failMsg ?? res.output ?? "Action failed", {
|
||||
id,
|
||||
description: res.output?.slice(-200),
|
||||
});
|
||||
}
|
||||
return res;
|
||||
} catch (err) {
|
||||
toast.error(extractError(err).message, { id });
|
||||
return null;
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
},
|
||||
[hostId],
|
||||
);
|
||||
|
||||
return { busy, run };
|
||||
}
|
||||
|
||||
export { extractError };
|
||||
export type { ManagerError };
|
||||
@@ -1,91 +0,0 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { getHostMetricsLayout, saveHostMetricsLayout } from "@/main-axios";
|
||||
import type { HostMetricsLayout } from "@/types/host-metrics";
|
||||
|
||||
const SAVE_DEBOUNCE_MS = 800;
|
||||
|
||||
function lsKey(hostId: number) {
|
||||
return `hostMetricsLayout:${hostId}`;
|
||||
}
|
||||
|
||||
function readCache(hostId: number): HostMetricsLayout | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(lsKey(hostId));
|
||||
if (!raw) return null;
|
||||
const parsed = JSON.parse(raw);
|
||||
if (parsed && Array.isArray(parsed.slots))
|
||||
return parsed as HostMetricsLayout;
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function writeCache(hostId: number, layout: HostMetricsLayout) {
|
||||
try {
|
||||
localStorage.setItem(lsKey(hostId), JSON.stringify(layout));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-host Host Metrics layout, cached in localStorage for instant paint and
|
||||
* synced to the backend (so it follows the user across devices). Saves are
|
||||
* debounced. Returns null layout until the first load resolves.
|
||||
*/
|
||||
export function useHostMetricsPreferences(hostId: number | null) {
|
||||
const [layout, setLayout] = useState<HostMetricsLayout | null>(() =>
|
||||
hostId != null ? readCache(hostId) : null,
|
||||
);
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (hostId == null) return;
|
||||
let cancelled = false;
|
||||
setLoaded(false);
|
||||
const cached = readCache(hostId);
|
||||
if (cached) setLayout(cached);
|
||||
|
||||
getHostMetricsLayout(hostId)
|
||||
.then((remote) => {
|
||||
if (cancelled || !remote) return;
|
||||
setLayout(remote);
|
||||
writeCache(hostId, remote);
|
||||
})
|
||||
.catch(() => {
|
||||
/* keep cache/default */
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoaded(true);
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [hostId]);
|
||||
|
||||
const save = useCallback(
|
||||
(next: HostMetricsLayout) => {
|
||||
if (hostId == null) return;
|
||||
setLayout(next);
|
||||
writeCache(hostId, next);
|
||||
if (saveTimer.current) clearTimeout(saveTimer.current);
|
||||
saveTimer.current = setTimeout(() => {
|
||||
saveHostMetricsLayout(hostId, next).catch(() => {
|
||||
/* best-effort; cache already holds it */
|
||||
});
|
||||
}, SAVE_DEBOUNCE_MS);
|
||||
},
|
||||
[hostId],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (saveTimer.current) clearTimeout(saveTimer.current);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return { layout, setLayout: save, loaded };
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
import type { ServerMetrics } from "@/main-axios";
|
||||
|
||||
/**
|
||||
* Coarse fingerprint of a metrics poll. Adaptive polling backs off while it
|
||||
* stays the same, so it must move whenever something a card shows changes.
|
||||
*/
|
||||
export function metricsChangeKey(data: ServerMetrics): string {
|
||||
const bucket = (value: number | null | undefined) =>
|
||||
value == null ? null : Math.round(value / 5) * 5;
|
||||
return JSON.stringify({
|
||||
cpu: bucket(data.cpu.percent),
|
||||
memory: bucket(data.memory.percent),
|
||||
disk: bucket(data.disk.percent),
|
||||
running: data.processes?.running ?? null,
|
||||
ports: data.ports?.ports?.length ?? 0,
|
||||
firewall: data.firewall?.status ?? null,
|
||||
gpus:
|
||||
data.gpu?.gpus?.map((gpu) => [
|
||||
bucket(gpu.utilizationPercent),
|
||||
bucket(gpu.memoryPercent),
|
||||
]) ?? [],
|
||||
gpuProcesses: data.gpu?.processes?.length ?? 0,
|
||||
});
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import type { TemperatureSensor } from "@/types/stats-widgets";
|
||||
|
||||
export function selectTemperatureSensor(
|
||||
sensors: TemperatureSensor[],
|
||||
preferredLabel: string,
|
||||
) {
|
||||
return sensors.find((sensor) => sensor.label === preferredLabel) ?? null;
|
||||
}
|
||||
|
||||
export function temperaturePreferenceKey(hostId: number) {
|
||||
return `termix-host-metrics:${hostId}:temperature-sensor`;
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { Network } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ProxmoxStatsSnapshot } from "@/types/proxmox";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { MetricCard } from "@/features/host-metrics/cards/MetricCard";
|
||||
import { MetricCard } from "@/components/metric-card";
|
||||
|
||||
export function ClusterHealthCard({
|
||||
snapshot,
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Network } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ProxmoxStatsSnapshot } from "@/types/proxmox";
|
||||
import { StatRow } from "@/components/charts";
|
||||
import { MetricCard } from "@/features/host-metrics/cards/MetricCard";
|
||||
import { MetricCard } from "@/components/metric-card";
|
||||
|
||||
export function NodeNetworkCard({
|
||||
snapshot,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Database } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ProxmoxStatsSnapshot } from "@/types/proxmox";
|
||||
import { MetricCard } from "@/features/host-metrics/cards/MetricCard";
|
||||
import { MetricCard } from "@/components/metric-card";
|
||||
|
||||
export function StoragePoolsCard({
|
||||
snapshot,
|
||||
|
||||
Reference in new issue
Block a user