feat(servers): auto-provision API tokens and add node metric graphs
Servers can now be connected with a login and password: the panel
authenticates once, creates its own API token on the node (privsep=0) and
uses it from then on. The token can be revoked from the Proxmox UI, cannot
be used for SSH or web login, and appears in the PVE audit log under its
own name. The password stays stored (encrypted) because ProxmoxClient needs
it for SSH fallbacks such as pvecm delnode.
- add proxmox/token_provisioning.py: token creation with free-name
selection and revoke-on-failure so a failed registration does not leave
an orphaned token whose secret was never persisted
- POST /api/servers accepts auto_create_token
- add POST /api/servers/{id}/provision-token to migrate servers that are
still on password auth
- store api_token_value as EncryptedString; it was kept in plaintext while
the password next to it was already encrypted
- drop the unused ProxmoxServerBase schema, a stale copy of the create
schema whose validator rejected the new auth mode
Node detail pages gain a Graphs tab (CPU, IO delay, memory, load average,
network, swap, root filesystem) built on the existing node rrddata
endpoint. The chart card is extracted from the instance graphs tab so both
views share it, and X axis ticks now switch to dates on multi-day ranges.
This commit is contained in:
137
frontend/src/components/shared/MetricChart.tsx
Normal file
137
frontend/src/components/shared/MetricChart.tsx
Normal file
@@ -0,0 +1,137 @@
|
||||
import { useId } from 'react';
|
||||
import {
|
||||
Area,
|
||||
AreaChart,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
Tooltip,
|
||||
ResponsiveContainer,
|
||||
} from 'recharts';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
|
||||
/** Presets shared by the instance and node graph views. */
|
||||
export const TIMEFRAME_PRESETS = [
|
||||
{ tf: 'hour', label: '1h' },
|
||||
{ tf: 'day', label: '24h' },
|
||||
{ tf: 'week', label: '7d' },
|
||||
{ tf: 'month', label: '30d' },
|
||||
];
|
||||
|
||||
/** HH:MM — the default tick format, adequate for hour/day ranges. */
|
||||
export function fmtTime(ts: number): string {
|
||||
const d = new Date(ts * 1000);
|
||||
return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
/** DD.MM — used for week/month/year ranges where HH:MM repeats itself. */
|
||||
export function fmtDate(ts: number): string {
|
||||
const d = new Date(ts * 1000);
|
||||
return `${String(d.getDate()).padStart(2, '0')}.${String(d.getMonth() + 1).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
/** Pick a tick formatter that stays readable for the given timeframe. */
|
||||
export function tickFormatterFor(timeframe: string): (ts: number) => string {
|
||||
return timeframe === 'hour' || timeframe === 'day' ? fmtTime : fmtDate;
|
||||
}
|
||||
|
||||
/** Convert a datetime-local string to unix seconds. */
|
||||
export function localToUnix(val: string): number | undefined {
|
||||
if (!val) return undefined;
|
||||
return Math.floor(new Date(val).getTime() / 1000);
|
||||
}
|
||||
|
||||
/** Convert unix seconds to a datetime-local value string. */
|
||||
export function unixToLocal(ts: number): string {
|
||||
const d = new Date(ts * 1000);
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
}
|
||||
|
||||
export interface ChartCardProps {
|
||||
title: string;
|
||||
data: Array<Record<string, unknown>>;
|
||||
dataKey: string;
|
||||
color: string;
|
||||
formatValue?: (v: number) => string;
|
||||
unit?: string;
|
||||
headerRight?: React.ReactNode;
|
||||
/** Overrides the X axis tick format (defaults to HH:MM). */
|
||||
tickFormatter?: (ts: number) => string;
|
||||
}
|
||||
|
||||
/** Single area chart card — one metric series over time. */
|
||||
export function ChartCard({
|
||||
title,
|
||||
data,
|
||||
dataKey,
|
||||
color,
|
||||
formatValue,
|
||||
unit,
|
||||
headerRight,
|
||||
tickFormatter,
|
||||
}: ChartCardProps) {
|
||||
// useId keeps the gradient unique even when two cards share a dataKey.
|
||||
const gradientId = `grad-${dataKey}-${useId().replace(/:/g, '')}`;
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<CardTitle className="text-sm font-semibold">{title}</CardTitle>
|
||||
{headerRight}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ResponsiveContainer width="100%" height={200}>
|
||||
<AreaChart data={data} margin={{ top: 5, right: 5, bottom: 0, left: 0 }}>
|
||||
<defs>
|
||||
<linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0%" stopColor={color} stopOpacity={0.3} />
|
||||
<stop offset="100%" stopColor={color} stopOpacity={0} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<CartesianGrid strokeDasharray="3 3" className="stroke-border" />
|
||||
<XAxis
|
||||
dataKey="time"
|
||||
tickFormatter={tickFormatter || fmtTime}
|
||||
className="text-2xs fill-muted-foreground"
|
||||
tick={{ fontSize: 10 }}
|
||||
/>
|
||||
<YAxis
|
||||
className="text-2xs fill-muted-foreground"
|
||||
tick={{ fontSize: 10 }}
|
||||
tickFormatter={(v) => (formatValue ? formatValue(v) : String(v))}
|
||||
width={55}
|
||||
/>
|
||||
<Tooltip
|
||||
contentStyle={{
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.65)',
|
||||
border: '1px solid rgba(255, 255, 255, 0.25)',
|
||||
borderRadius: '6px',
|
||||
fontSize: 12,
|
||||
color: '#fff',
|
||||
}}
|
||||
labelStyle={{ color: '#fff' }}
|
||||
itemStyle={{ color: '#fff' }}
|
||||
formatter={(val: unknown) => [
|
||||
val != null && typeof val === 'number' && formatValue
|
||||
? formatValue(val)
|
||||
: `${val ?? ''}${unit || ''}`,
|
||||
title,
|
||||
]}
|
||||
labelFormatter={(ts) => new Date((ts as number) * 1000).toLocaleString()}
|
||||
/>
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey={dataKey}
|
||||
stroke={color}
|
||||
strokeWidth={1.5}
|
||||
fill={`url(#${gradientId})`}
|
||||
dot={false}
|
||||
/>
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,19 +1,16 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
Area,
|
||||
AreaChart,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
Tooltip,
|
||||
ResponsiveContainer,
|
||||
} from 'recharts';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { useVMMetrics } from '@/hooks/use-instances';
|
||||
import { formatBytes } from '@/lib/format';
|
||||
import {
|
||||
ChartCard,
|
||||
TIMEFRAME_PRESETS as PRESETS,
|
||||
localToUnix,
|
||||
unixToLocal,
|
||||
tickFormatterFor,
|
||||
} from '@/components/shared/MetricChart';
|
||||
|
||||
interface Props {
|
||||
serverId: number;
|
||||
@@ -22,107 +19,8 @@ interface Props {
|
||||
node: string;
|
||||
}
|
||||
|
||||
const PRESETS = [
|
||||
{ tf: 'hour', label: '1h' },
|
||||
{ tf: 'day', label: '24h' },
|
||||
{ tf: 'week', label: '7d' },
|
||||
{ tf: 'month', label: '30d' },
|
||||
];
|
||||
|
||||
const MAX_SPAN = 30 * 86400;
|
||||
|
||||
function fmtTime(ts: number): string {
|
||||
const d = new Date(ts * 1000);
|
||||
return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
// Convert a datetime-local string to unix seconds
|
||||
function localToUnix(val: string): number | undefined {
|
||||
if (!val) return undefined;
|
||||
return Math.floor(new Date(val).getTime() / 1000);
|
||||
}
|
||||
|
||||
// Convert unix seconds to datetime-local value string
|
||||
function unixToLocal(ts: number): string {
|
||||
const d = new Date(ts * 1000);
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
}
|
||||
|
||||
interface ChartCardProps {
|
||||
title: string;
|
||||
data: Array<Record<string, unknown>>;
|
||||
dataKey: string;
|
||||
color: string;
|
||||
formatValue?: (v: number) => string;
|
||||
unit?: string;
|
||||
headerRight?: React.ReactNode;
|
||||
}
|
||||
|
||||
function ChartCard({ title, data, dataKey, color, formatValue, unit, headerRight }: ChartCardProps) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<CardTitle className="text-sm font-semibold">{title}</CardTitle>
|
||||
{headerRight}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ResponsiveContainer width="100%" height={200}>
|
||||
<AreaChart data={data} margin={{ top: 5, right: 5, bottom: 0, left: 0 }}>
|
||||
<defs>
|
||||
<linearGradient id={`grad-${dataKey}`} x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0%" stopColor={color} stopOpacity={0.3} />
|
||||
<stop offset="100%" stopColor={color} stopOpacity={0} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<CartesianGrid strokeDasharray="3 3" className="stroke-border" />
|
||||
<XAxis
|
||||
dataKey="time"
|
||||
tickFormatter={fmtTime}
|
||||
className="text-2xs fill-muted-foreground"
|
||||
tick={{ fontSize: 10 }}
|
||||
/>
|
||||
<YAxis
|
||||
className="text-2xs fill-muted-foreground"
|
||||
tick={{ fontSize: 10 }}
|
||||
tickFormatter={(v) => (formatValue ? formatValue(v) : String(v))}
|
||||
width={55}
|
||||
/>
|
||||
<Tooltip
|
||||
contentStyle={{
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.65)',
|
||||
border: '1px solid rgba(255, 255, 255, 0.25)',
|
||||
borderRadius: '6px',
|
||||
fontSize: 12,
|
||||
color: '#fff',
|
||||
}}
|
||||
labelStyle={{ color: '#fff' }}
|
||||
itemStyle={{ color: '#fff' }}
|
||||
formatter={(val: unknown) => [
|
||||
val != null && typeof val === 'number' && formatValue
|
||||
? formatValue(val)
|
||||
: `${val ?? ''}${unit || ''}`,
|
||||
title,
|
||||
]}
|
||||
labelFormatter={(ts) => new Date((ts as number) * 1000).toLocaleString()}
|
||||
/>
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey={dataKey}
|
||||
stroke={color}
|
||||
strokeWidth={1.5}
|
||||
fill={`url(#grad-${dataKey})`}
|
||||
dot={false}
|
||||
/>
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export default function GraphsTab({ serverId, vmid, type, node }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const [timeframe, setTimeframe] = useState('hour');
|
||||
@@ -153,6 +51,13 @@ export default function GraphsTab({ serverId, vmid, type, node }: Props) {
|
||||
const points = (data?.data ?? []) as unknown as Array<Record<string, unknown>>;
|
||||
const nics = data?.meta?.nics ?? [];
|
||||
|
||||
// Custom ranges spanning more than a day need date ticks, not HH:MM.
|
||||
const spanSeconds =
|
||||
hasCustom && customRange.from != null && customRange.to != null
|
||||
? customRange.to - customRange.from
|
||||
: 0;
|
||||
const xTick = tickFormatterFor(hasCustom ? (spanSeconds > 86400 ? 'week' : 'day') : timeframe);
|
||||
|
||||
function resetCustom() {
|
||||
setFromLocal('');
|
||||
setToLocal('');
|
||||
@@ -233,6 +138,7 @@ export default function GraphsTab({ serverId, vmid, type, node }: Props) {
|
||||
) : (
|
||||
<div className="grid gap-4 lg:grid-cols-2">
|
||||
<ChartCard
|
||||
tickFormatter={xTick}
|
||||
title={t('graphs.cpu_usage')}
|
||||
data={points}
|
||||
dataKey="cpu"
|
||||
@@ -241,6 +147,7 @@ export default function GraphsTab({ serverId, vmid, type, node }: Props) {
|
||||
unit="%"
|
||||
/>
|
||||
<ChartCard
|
||||
tickFormatter={xTick}
|
||||
title={t('graphs.memory_usage')}
|
||||
data={points}
|
||||
dataKey="mem"
|
||||
@@ -248,6 +155,7 @@ export default function GraphsTab({ serverId, vmid, type, node }: Props) {
|
||||
formatValue={(v) => formatBytes(v)}
|
||||
/>
|
||||
<ChartCard
|
||||
tickFormatter={xTick}
|
||||
title={t('graphs.disk_write')}
|
||||
data={points}
|
||||
dataKey="diskwrite"
|
||||
@@ -255,6 +163,7 @@ export default function GraphsTab({ serverId, vmid, type, node }: Props) {
|
||||
formatValue={(v) => `${formatBytes(v)}/s`}
|
||||
/>
|
||||
<ChartCard
|
||||
tickFormatter={xTick}
|
||||
title={t('graphs.disk_read')}
|
||||
data={points}
|
||||
dataKey="diskread"
|
||||
@@ -262,6 +171,7 @@ export default function GraphsTab({ serverId, vmid, type, node }: Props) {
|
||||
formatValue={(v) => `${formatBytes(v)}/s`}
|
||||
/>
|
||||
<ChartCard
|
||||
tickFormatter={xTick}
|
||||
title={t('graphs.network_in')}
|
||||
data={points}
|
||||
dataKey="netin"
|
||||
@@ -270,6 +180,7 @@ export default function GraphsTab({ serverId, vmid, type, node }: Props) {
|
||||
headerRight={nicSelector}
|
||||
/>
|
||||
<ChartCard
|
||||
tickFormatter={xTick}
|
||||
title={t('graphs.network_out')}
|
||||
data={points}
|
||||
dataKey="netout"
|
||||
@@ -278,6 +189,7 @@ export default function GraphsTab({ serverId, vmid, type, node }: Props) {
|
||||
headerRight={nicSelector}
|
||||
/>
|
||||
<ChartCard
|
||||
tickFormatter={xTick}
|
||||
title="IOPS чтение"
|
||||
data={points}
|
||||
dataKey="iops_read"
|
||||
@@ -286,6 +198,7 @@ export default function GraphsTab({ serverId, vmid, type, node }: Props) {
|
||||
unit=" ops/s"
|
||||
/>
|
||||
<ChartCard
|
||||
tickFormatter={xTick}
|
||||
title="IOPS запись"
|
||||
data={points}
|
||||
dataKey="iops_write"
|
||||
@@ -294,6 +207,7 @@ export default function GraphsTab({ serverId, vmid, type, node }: Props) {
|
||||
unit=" ops/s"
|
||||
/>
|
||||
<ChartCard
|
||||
tickFormatter={xTick}
|
||||
title="Заполненность диска"
|
||||
data={points}
|
||||
dataKey="diskpct"
|
||||
|
||||
@@ -67,6 +67,7 @@ function NodeActionsMenu({ serverId, node }: { serverId: number; node: string })
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
import NodeGraphs from './NodeGraphs';
|
||||
import NodeNetworks from './NodeNetworks';
|
||||
import HAResources from './HAResources';
|
||||
import SDNManager from './SDNManager';
|
||||
@@ -126,6 +127,7 @@ export default function NodeDetailPage() {
|
||||
<TabsTrigger value="overview">{t('nodes.tab_overview', 'Обзор')}</TabsTrigger>
|
||||
{nodes.length > 0 && (
|
||||
<>
|
||||
<TabsTrigger value="graphs">{t('nodes.tab_graphs', 'Графики')}</TabsTrigger>
|
||||
<TabsTrigger value="network">{t('nodes.tab_network', 'Сеть')}</TabsTrigger>
|
||||
<TabsTrigger value="ha">{t('nodes.tab_ha', 'HA')}</TabsTrigger>
|
||||
<TabsTrigger value="firewall">{t('nodes.tab_firewall', 'Firewall')}</TabsTrigger>
|
||||
@@ -206,6 +208,11 @@ export default function NodeDetailPage() {
|
||||
|
||||
{nodes.length > 0 && (
|
||||
<>
|
||||
{/* Graphs: node RRD metrics */}
|
||||
<TabsContent value="graphs" className="mt-4">
|
||||
<NodeGraphs serverId={sid} nodeNames={nodes.map(n => n.node)} />
|
||||
</TabsContent>
|
||||
|
||||
{/* Network: interfaces + SDN */}
|
||||
<TabsContent value="network" className="mt-4 space-y-6">
|
||||
<NodeNetworks serverId={sid} nodeNames={nodes.map(n => n.node)} />
|
||||
|
||||
146
frontend/src/features/nodes/NodeGraphs.tsx
Normal file
146
frontend/src/features/nodes/NodeGraphs.tsx
Normal file
@@ -0,0 +1,146 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { useNodeMetrics } from '@/hooks/use-nodes';
|
||||
import { formatBytes } from '@/lib/format';
|
||||
import {
|
||||
ChartCard,
|
||||
TIMEFRAME_PRESETS,
|
||||
tickFormatterFor,
|
||||
} from '@/components/shared/MetricChart';
|
||||
|
||||
interface Props {
|
||||
serverId: number;
|
||||
nodeNames: string[];
|
||||
}
|
||||
|
||||
// PVE keeps a year of node RRD data, unlike the 30-day instance history.
|
||||
const PRESETS = [...TIMEFRAME_PRESETS, { tf: 'year', label: '1y' }];
|
||||
|
||||
export default function NodeGraphs({ serverId, nodeNames }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const [node, setNode] = useState(nodeNames[0] || '');
|
||||
const [timeframe, setTimeframe] = useState('hour');
|
||||
|
||||
// Nodes arrive asynchronously; adopt the first one once it shows up, and
|
||||
// fall back if the selected node disappears from the cluster.
|
||||
useEffect(() => {
|
||||
if (nodeNames.length && !nodeNames.includes(node)) setNode(nodeNames[0]);
|
||||
}, [nodeNames, node]);
|
||||
|
||||
const { data: points = [], isLoading } = useNodeMetrics(serverId, node, timeframe);
|
||||
const xTick = tickFormatterFor(timeframe);
|
||||
const rows = points as unknown as Array<Record<string, unknown>>;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{nodeNames.length > 1 && (
|
||||
<select
|
||||
value={node}
|
||||
onChange={(e) => setNode(e.target.value)}
|
||||
className="rounded border border-border bg-background px-2 py-1 text-sm text-foreground focus:outline-none"
|
||||
>
|
||||
{nodeNames.map((n) => (
|
||||
<option key={n} value={n}>
|
||||
{n}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
<div className="flex gap-1">
|
||||
{PRESETS.map((p) => (
|
||||
<Button
|
||||
key={p.tf}
|
||||
variant={timeframe === p.tf ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => setTimeframe(p.tf)}
|
||||
>
|
||||
{p.label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-20">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : rows.length === 0 ? (
|
||||
<div className="flex items-center justify-center py-20 text-sm text-muted-foreground">
|
||||
{t('common.no_data')}
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-4 lg:grid-cols-2">
|
||||
<ChartCard
|
||||
tickFormatter={xTick}
|
||||
title={t('graphs.cpu_usage')}
|
||||
data={rows}
|
||||
dataKey="cpu"
|
||||
color="hsl(217, 91%, 60%)"
|
||||
formatValue={(v) => `${v.toFixed(1)}%`}
|
||||
unit="%"
|
||||
/>
|
||||
<ChartCard
|
||||
tickFormatter={xTick}
|
||||
title={t('graphs.io_delay', 'IO delay')}
|
||||
data={rows}
|
||||
dataKey="iowait"
|
||||
color="hsl(45, 93%, 47%)"
|
||||
formatValue={(v) => `${v.toFixed(2)}%`}
|
||||
unit="%"
|
||||
/>
|
||||
<ChartCard
|
||||
tickFormatter={xTick}
|
||||
title={t('graphs.memory_usage')}
|
||||
data={rows}
|
||||
dataKey="memused"
|
||||
color="hsl(142, 76%, 36%)"
|
||||
formatValue={(v) => formatBytes(v)}
|
||||
/>
|
||||
<ChartCard
|
||||
tickFormatter={xTick}
|
||||
title={t('graphs.load_average', 'Load average')}
|
||||
data={rows}
|
||||
dataKey="loadavg"
|
||||
color="hsl(0, 84%, 60%)"
|
||||
formatValue={(v) => v.toFixed(2)}
|
||||
/>
|
||||
<ChartCard
|
||||
tickFormatter={xTick}
|
||||
title={t('graphs.network_in')}
|
||||
data={rows}
|
||||
dataKey="netin"
|
||||
color="hsl(262, 83%, 58%)"
|
||||
formatValue={(v) => `${formatBytes(v)}/s`}
|
||||
/>
|
||||
<ChartCard
|
||||
tickFormatter={xTick}
|
||||
title={t('graphs.network_out')}
|
||||
data={rows}
|
||||
dataKey="netout"
|
||||
color="hsl(25, 95%, 53%)"
|
||||
formatValue={(v) => `${formatBytes(v)}/s`}
|
||||
/>
|
||||
<ChartCard
|
||||
tickFormatter={xTick}
|
||||
title={t('graphs.swap_usage', 'Swap')}
|
||||
data={rows}
|
||||
dataKey="swapused"
|
||||
color="hsl(300, 60%, 50%)"
|
||||
formatValue={(v) => formatBytes(v)}
|
||||
/>
|
||||
<ChartCard
|
||||
tickFormatter={xTick}
|
||||
title={t('graphs.root_fs', 'Root filesystem')}
|
||||
data={rows}
|
||||
dataKey="rootused"
|
||||
color="hsl(180, 70%, 40%)"
|
||||
formatValue={(v) => formatBytes(v)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Link } from 'react-router';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Server, Monitor, Container, Plus, Pencil, Trash2, Wifi, Loader2, Clock, Layers, LayoutGrid, ExternalLink } from 'lucide-react';
|
||||
import { Server, Monitor, Container, Plus, Pencil, Trash2, Wifi, Loader2, Clock, Layers, LayoutGrid, ExternalLink, KeyRound } from 'lucide-react';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -9,7 +9,7 @@ import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogClose } from '@/components/ui/dialog';
|
||||
import { useServers, useCreateServer, useUpdateServer, useDeleteServer, useTestServerCredentials, useNodes } from '@/hooks/use-nodes';
|
||||
import { useServers, useCreateServer, useUpdateServer, useDeleteServer, useTestServerCredentials, useProvisionServerToken, useNodes } from '@/hooks/use-nodes';
|
||||
import { useVirtualMachines } from '@/hooks/use-instances';
|
||||
import type { ProxmoxServer, ProxmoxServerCreate } from '@/types';
|
||||
import { formatUptime } from '@/lib/format';
|
||||
@@ -83,15 +83,23 @@ function WorkspaceChips({ server }: { server: ProxmoxServer }) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* How the panel authenticates to Proxmox:
|
||||
* - auto — log in with the password once, panel creates its own API token
|
||||
* - token — an API token created by hand in the PVE UI
|
||||
* - password — password auth on every call (legacy)
|
||||
*/
|
||||
type AuthMode = 'auto' | 'token' | 'password';
|
||||
|
||||
interface ServerFormData {
|
||||
name: string;
|
||||
hostname: string;
|
||||
ip_address: string;
|
||||
port: string;
|
||||
api_user: string;
|
||||
auth_mode: AuthMode;
|
||||
api_token_name: string;
|
||||
api_token_value: string;
|
||||
use_password: boolean;
|
||||
password: string;
|
||||
verify_ssl: boolean;
|
||||
description: string;
|
||||
@@ -103,9 +111,9 @@ const emptyForm: ServerFormData = {
|
||||
ip_address: '',
|
||||
port: '8006',
|
||||
api_user: 'root@pam',
|
||||
auth_mode: 'auto',
|
||||
api_token_name: '',
|
||||
api_token_value: '',
|
||||
use_password: false,
|
||||
password: '',
|
||||
verify_ssl: false,
|
||||
description: '',
|
||||
@@ -154,7 +162,11 @@ function ServerFormDialog({
|
||||
// "не менять" — отправлять его нельзя, иначе бэкенд затрёт реальный
|
||||
// токен/пароль пустой строкой и сервер уйдёт в offline.
|
||||
const isEdit = serverId != null;
|
||||
if (form.use_password) {
|
||||
if (form.auth_mode === 'auto') {
|
||||
// Пароль уходит на бэкенд, тот подключается им один раз и создаёт токен.
|
||||
payload.auto_create_token = true;
|
||||
payload.password = form.password;
|
||||
} else if (form.auth_mode === 'password') {
|
||||
if (!isEdit || form.password) {
|
||||
payload.use_password = true;
|
||||
payload.password = form.password;
|
||||
@@ -170,8 +182,13 @@ function ServerFormDialog({
|
||||
onSubmit(buildPayload());
|
||||
};
|
||||
|
||||
const credentialsMissing =
|
||||
form.auth_mode === 'token'
|
||||
? !form.api_token_name || !form.api_token_value
|
||||
: !form.password;
|
||||
|
||||
const handleTest = () => {
|
||||
if (form.use_password ? !form.password : (!form.api_token_name || !form.api_token_value)) {
|
||||
if (credentialsMissing) {
|
||||
toast.error(t('nodes.connection_failed'));
|
||||
return;
|
||||
}
|
||||
@@ -208,21 +225,22 @@ function ServerFormDialog({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="use_password"
|
||||
checked={form.use_password}
|
||||
onChange={e => set('use_password', e.target.checked)}
|
||||
/>
|
||||
<Label htmlFor="use_password" className="cursor-pointer">{t('nodes.use_password')}</Label>
|
||||
<div>
|
||||
<Label>{t('nodes.auth_mode')}</Label>
|
||||
<select
|
||||
value={form.auth_mode}
|
||||
onChange={e => set('auth_mode', e.target.value as AuthMode)}
|
||||
className="mt-1 w-full rounded-md border border-border bg-background px-3 py-2 text-sm text-foreground focus:outline-none"
|
||||
>
|
||||
{/* Перевыпуск токена для существующего сервера — отдельным
|
||||
действием на карточке, а не через форму редактирования. */}
|
||||
{serverId == null && <option value="auto">{t('nodes.auth_mode_auto')}</option>}
|
||||
<option value="token">{t('nodes.auth_mode_token')}</option>
|
||||
<option value="password">{t('nodes.auth_mode_password')}</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{form.use_password ? (
|
||||
<div>
|
||||
<Label>{t('wizard.password')}</Label>
|
||||
<Input type="password" value={form.password} onChange={e => set('password', e.target.value)} className="mt-1" />
|
||||
</div>
|
||||
) : (
|
||||
{form.auth_mode === 'token' ? (
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<Label>{t('nodes.api_token_name')}</Label>
|
||||
@@ -233,6 +251,14 @@ function ServerFormDialog({
|
||||
<Input value={form.api_token_value} onChange={e => set('api_token_value', e.target.value)} className="mt-1" placeholder="xxxxxxxx-xxxx-..." />
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<Label>{t('wizard.password')}</Label>
|
||||
<Input type="password" value={form.password} onChange={e => set('password', e.target.value)} className="mt-1" />
|
||||
{form.auth_mode === 'auto' && (
|
||||
<p className="mt-1 text-xs text-muted-foreground">{t('nodes.auth_mode_auto_hint')}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -278,6 +304,7 @@ export default function NodesPage() {
|
||||
const createServer = useCreateServer();
|
||||
const updateServer = useUpdateServer();
|
||||
const deleteServer = useDeleteServer();
|
||||
const provisionToken = useProvisionServerToken();
|
||||
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
@@ -310,6 +337,14 @@ export default function NodesPage() {
|
||||
});
|
||||
};
|
||||
|
||||
const handleProvisionToken = async (id: number, name: string) => {
|
||||
if (!await confirm(t('nodes.switch_to_token_confirm', { name }), { title: t('nodes.switch_to_token') })) return;
|
||||
provisionToken.mutate(id, {
|
||||
onSuccess: (res) => toast.success(t('nodes.switch_to_token_ok', { token: res.token_name })),
|
||||
onError: (err) => toast.error(err.message),
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
@@ -353,6 +388,18 @@ export default function NodesPage() {
|
||||
>
|
||||
<ExternalLink className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
{srv.use_password && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7"
|
||||
title={t('nodes.switch_to_token')}
|
||||
disabled={provisionToken.isPending}
|
||||
onClick={() => handleProvisionToken(srv.id, srv.name)}
|
||||
>
|
||||
<KeyRound className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
@@ -365,9 +412,9 @@ export default function NodesPage() {
|
||||
ip_address: srv.ip_address,
|
||||
port: String(srv.port || 8006),
|
||||
api_user: srv.api_user || 'root@pam',
|
||||
auth_mode: srv.use_password ? 'password' : 'token',
|
||||
api_token_name: '',
|
||||
api_token_value: '',
|
||||
use_password: false,
|
||||
password: '',
|
||||
verify_ssl: srv.verify_ssl || false,
|
||||
description: srv.description || '',
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useQuery, useMutation, useQueryClient, keepPreviousData } from '@tanstack/react-query';
|
||||
import { apiClient } from '@/lib/api-client';
|
||||
import type { ProxmoxServer, ProxmoxNode, ProxmoxServerCreate, NodeNetworkInterface } from '@/types';
|
||||
import { vmKeys } from './use-instances';
|
||||
@@ -53,11 +53,76 @@ export function useNodeStatus(serverId: number, node: string) {
|
||||
});
|
||||
}
|
||||
|
||||
export function useNodeRrddata(serverId: number, node: string, timeframe = 'hour') {
|
||||
return useQuery({
|
||||
/** One normalized sample of node RRD data — mirrors MetricPoint for instances. */
|
||||
export interface NodeMetricPoint {
|
||||
time: number;
|
||||
cpu: number | null; // percent
|
||||
iowait: number | null; // percent
|
||||
loadavg: number | null;
|
||||
memused: number | null; // bytes
|
||||
memtotal: number | null; // bytes
|
||||
mempct: number | null; // percent
|
||||
swapused: number | null; // bytes
|
||||
rootused: number | null; // bytes
|
||||
rootpct: number | null; // percent
|
||||
netin: number | null; // bytes/s
|
||||
netout: number | null; // bytes/s
|
||||
}
|
||||
|
||||
/** Raw RRD rows report cpu/iowait as 0..1 fractions and may omit fields entirely. */
|
||||
function num(row: Record<string, unknown>, key: string): number | null {
|
||||
const v = row[key];
|
||||
return typeof v === 'number' && Number.isFinite(v) ? v : null;
|
||||
}
|
||||
|
||||
function pct(used: number | null, total: number | null): number | null {
|
||||
if (used == null || !total) return null;
|
||||
return (used / total) * 100;
|
||||
}
|
||||
|
||||
export function normalizeNodeRrd(rows: Array<Record<string, unknown>>): NodeMetricPoint[] {
|
||||
return rows.map((r) => {
|
||||
const cpu = num(r, 'cpu');
|
||||
const iowait = num(r, 'iowait');
|
||||
const memused = num(r, 'memused');
|
||||
const memtotal = num(r, 'memtotal');
|
||||
const rootused = num(r, 'rootused');
|
||||
const roottotal = num(r, 'roottotal');
|
||||
return {
|
||||
time: num(r, 'time') ?? 0,
|
||||
cpu: cpu == null ? null : cpu * 100,
|
||||
iowait: iowait == null ? null : iowait * 100,
|
||||
loadavg: num(r, 'loadavg'),
|
||||
memused,
|
||||
memtotal,
|
||||
mempct: pct(memused, memtotal),
|
||||
swapused: num(r, 'swapused'),
|
||||
rootused,
|
||||
rootpct: pct(rootused, roottotal),
|
||||
netin: num(r, 'netin'),
|
||||
netout: num(r, 'netout'),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Node metrics for the graphs tab. PVE returns raw RRD rows (cpu as a 0..1
|
||||
* fraction, no percentages), so normalization happens here to keep the chart
|
||||
* components identical to the instance ones.
|
||||
*/
|
||||
export function useNodeMetrics(serverId: number, node: string, timeframe = 'hour') {
|
||||
return useQuery<NodeMetricPoint[]>({
|
||||
queryKey: nodeKeys.nodeRrd(serverId, node, timeframe),
|
||||
queryFn: () => apiClient.get<unknown[]>(`/proxmox/api/${serverId}/node/rrddata?node=${node}&timeframe=${timeframe}`),
|
||||
queryFn: () =>
|
||||
apiClient
|
||||
.get<{ data?: Array<Record<string, unknown>> } | Array<Record<string, unknown>>>(
|
||||
`/proxmox/api/${serverId}/node/rrddata?node=${node}&timeframe=${timeframe}`,
|
||||
)
|
||||
.then((r) => normalizeNodeRrd(Array.isArray(r) ? r : (r?.data ?? []))),
|
||||
enabled: serverId > 0 && !!node,
|
||||
// Keep the previous series on screen while a new timeframe loads.
|
||||
placeholderData: keepPreviousData,
|
||||
refetchInterval: timeframe === 'hour' ? 60000 : false,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -122,6 +187,23 @@ export function useDeleteServer() {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch a password-authenticated server over to an API token the panel creates
|
||||
* for itself. Uses the password already stored for that server.
|
||||
*/
|
||||
export function useProvisionServerToken() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (id: number) =>
|
||||
apiClient.post<{ success: boolean; token_name: string }>(
|
||||
`/proxmox/api/servers/${id}/provision-token`, {},
|
||||
),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: nodeKeys.servers });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useTestServer() {
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => apiClient.post<{ success: boolean; status?: string; message?: string }>(`/proxmox/api/servers/${id}/test`, {}),
|
||||
|
||||
@@ -598,6 +598,7 @@
|
||||
"cluster_nodes": "Cluster Nodes",
|
||||
"instances_on_server": "Instances on server",
|
||||
"tab_overview": "Overview",
|
||||
"tab_graphs": "Graphs",
|
||||
"tab_network": "Network",
|
||||
"tab_ha": "HA",
|
||||
"tab_firewall": "Firewall",
|
||||
@@ -619,6 +620,14 @@
|
||||
"api_token_name": "API Token Name",
|
||||
"api_token_value": "API Token Value",
|
||||
"use_password": "Use password auth",
|
||||
"auth_mode": "Connection method",
|
||||
"auth_mode_auto": "Login and password (panel creates an API token)",
|
||||
"auth_mode_token": "Existing API token",
|
||||
"auth_mode_password": "Password only",
|
||||
"auth_mode_auto_hint": "The password is used once to create an API token. From then on the panel works through the token, which you can revoke in Proxmox at any time.",
|
||||
"switch_to_token": "Switch to API token",
|
||||
"switch_to_token_confirm": "Create an API token for server \"{{name}}\" and switch the panel to it? The stored password is used.",
|
||||
"switch_to_token_ok": "Server switched to token \"{{token}}\"",
|
||||
"verify_ssl": "Verify SSL",
|
||||
"connection_ok": "Connection successful",
|
||||
"connection_failed": "Connection failed",
|
||||
@@ -1491,7 +1500,11 @@
|
||||
"network_in": "Network In",
|
||||
"network_out": "Network Out",
|
||||
"disk_read": "Disk Read",
|
||||
"disk_write": "Disk Write"
|
||||
"disk_write": "Disk Write",
|
||||
"io_delay": "IO Delay",
|
||||
"load_average": "Load Average",
|
||||
"swap_usage": "Swap Usage",
|
||||
"root_fs": "Root Filesystem"
|
||||
},
|
||||
"console": {
|
||||
"connecting": "Connecting to console...",
|
||||
|
||||
@@ -598,6 +598,7 @@
|
||||
"cluster_nodes": "Узлы кластера",
|
||||
"instances_on_server": "Инстансы на сервере",
|
||||
"tab_overview": "Обзор",
|
||||
"tab_graphs": "Графики",
|
||||
"tab_network": "Сеть",
|
||||
"tab_ha": "HA",
|
||||
"tab_firewall": "Firewall",
|
||||
@@ -619,6 +620,14 @@
|
||||
"api_token_name": "Имя API токена",
|
||||
"api_token_value": "Значение API токена",
|
||||
"use_password": "Использовать аутентификацию по паролю",
|
||||
"auth_mode": "Способ подключения",
|
||||
"auth_mode_auto": "Логин и пароль (панель создаст API-токен)",
|
||||
"auth_mode_token": "Готовый API-токен",
|
||||
"auth_mode_password": "Только пароль",
|
||||
"auth_mode_auto_hint": "Пароль будет использован один раз для создания API-токена. Дальше панель работает по токену — его можно отозвать в Proxmox в любой момент.",
|
||||
"switch_to_token": "Перевести на API-токен",
|
||||
"switch_to_token_confirm": "Создать API-токен для сервера «{{name}}» и переключить панель на него? Используется сохранённый пароль.",
|
||||
"switch_to_token_ok": "Сервер переключён на токен «{{token}}»",
|
||||
"verify_ssl": "Проверять SSL",
|
||||
"connection_ok": "Соединение успешно",
|
||||
"connection_failed": "Ошибка соединения",
|
||||
@@ -1491,7 +1500,11 @@
|
||||
"network_in": "Входящий трафик",
|
||||
"network_out": "Исходящий трафик",
|
||||
"disk_read": "Чтение диска",
|
||||
"disk_write": "Запись диска"
|
||||
"disk_write": "Запись диска",
|
||||
"io_delay": "Задержка ввода-вывода",
|
||||
"load_average": "Средняя нагрузка",
|
||||
"swap_usage": "Использование swap",
|
||||
"root_fs": "Корневая ФС"
|
||||
},
|
||||
"console": {
|
||||
"connecting": "Подключение к консоли...",
|
||||
|
||||
@@ -73,6 +73,8 @@ export interface ProxmoxServerCreate {
|
||||
api_token_value?: string;
|
||||
use_password?: boolean;
|
||||
password?: string;
|
||||
/** Authenticate once with the password, then let the panel create its own API token. */
|
||||
auto_create_token?: boolean;
|
||||
verify_ssl?: boolean;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user