feat: scheduled backups, availability tracking, PoE power metrics (v0.11.2 Beta)
P1 — Scheduled Backups - BackupService.createBackup() now accepts a `type` param (manual/scheduled) - PollerService: cronMatchesNow() parser + runScheduledBackups() + Redis 1h gate - Settings page: backup schedule toggle + cron expression input with examples P2 — Uptime/Availability Tracking - DB: device_availability table (went_offline_at, came_back_online_at, duration_seconds) - PollerService: inserts outage rows on offline detection, closes them on recovery - GET /api/metrics/device/:id/availability?range=30d endpoint - /api/metrics/summary now includes fleet 30-day uptime % - DeviceDetailPage: 30-day availability card (uptime %, outage count, longest outage) - DashboardPage HealthBar: Uptime 30d mini-stat P3 — PoE Power Draw Metrics - DeviceCollector.collectPoePower() queries /interface/ethernet/poe/monitor for switches - Writes poe_power measurement to InfluxDB (tags: device_id, port; fields: watts, current_ma, voltage_v) - GET /api/metrics/device/:id/poe endpoint (current per-port + 1h history) - SwitchPortDiagram: amber watt badge on PoE-active ports - HardwareTab: PoE budget section showing active ports and total watts Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
e692a1d7cd
commit
6a4ab1fc5f
@@ -2,7 +2,7 @@
|
||||
|
||||
A self-hosted, full-stack network management platform for MikroTik devices. Monitor, configure, and manage your entire MikroTik infrastructure — routers, switches, and wireless access points — from a single web interface.
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "mikrotik-manager-backend",
|
||||
"version": "0.11.1-beta",
|
||||
"version": "0.11.2-beta",
|
||||
"description": "Mikrotik Network Management Platform - Backend API",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -291,6 +291,16 @@ CREATE TABLE IF NOT EXISTS credential_presets (
|
||||
);
|
||||
ALTER TABLE credential_presets ADD COLUMN IF NOT EXISTS allow_operator_use BOOLEAN NOT NULL DEFAULT TRUE;
|
||||
|
||||
-- Device availability (offline/online outage tracking)
|
||||
CREATE TABLE IF NOT EXISTS device_availability (
|
||||
id SERIAL PRIMARY KEY,
|
||||
device_id INTEGER NOT NULL REFERENCES devices(id) ON DELETE CASCADE,
|
||||
went_offline_at TIMESTAMPTZ NOT NULL,
|
||||
came_back_online_at TIMESTAMPTZ,
|
||||
duration_seconds INTEGER
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_device_availability_device ON device_availability(device_id, went_offline_at DESC);
|
||||
|
||||
-- Wireless security profiles (WPA/WPA2/WPA3 config)
|
||||
CREATE TABLE IF NOT EXISTS wireless_security_profiles (
|
||||
id SERIAL PRIMARY KEY,
|
||||
|
||||
@@ -213,9 +213,103 @@ router.get('/device/:deviceId/resources', async (req: Request, res: Response) =>
|
||||
res.json(Object.values(pivoted).sort((a, b) => String(a['time']).localeCompare(String(b['time']))));
|
||||
});
|
||||
|
||||
// GET /api/metrics/device/:deviceId/poe - current PoE power per port + 1h time series
|
||||
router.get('/device/:deviceId/poe', async (req: Request, res: Response) => {
|
||||
const queryApi = getQueryApi();
|
||||
const deviceId = req.params.deviceId;
|
||||
|
||||
const currentFlux = `
|
||||
from(bucket: "${bucket}")
|
||||
|> range(start: -5m)
|
||||
|> filter(fn: (r) => r._measurement == "poe_power")
|
||||
|> filter(fn: (r) => r.device_id == "${deviceId}")
|
||||
|> filter(fn: (r) => r._field == "watts" or r._field == "current_ma" or r._field == "voltage_v")
|
||||
|> last()
|
||||
`;
|
||||
|
||||
const portData: Record<string, { port: string; watts: number; current_ma: number; voltage_v: number }> = {};
|
||||
try {
|
||||
await queryApi.collectRows(currentFlux, (row, tableMeta) => {
|
||||
const port = tableMeta.get(row, 'port') as string;
|
||||
const field = tableMeta.get(row, '_field') as string;
|
||||
const value = Number(tableMeta.get(row, '_value')) || 0;
|
||||
if (!portData[port]) portData[port] = { port, watts: 0, current_ma: 0, voltage_v: 0 };
|
||||
if (field === 'watts') portData[port].watts = value;
|
||||
if (field === 'current_ma') portData[port].current_ma = value;
|
||||
if (field === 'voltage_v') portData[port].voltage_v = value;
|
||||
});
|
||||
} catch { /* no data */ }
|
||||
|
||||
const historyFlux = `
|
||||
from(bucket: "${bucket}")
|
||||
|> range(start: -1h)
|
||||
|> filter(fn: (r) => r._measurement == "poe_power")
|
||||
|> filter(fn: (r) => r.device_id == "${deviceId}")
|
||||
|> filter(fn: (r) => r._field == "watts")
|
||||
|> aggregateWindow(every: 1m, fn: mean, createEmpty: false)
|
||||
`;
|
||||
|
||||
const history: { time: string; port: string; watts: number }[] = [];
|
||||
try {
|
||||
await queryApi.collectRows(historyFlux, (row, tableMeta) => {
|
||||
history.push({
|
||||
time: tableMeta.get(row, '_time') as string,
|
||||
port: tableMeta.get(row, 'port') as string,
|
||||
watts: Number(tableMeta.get(row, '_value')) || 0,
|
||||
});
|
||||
});
|
||||
} catch { /* no data */ }
|
||||
|
||||
const ports = Object.values(portData);
|
||||
const totalWatts = parseFloat(ports.reduce((s, p) => s + p.watts, 0).toFixed(2));
|
||||
|
||||
res.json({ ports, totalWatts, history });
|
||||
});
|
||||
|
||||
// GET /api/metrics/device/:deviceId/availability?range=30d
|
||||
router.get('/device/:deviceId/availability', async (req: Request, res: Response) => {
|
||||
const deviceId = parseInt(req.params.deviceId, 10);
|
||||
const rangeRaw = String(req.query.range || '30d');
|
||||
const allowedRanges: Record<string, string> = {
|
||||
'7d': '7 days', '30d': '30 days', '90d': '90 days',
|
||||
};
|
||||
const intervalStr = allowedRanges[rangeRaw] ?? '30 days';
|
||||
|
||||
const outages = await query<{
|
||||
id: number;
|
||||
went_offline_at: string;
|
||||
came_back_online_at: string | null;
|
||||
duration_seconds: number | null;
|
||||
}>(
|
||||
`SELECT id, went_offline_at, came_back_online_at, duration_seconds
|
||||
FROM device_availability
|
||||
WHERE device_id = $1
|
||||
AND went_offline_at > NOW() - ($2::text || '')::interval
|
||||
ORDER BY went_offline_at DESC`,
|
||||
[deviceId, intervalStr]
|
||||
);
|
||||
|
||||
const rangeSeconds = parseInt(intervalStr, 10) * 86400;
|
||||
const totalOutageSec = outages.reduce((sum, o) => {
|
||||
const dur = o.duration_seconds ?? (o.came_back_online_at == null ? Math.round((Date.now() / 1000) - new Date(o.went_offline_at).getTime() / 1000) : 0);
|
||||
return sum + dur;
|
||||
}, 0);
|
||||
const uptimePct = Math.max(0, Math.min(100, parseFloat(((1 - totalOutageSec / rangeSeconds) * 100).toFixed(2))));
|
||||
const longestOutage = outages.reduce((max, o) => Math.max(max, o.duration_seconds ?? 0), 0);
|
||||
|
||||
res.json({
|
||||
uptimePct,
|
||||
totalOutages: outages.length,
|
||||
longestOutageSec: longestOutage,
|
||||
totalOutageSec,
|
||||
outages,
|
||||
range: rangeRaw,
|
||||
});
|
||||
});
|
||||
|
||||
// GET /api/metrics/summary - dashboard summary stats
|
||||
router.get('/summary', async (_req: Request, res: Response) => {
|
||||
const [deviceStats, clientStats, alertStats] = await Promise.all([
|
||||
const [deviceStats, clientStats, alertStats, availStats] = await Promise.all([
|
||||
query<{ total: string; online: string; offline: string }>(
|
||||
`SELECT
|
||||
COUNT(*) as total,
|
||||
@@ -234,11 +328,23 @@ router.get('/summary', async (_req: Request, res: Response) => {
|
||||
COUNT(*) FILTER (WHERE severity='warning') as warning
|
||||
FROM events WHERE event_time > NOW() - INTERVAL '24 hours'`
|
||||
),
|
||||
query<{ total_outage_sec: string }>(
|
||||
`SELECT COALESCE(SUM(COALESCE(duration_seconds, 0)), 0)::text AS total_outage_sec
|
||||
FROM device_availability
|
||||
WHERE went_offline_at > NOW() - INTERVAL '30 days'`
|
||||
),
|
||||
]);
|
||||
|
||||
const deviceTotal = parseInt(deviceStats[0]?.total || '0', 10);
|
||||
const totalOutageSec = parseInt(availStats[0]?.total_outage_sec || '0', 10);
|
||||
const possibleDeviceSeconds = deviceTotal * 30 * 86400;
|
||||
const fleetUptimePct = possibleDeviceSeconds > 0
|
||||
? parseFloat(Math.max(0, Math.min(100, (1 - totalOutageSec / possibleDeviceSeconds) * 100)).toFixed(2))
|
||||
: 100;
|
||||
|
||||
res.json({
|
||||
devices: {
|
||||
total: parseInt(deviceStats[0]?.total || '0', 10),
|
||||
total: deviceTotal,
|
||||
online: parseInt(deviceStats[0]?.online || '0', 10),
|
||||
offline: parseInt(deviceStats[0]?.offline || '0', 10),
|
||||
},
|
||||
@@ -250,6 +356,9 @@ router.get('/summary', async (_req: Request, res: Response) => {
|
||||
critical: parseInt(alertStats[0]?.critical || '0', 10),
|
||||
warning: parseInt(alertStats[0]?.warning || '0', 10),
|
||||
},
|
||||
availability: {
|
||||
fleetUptimePct30d: fleetUptimePct,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ export class BackupService {
|
||||
}
|
||||
}
|
||||
|
||||
async createBackup(device: BackupDevice, notes?: string): Promise<number> {
|
||||
async createBackup(device: BackupDevice, notes?: string, type: string = 'manual'): Promise<number> {
|
||||
const sshUser = device.ssh_username || device.api_username;
|
||||
const sshPass = device.ssh_password_encrypted
|
||||
? decrypt(device.ssh_password_encrypted)
|
||||
@@ -53,8 +53,8 @@ export class BackupService {
|
||||
|
||||
const rows = await query<{ id: number }>(
|
||||
`INSERT INTO backups (device_id, filename, file_path, size_bytes, backup_type, notes)
|
||||
VALUES ($1,$2,$3,$4,'manual',$5) RETURNING id`,
|
||||
[device.id, filename, filePath, stats.size, notes || null]
|
||||
VALUES ($1,$2,$3,$4,$5,$6) RETURNING id`,
|
||||
[device.id, filename, filePath, stats.size, type, notes || null]
|
||||
);
|
||||
|
||||
return rows[0].id;
|
||||
|
||||
@@ -96,6 +96,8 @@ export class PollerService {
|
||||
const spectralIntervalHours = (appSettings['spectral_scan_interval_hours'] as number) || 24;
|
||||
const apScanEnabled = appSettings['ap_scan_enabled'] === true;
|
||||
const apScanIntervalHours = (appSettings['ap_scan_interval_hours'] as number) || 24;
|
||||
const backupScheduleEnabled = appSettings['backup_schedule_enabled'] === true;
|
||||
const backupScheduleCron = (appSettings['backup_schedule_cron'] as string) || '0 2 * * *';
|
||||
|
||||
const devices = await query<DeviceRow>(
|
||||
`SELECT * FROM devices WHERE status != 'disabled'`
|
||||
@@ -197,6 +199,19 @@ export class PollerService {
|
||||
console.error('[Poller] Client prune error:', e)
|
||||
);
|
||||
}
|
||||
|
||||
// Scheduled backups — fire when the cron expression matches the current minute/hour.
|
||||
// Redis key with 1-hour TTL prevents double-firing within the same cron window.
|
||||
if (backupScheduleEnabled && this.cronMatchesNow(backupScheduleCron)) {
|
||||
const backupKey = 'task:scheduled_backup';
|
||||
const lastBackup = await this.getTimestamp(backupKey);
|
||||
if (now - lastBackup > 3_600_000) {
|
||||
await this.setTimestamp(backupKey, now);
|
||||
this.runScheduledBackups().catch((e) =>
|
||||
console.error('[Poller] Scheduled backup error:', e)
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Scheduler error:', err);
|
||||
}
|
||||
@@ -209,7 +224,8 @@ export class PollerService {
|
||||
WHERE key IN ('mac_scan_enabled', 'mac_scan_interval', 'reverse_dns_enabled',
|
||||
'retention_clients_days', 'spectral_scan_enabled',
|
||||
'spectral_scan_interval_hours', 'ap_scan_enabled',
|
||||
'ap_scan_interval_hours')`
|
||||
'ap_scan_interval_hours', 'backup_schedule_enabled',
|
||||
'backup_schedule_cron')`
|
||||
);
|
||||
const map: Record<string, unknown> = {};
|
||||
for (const row of rows) map[row.key] = row.value;
|
||||
@@ -219,6 +235,49 @@ export class PollerService {
|
||||
}
|
||||
}
|
||||
|
||||
// Returns true if the 5-part cron expression matches the current minute/hour.
|
||||
// Supports: *, exact numbers, comma lists, ranges (a-b), and step values (*/n).
|
||||
private cronMatchesNow(cron: string): boolean {
|
||||
const parts = cron.trim().split(/\s+/);
|
||||
if (parts.length < 5) return false;
|
||||
const [minuteField, hourField] = parts;
|
||||
const now = new Date();
|
||||
const matchField = (field: string, val: number): boolean => {
|
||||
if (field === '*') return true;
|
||||
return field.split(',').some((f) => {
|
||||
if (f.includes('/')) {
|
||||
const [base, step] = f.split('/');
|
||||
const start = base === '*' ? 0 : Number(base);
|
||||
return val >= start && (val - start) % Number(step) === 0;
|
||||
}
|
||||
if (f.includes('-')) {
|
||||
const [lo, hi] = f.split('-').map(Number);
|
||||
return val >= lo && val <= hi;
|
||||
}
|
||||
return Number(f) === val;
|
||||
});
|
||||
};
|
||||
return matchField(minuteField, now.getMinutes()) && matchField(hourField, now.getHours());
|
||||
}
|
||||
|
||||
private async runScheduledBackups(): Promise<void> {
|
||||
const { BackupService } = await import('./BackupService');
|
||||
const backupService = new BackupService();
|
||||
const devices = await query<{
|
||||
id: number; name: string; ip_address: string; ssh_port: number;
|
||||
ssh_username: string; ssh_password_encrypted: string;
|
||||
api_username: string; api_password_encrypted: string;
|
||||
}>(`SELECT id, name, ip_address, ssh_port, ssh_username, ssh_password_encrypted,
|
||||
api_username, api_password_encrypted
|
||||
FROM devices WHERE status = 'online'`);
|
||||
console.log(`[Poller] Starting scheduled backup for ${devices.length} online device(s)`);
|
||||
const results = await Promise.allSettled(
|
||||
devices.map((d) => backupService.createBackup(d, 'Scheduled backup', 'scheduled'))
|
||||
);
|
||||
const succeeded = results.filter((r) => r.status === 'fulfilled').length;
|
||||
console.log(`[Poller] Scheduled backup complete: ${succeeded}/${devices.length} succeeded`);
|
||||
}
|
||||
|
||||
private async resolveClientHostnames(): Promise<void> {
|
||||
const { reverse } = await import('dns/promises');
|
||||
|
||||
@@ -376,6 +435,16 @@ export class PollerService {
|
||||
deviceId: device.id,
|
||||
deviceName: device.name,
|
||||
}).catch(() => {});
|
||||
// Close the open outage row if one exists
|
||||
if (prevStatus === 'offline') {
|
||||
query(
|
||||
`UPDATE device_availability
|
||||
SET came_back_online_at = NOW(),
|
||||
duration_seconds = EXTRACT(EPOCH FROM (NOW() - went_offline_at))::INTEGER
|
||||
WHERE device_id = $1 AND came_back_online_at IS NULL`,
|
||||
[device.id]
|
||||
).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
this.io?.emit('device:updated', { deviceId: device.id });
|
||||
@@ -620,6 +689,11 @@ export class PollerService {
|
||||
deviceId,
|
||||
deviceName: device?.name,
|
||||
}).catch(() => {});
|
||||
// Open a new availability outage row
|
||||
query(
|
||||
`INSERT INTO device_availability (device_id, went_offline_at) VALUES ($1, NOW())`,
|
||||
[deviceId]
|
||||
).catch(() => {});
|
||||
}
|
||||
// Mark all clients for this device inactive — updateClients() never ran because connect() failed.
|
||||
await query(`UPDATE clients SET active = FALSE WHERE device_id = $1`, [deviceId]);
|
||||
|
||||
@@ -71,6 +71,9 @@ export class DeviceCollector {
|
||||
if (this.device.device_type === 'wireless_ap') {
|
||||
await this.collectWirelessStats();
|
||||
}
|
||||
if (this.device.device_type === 'switch') {
|
||||
await this.collectPoePower();
|
||||
}
|
||||
await this.updateDeviceStatus('online');
|
||||
}
|
||||
|
||||
@@ -1727,6 +1730,37 @@ export class DeviceCollector {
|
||||
return this.client.execute('/interface/ethernet/poe/print', { detail: '' }).catch(() => []);
|
||||
}
|
||||
|
||||
async collectPoePower(): Promise<void> {
|
||||
try {
|
||||
const ports = await this.client
|
||||
.execute('/interface/ethernet/poe/monitor', { once: '' })
|
||||
.catch(() => [] as Record<string, string>[]);
|
||||
if (ports.length === 0) return;
|
||||
|
||||
const writeApi = getWriteApi();
|
||||
for (const port of ports) {
|
||||
const name = port['name'] || port['port-name'] || '';
|
||||
if (!name) continue;
|
||||
const watts = parseFloat(port['poe-out-voltage'] || '0') * parseFloat(port['poe-out-current'] || '0') / 1000;
|
||||
const currentMa = parseFloat(port['poe-out-current'] || '0');
|
||||
const voltageV = parseFloat(port['poe-out-voltage'] || '0');
|
||||
writeApi.writePoint(
|
||||
new Point('poe_power')
|
||||
.tag('device_id', String(this.device.id))
|
||||
.tag('device_name', this.device.name)
|
||||
.tag('port', name)
|
||||
.floatField('watts', parseFloat(watts.toFixed(2)))
|
||||
.floatField('current_ma', currentMa)
|
||||
.floatField('voltage_v', voltageV)
|
||||
.timestamp(new Date())
|
||||
);
|
||||
}
|
||||
await writeApi.flush().catch((e) => console.error('InfluxDB PoE flush error:', e));
|
||||
} catch (err) {
|
||||
console.error(`[${this.device.name}] Failed to collect PoE power:`, err);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Port VLAN config ─────────────────────────────────────────────────────
|
||||
|
||||
async setPortVlanConfig(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "mikrotik-manager-frontend",
|
||||
"version": "0.11.1-beta",
|
||||
"version": "0.11.2-beta",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -321,6 +321,12 @@ export default function HardwareTab({ deviceId }: { deviceId: number }) {
|
||||
refetchInterval: 30_000,
|
||||
});
|
||||
|
||||
const { data: poeData } = useQuery({
|
||||
queryKey: ['device-poe', deviceId],
|
||||
queryFn: () => metricsApi.devicePoe(deviceId).then((r) => r.data),
|
||||
refetchInterval: 30_000,
|
||||
});
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-48">
|
||||
@@ -473,6 +479,31 @@ export default function HardwareTab({ deviceId }: { deviceId: number }) {
|
||||
))}
|
||||
</Section>
|
||||
)}
|
||||
|
||||
{poeData && poeData.ports.length > 0 && (
|
||||
<div className="lg:col-span-2">
|
||||
<Section title={`PoE Budget — ${poeData.totalWatts.toFixed(1)} W total`} icon={<Zap className="w-4 h-4" />} grid={false}>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3">
|
||||
{poeData.ports.filter(p => p.watts > 0).map((p) => (
|
||||
<div key={p.port} className="rounded-lg p-3" style={{ background: 'var(--surface-2)' }}>
|
||||
<div className="text-xs font-mono text-gray-500 dark:text-slate-400 mb-1">{p.port}</div>
|
||||
<div className="text-lg font-bold text-yellow-500">{p.watts.toFixed(1)} W</div>
|
||||
<div className="text-xs text-gray-400 dark:text-slate-500">
|
||||
{p.voltage_v.toFixed(1)} V · {p.current_ma.toFixed(0)} mA
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{poeData.ports.filter(p => p.watts === 0).length > 0 && (
|
||||
<div className="rounded-lg p-3 opacity-40" style={{ background: 'var(--surface-2)' }}>
|
||||
<div className="text-xs text-gray-500 dark:text-slate-400">
|
||||
{poeData.ports.filter(p => p.watts === 0).length} port(s) inactive
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Section>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -56,10 +56,10 @@ function portState(port: SwitchPort): 'up' | 'down' | 'disabled' {
|
||||
}
|
||||
|
||||
function PortTile({
|
||||
port, selected, hovered, isMember,
|
||||
port, selected, hovered, isMember, watts,
|
||||
onClick, onMouseEnter, onMouseLeave, onDoubleClick,
|
||||
}: {
|
||||
port: SwitchPort; selected: boolean; hovered: boolean; isMember?: boolean;
|
||||
port: SwitchPort; selected: boolean; hovered: boolean; isMember?: boolean; watts?: number;
|
||||
onClick: (e: React.MouseEvent) => void;
|
||||
onMouseEnter: () => void; onMouseLeave: () => void; onDoubleClick: () => void;
|
||||
}) {
|
||||
@@ -74,7 +74,7 @@ function PortTile({
|
||||
onMouseEnter={onMouseEnter}
|
||||
onMouseLeave={onMouseLeave}
|
||||
onDoubleClick={onDoubleClick}
|
||||
title={`${port.name}${port.comment ? ` — ${port.comment}` : ''}${port.speed ? ` · ${port.speed}` : ''}`}
|
||||
title={`${port.name}${port.comment ? ` — ${port.comment}` : ''}${port.speed ? ` · ${port.speed}` : ''}${watts && watts > 0 ? ` · ${watts.toFixed(1)}W PoE` : ''}`}
|
||||
style={{
|
||||
width: 46, height: 46, borderRadius: 4, position: 'relative', flexShrink: 0,
|
||||
background: bg, border: `1px solid ${border}`,
|
||||
@@ -90,6 +90,15 @@ function PortTile({
|
||||
boxShadow: state === 'up' && !selected ? '0 0 6px var(--accent)' : 'none',
|
||||
}} />
|
||||
<span>{portLabel(port.name)}</span>
|
||||
{watts && watts > 0 ? (
|
||||
<span style={{
|
||||
position: 'absolute', bottom: 2, left: 0, right: 0, textAlign: 'center',
|
||||
fontSize: 7, fontWeight: 700, color: selected ? '#fff' : '#f59e0b',
|
||||
lineHeight: 1, letterSpacing: 0,
|
||||
}}>
|
||||
{watts.toFixed(0)}W
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -494,6 +503,16 @@ export default function SwitchPortDiagram({ deviceId, autoOpenBridge, onBridgeOp
|
||||
refetchInterval: 30_000,
|
||||
});
|
||||
|
||||
const { data: poeMetrics } = useQuery({
|
||||
queryKey: ['device-poe', deviceId],
|
||||
queryFn: () => metricsApi.devicePoe(deviceId).then((r) => r.data),
|
||||
refetchInterval: 30_000,
|
||||
});
|
||||
|
||||
const poeWattsMap = Object.fromEntries(
|
||||
(poeMetrics?.ports ?? []).map(p => [p.port, p.watts])
|
||||
);
|
||||
|
||||
// Auto-open bridge config panel when navigated from the VLANs tab warning
|
||||
useEffect(() => {
|
||||
if (!autoOpenBridge || !data?.ports) return;
|
||||
@@ -881,19 +900,19 @@ export default function SwitchPortDiagram({ deviceId, autoOpenBridge, onBridgeOp
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
|
||||
<div style={{ display: 'flex', gap: 4 }}>
|
||||
{topRowPorts.map(port => (
|
||||
<PortTile key={port.name} port={port} selected={selectedPorts.has(port.name)} hovered={hoveredPort === port.name} isMember={bondMemberMap.has(port.name)} onClick={e => togglePort(port.name, e)} onMouseEnter={() => setHoveredPort(port.name)} onMouseLeave={() => setHoveredPort(null)} onDoubleClick={() => canWrite && openEditPanel(port)} />
|
||||
<PortTile key={port.name} port={port} selected={selectedPorts.has(port.name)} hovered={hoveredPort === port.name} isMember={bondMemberMap.has(port.name)} watts={poeWattsMap[port.name]} onClick={e => togglePort(port.name, e)} onMouseEnter={() => setHoveredPort(port.name)} onMouseLeave={() => setHoveredPort(null)} onDoubleClick={() => canWrite && openEditPanel(port)} />
|
||||
))}
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 4 }}>
|
||||
{bottomRowPorts.map(port => (
|
||||
<PortTile key={port.name} port={port} selected={selectedPorts.has(port.name)} hovered={hoveredPort === port.name} isMember={bondMemberMap.has(port.name)} onClick={e => togglePort(port.name, e)} onMouseEnter={() => setHoveredPort(port.name)} onMouseLeave={() => setHoveredPort(null)} onDoubleClick={() => canWrite && openEditPanel(port)} />
|
||||
<PortTile key={port.name} port={port} selected={selectedPorts.has(port.name)} hovered={hoveredPort === port.name} isMember={bondMemberMap.has(port.name)} watts={poeWattsMap[port.name]} onClick={e => togglePort(port.name, e)} onMouseEnter={() => setHoveredPort(port.name)} onMouseLeave={() => setHoveredPort(null)} onDoubleClick={() => canWrite && openEditPanel(port)} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ display: 'flex', gap: 4 }}>
|
||||
{topRowPorts.map(port => (
|
||||
<PortTile key={port.name} port={port} selected={selectedPorts.has(port.name)} hovered={hoveredPort === port.name} isMember={bondMemberMap.has(port.name)} onClick={e => togglePort(port.name, e)} onMouseEnter={() => setHoveredPort(port.name)} onMouseLeave={() => setHoveredPort(null)} onDoubleClick={() => canWrite && openEditPanel(port)} />
|
||||
<PortTile key={port.name} port={port} selected={selectedPorts.has(port.name)} hovered={hoveredPort === port.name} isMember={bondMemberMap.has(port.name)} watts={poeWattsMap[port.name]} onClick={e => togglePort(port.name, e)} onMouseEnter={() => setHoveredPort(port.name)} onMouseLeave={() => setHoveredPort(null)} onDoubleClick={() => canWrite && openEditPanel(port)} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
@@ -908,7 +927,7 @@ export default function SwitchPortDiagram({ deviceId, autoOpenBridge, onBridgeOp
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 4, flexWrap: 'wrap', maxWidth: individualSfpPorts.length * 52 }}>
|
||||
{individualSfpPorts.map(port => (
|
||||
<PortTile key={port.name} port={port} selected={selectedPorts.has(port.name)} hovered={hoveredPort === port.name} onClick={e => togglePort(port.name, e)} onMouseEnter={() => setHoveredPort(port.name)} onMouseLeave={() => setHoveredPort(null)} onDoubleClick={() => canWrite && openEditPanel(port)} />
|
||||
<PortTile key={port.name} port={port} selected={selectedPorts.has(port.name)} hovered={hoveredPort === port.name} watts={poeWattsMap[port.name]} onClick={e => togglePort(port.name, e)} onMouseEnter={() => setHoveredPort(port.name)} onMouseLeave={() => setHoveredPort(null)} onDoubleClick={() => canWrite && openEditPanel(port)} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
@@ -929,7 +948,7 @@ export default function SwitchPortDiagram({ deviceId, autoOpenBridge, onBridgeOp
|
||||
const lane = isSingleMode ? cage.singlePort! : cage.lanes[li];
|
||||
const visualPort: SwitchPort = (isSingleMode || isSingleCable) ? { ...refPort, running: refPort.running, disabled: refPort.disabled } : lane;
|
||||
return (
|
||||
<PortTile key={li} port={visualPort} selected={selectedPorts.has(lane.name)} hovered={hoveredPort === lane.name} onClick={e => togglePort(lane.name, e)} onMouseEnter={() => setHoveredPort(lane.name)} onMouseLeave={() => setHoveredPort(null)} onDoubleClick={() => canWrite && openEditPanel(lane)} />
|
||||
<PortTile key={li} port={visualPort} selected={selectedPorts.has(lane.name)} hovered={hoveredPort === lane.name} watts={poeWattsMap[lane.name]} onClick={e => togglePort(lane.name, e)} onMouseEnter={() => setHoveredPort(lane.name)} onMouseLeave={() => setHoveredPort(null)} onDoubleClick={() => canWrite && openEditPanel(lane)} />
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
@@ -943,7 +962,7 @@ export default function SwitchPortDiagram({ deviceId, autoOpenBridge, onBridgeOp
|
||||
<div className="mono" style={{ fontSize: 10, color: 'var(--ink-4)', letterSpacing: '.1em' }}>BRIDGE</div>
|
||||
<div style={{ display: 'flex', gap: 4 }}>
|
||||
{bridgePorts.map(port => (
|
||||
<PortTile key={port.name} port={port} selected={selectedPorts.has(port.name)} hovered={hoveredPort === port.name} onClick={e => togglePort(port.name, e)} onMouseEnter={() => setHoveredPort(port.name)} onMouseLeave={() => setHoveredPort(null)} onDoubleClick={() => canWrite && openEditPanel(port)} />
|
||||
<PortTile key={port.name} port={port} selected={selectedPorts.has(port.name)} hovered={hoveredPort === port.name} watts={poeWattsMap[port.name]} onClick={e => togglePort(port.name, e)} onMouseEnter={() => setHoveredPort(port.name)} onMouseLeave={() => setHoveredPort(null)} onDoubleClick={() => canWrite && openEditPanel(port)} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
@@ -955,7 +974,7 @@ export default function SwitchPortDiagram({ deviceId, autoOpenBridge, onBridgeOp
|
||||
<div className="mono" style={{ fontSize: 10, color: 'var(--ink-4)', letterSpacing: '.1em' }}>BOND</div>
|
||||
<div style={{ display: 'flex', gap: 4 }}>
|
||||
{bondPorts.map(port => (
|
||||
<PortTile key={port.name} port={port} selected={selectedPorts.has(port.name)} hovered={hoveredPort === port.name} onClick={e => togglePort(port.name, e)} onMouseEnter={() => setHoveredPort(port.name)} onMouseLeave={() => setHoveredPort(null)} onDoubleClick={() => canWrite && openEditPanel(port)} />
|
||||
<PortTile key={port.name} port={port} selected={selectedPorts.has(port.name)} hovered={hoveredPort === port.name} watts={poeWattsMap[port.name]} onClick={e => togglePort(port.name, e)} onMouseEnter={() => setHoveredPort(port.name)} onMouseLeave={() => setHoveredPort(null)} onDoubleClick={() => canWrite && openEditPanel(port)} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -158,7 +158,7 @@ function DeviceLocationsMap({ devices }: { devices: Device[] }) {
|
||||
function HealthBar({
|
||||
summary, devices, wirelessCount, clientSparkline,
|
||||
}: {
|
||||
summary: { devices: { total: number; online: number; offline: number }; clients: { active: number; total: number }; alerts: { critical: number; warning: number } } | undefined;
|
||||
summary: { devices: { total: number; online: number; offline: number }; clients: { active: number; total: number }; alerts: { critical: number; warning: number }; availability?: { fleetUptimePct30d: number } } | undefined;
|
||||
devices: Device[];
|
||||
wirelessCount: number;
|
||||
clientSparkline: number[];
|
||||
@@ -234,6 +234,14 @@ function HealthBar({
|
||||
spark: [] as number[],
|
||||
color: (summary?.alerts.critical ?? 0) > 0 ? 'var(--bad)' : 'var(--ink-3)',
|
||||
},
|
||||
{
|
||||
label: 'Uptime 30d',
|
||||
value: summary?.availability != null
|
||||
? `${summary.availability.fleetUptimePct30d.toFixed(1)}%`
|
||||
: '—',
|
||||
spark: [] as number[],
|
||||
color: (summary?.availability?.fleetUptimePct30d ?? 100) >= 99 ? 'var(--accent)' : (summary?.availability?.fleetUptimePct30d ?? 100) >= 95 ? 'var(--warn)' : 'var(--bad)',
|
||||
},
|
||||
].map(({ label, value, spark, color }) => (
|
||||
<div key={label} style={{ minWidth: 110, paddingLeft: 20, borderLeft: '1px solid var(--line)' }}>
|
||||
<div className="text-[11px] mb-[2px]" style={{ color: 'var(--ink-3)' }}>{label}</div>
|
||||
|
||||
@@ -2,9 +2,9 @@ import { useState } from 'react';
|
||||
import { useParams, useNavigate } from 'react-router-dom';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import {
|
||||
ArrowLeft, RefreshCw, Activity, Cpu, MemoryStick, Clock, ExternalLink, TerminalSquare,
|
||||
ArrowLeft, RefreshCw, Activity, Cpu, MemoryStick, Clock, ExternalLink, TerminalSquare, ShieldCheck,
|
||||
} from 'lucide-react';
|
||||
import { devicesApi } from '../services/api';
|
||||
import { devicesApi, metricsApi } from '../services/api';
|
||||
import { useCanWrite } from '../hooks/useCanWrite';
|
||||
import SwitchPortDiagram from '../components/ports/SwitchPortDiagram';
|
||||
import TerminalModal from '../components/TerminalModal';
|
||||
@@ -64,6 +64,12 @@ export default function DeviceDetailPage() {
|
||||
enabled: device?.status === 'online',
|
||||
});
|
||||
|
||||
const { data: availability } = useQuery({
|
||||
queryKey: ['device-availability', deviceId],
|
||||
queryFn: () => metricsApi.deviceAvailability(deviceId, '30d').then((r) => r.data),
|
||||
refetchInterval: 60_000,
|
||||
});
|
||||
|
||||
const syncMutation = useMutation({
|
||||
mutationFn: () => devicesApi.sync(deviceId),
|
||||
onSuccess: () => {
|
||||
@@ -265,6 +271,56 @@ export default function DeviceDetailPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Availability card */}
|
||||
<div className="card p-4">
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<ShieldCheck className="w-4 h-4 text-blue-500" />
|
||||
<span className="text-sm font-semibold text-gray-900 dark:text-white">30-Day Availability</span>
|
||||
</div>
|
||||
{availability ? (
|
||||
<div className="flex flex-wrap gap-6">
|
||||
<div>
|
||||
<div className={clsx(
|
||||
'text-3xl font-bold',
|
||||
availability.uptimePct >= 99 ? 'text-green-500' : availability.uptimePct >= 95 ? 'text-yellow-500' : 'text-red-500'
|
||||
)}>
|
||||
{availability.uptimePct.toFixed(2)}%
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 dark:text-slate-400 mt-0.5">Uptime</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-2xl font-bold text-gray-900 dark:text-white">{availability.totalOutages}</div>
|
||||
<div className="text-xs text-gray-500 dark:text-slate-400 mt-0.5">Outages</div>
|
||||
</div>
|
||||
{availability.longestOutageSec > 0 && (
|
||||
<div>
|
||||
<div className="text-2xl font-bold text-gray-900 dark:text-white">
|
||||
{availability.longestOutageSec < 60
|
||||
? `${availability.longestOutageSec}s`
|
||||
: availability.longestOutageSec < 3600
|
||||
? `${Math.round(availability.longestOutageSec / 60)}m`
|
||||
: `${(availability.longestOutageSec / 3600).toFixed(1)}h`}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 dark:text-slate-400 mt-0.5">Longest outage</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex-1 min-w-[120px] self-center">
|
||||
<div className="h-2 bg-gray-200 dark:bg-slate-600 rounded-full overflow-hidden">
|
||||
<div
|
||||
className={clsx(
|
||||
'h-full rounded-full transition-all',
|
||||
availability.uptimePct >= 99 ? 'bg-green-500' : availability.uptimePct >= 95 ? 'bg-yellow-500' : 'bg-red-500'
|
||||
)}
|
||||
style={{ width: `${availability.uptimePct}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-sm text-gray-400 dark:text-slate-500">No availability data yet</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* System details */}
|
||||
<div className="card p-5">
|
||||
<h3 className="text-sm font-semibold text-gray-900 dark:text-white mb-4">
|
||||
|
||||
@@ -496,6 +496,53 @@ export default function SettingsPage() {
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Scheduled Backups */}
|
||||
<div className="card p-5">
|
||||
<h3 className="font-semibold text-gray-900 dark:text-white mb-1">Scheduled Backups</h3>
|
||||
<p className="text-xs text-gray-400 dark:text-slate-500 mb-4">
|
||||
Automatically backs up all online devices on a cron schedule via SSH export.
|
||||
Backups appear in the Backups section with type <code className="font-mono">scheduled</code>.
|
||||
</p>
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="text-sm font-medium text-gray-700 dark:text-slate-300">Enable scheduled backups</div>
|
||||
<button
|
||||
onClick={() => isAdmin && updateSettingsMutation.mutate({ backup_schedule_enabled: !settings['backup_schedule_enabled'] })}
|
||||
disabled={!isAdmin}
|
||||
className={clsx(
|
||||
'relative inline-flex h-6 w-11 flex-shrink-0 rounded-full border-2 border-transparent transition-colors duration-200',
|
||||
isAdmin ? 'cursor-pointer' : 'cursor-not-allowed opacity-50',
|
||||
settings['backup_schedule_enabled'] ? 'bg-blue-600' : 'bg-gray-300 dark:bg-slate-600'
|
||||
)}
|
||||
>
|
||||
<span className={clsx(
|
||||
'inline-block h-5 w-5 transform rounded-full bg-white shadow transition duration-200',
|
||||
settings['backup_schedule_enabled'] ? 'translate-x-5' : 'translate-x-0'
|
||||
)} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<div className="text-sm font-medium text-gray-700 dark:text-slate-300">Cron schedule</div>
|
||||
<div className="text-xs text-gray-400">Standard 5-part cron expression (minute hour day month weekday)</div>
|
||||
</div>
|
||||
<input
|
||||
type="text"
|
||||
className="input w-36 text-center font-mono text-sm disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
value={(settings['backup_schedule_cron'] as string) ?? '0 2 * * *'}
|
||||
onChange={(e) => updateSettingsMutation.mutate({ backup_schedule_cron: e.target.value })}
|
||||
placeholder="0 2 * * *"
|
||||
disabled={!isAdmin || !settings['backup_schedule_enabled']}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-gray-400 dark:text-slate-500">
|
||||
Examples: <code className="font-mono">0 2 * * *</code> = daily at 2:00 AM ·
|
||||
<code className="font-mono">0 3 * * 0</code> = weekly Sunday at 3:00 AM ·
|
||||
<code className="font-mono">0 */6 * * *</code> = every 6 hours
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import type {
|
||||
DeviceEvent,
|
||||
Backup,
|
||||
MetricsSummary,
|
||||
DeviceAvailability,
|
||||
TimeSeriesPoint,
|
||||
TrafficPoint,
|
||||
ResourcePoint,
|
||||
@@ -370,6 +371,10 @@ export const metricsApi = {
|
||||
}),
|
||||
deviceResources: (deviceId: number, range = '24h') =>
|
||||
api.get<ResourcePoint[]>(`/metrics/device/${deviceId}/resources`, { params: { range } }),
|
||||
deviceAvailability: (deviceId: number, range = '30d') =>
|
||||
api.get<DeviceAvailability>(`/metrics/device/${deviceId}/availability`, { params: { range } }),
|
||||
devicePoe: (deviceId: number) =>
|
||||
api.get<{ ports: { port: string; watts: number; current_ma: number; voltage_v: number }[]; totalWatts: number; history: { time: string; port: string; watts: number }[] }>(`/metrics/device/${deviceId}/poe`),
|
||||
};
|
||||
|
||||
// ─── Topology ────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -230,6 +230,21 @@ export interface MetricsSummary {
|
||||
devices: { total: number; online: number; offline: number };
|
||||
clients: { total: number; active: number };
|
||||
alerts: { critical: number; warning: number };
|
||||
availability?: { fleetUptimePct30d: number };
|
||||
}
|
||||
|
||||
export interface DeviceAvailability {
|
||||
uptimePct: number;
|
||||
totalOutages: number;
|
||||
longestOutageSec: number;
|
||||
totalOutageSec: number;
|
||||
outages: {
|
||||
id: number;
|
||||
went_offline_at: string;
|
||||
came_back_online_at: string | null;
|
||||
duration_seconds: number | null;
|
||||
}[];
|
||||
range: string;
|
||||
}
|
||||
|
||||
export interface TimeSeriesPoint {
|
||||
|
||||
@@ -1 +1 @@
|
||||
export const APP_VERSION = 'v0.11.1 Beta';
|
||||
export const APP_VERSION = 'v0.11.2 Beta';
|
||||
|
||||
Reference in New Issue
Block a user