Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
import type { Disk } from '@/types/api';
import { getFilesystemByteUsagePercent } from '@/utils/filesystemByteUsage';
import { getWorkloadDiskUsagePercent } from '@/utils/workloadDiskUsage';
import type { WorkloadGuestDiskRead } from '@/utils/workloadGuestPresentation';
import type { AnomalyReport } from '@/types/aiIntelligence';
import {
ANOMALY_SEVERITY_CLASS,
estimateTextWidth,
formatAnomalyRatio,
formatBytes,
formatPercent,
} from '@/utils/format';
import { getMetricColorRgba } from '@/utils/metricThresholds';
import type { MetricDisplayThresholds } from '@/utils/metricThresholds';
export interface StackedDiskBarProps {
disks?: Disk[];
aggregateDisk?: Disk;
mode?: 'stacked' | 'aggregate' | 'mini' | 'vertical-bars';
summaryStrategy?: 'total' | 'max';
showDiskCount?: boolean;
anomaly?: AnomalyReport | null;
thresholds?: MetricDisplayThresholds | null;
statusMessage?: string;
/** Source-owned classification; advisory text and capacity never establish freshness. */
reading?: Pick<WorkloadGuestDiskRead, 'state' | 'message'> | null;
}
export interface StackedDiskSegment {
color: string;
disk: Disk;
diskUsagePercent: number;
index: number;
widthPercent: number;
}
export interface StackedDiskTooltipItem {
color: string;
label: string;
percent: string;
total: string;
used: string;
}
export interface StackedDiskMiniDisk {
color: string;
inlineText: string;
label: string;
percent: number;
percentLabel: string;
shortLabel: string;
title: string;
}
export interface StackedDiskVerticalBar {
color: string;
fillPercent: number;
title: string;
}
export interface StackedDiskMaxInfo {
label: string;
percent: number;
total: number;
used: number;
}
export interface StackedDiskBarPresentation {
aggregateMode: boolean;
anomalyClass: string;
anomalyDescription?: string;
anomalyRatio: string;
barColor: string;
barPercent: number;
containerClass: string;
diskCountLabel: string;
diskCountTitle: string;
displayLabel: string;
displayPercentValue: number;
displaySublabel: string;
hasDisks: boolean;
hasMultipleDisks: boolean;
inlineDiskMode: boolean;
maxLabelFull: string;
maxLabelShort: string;
miniDisks: StackedDiskMiniDisk[];
miniMode: boolean;
segments: StackedDiskSegment[];
showDiskCount: boolean;
showMaxLabel: boolean;
showSublabel: boolean;
tooltipContent: StackedDiskTooltipItem[];
tooltipTitle: string;
tooltipMessage?: string;
unavailable: boolean;
useStackedSegments: boolean;
verticalBars: StackedDiskVerticalBar[];
// The fullest disk's usage, shown beside the micro-bars so a multi-disk
// host answers "how close is this host to running out?" without a hover.
verticalBarsLabel: string;
verticalBarsLabelTitle: string;
verticalBarsMode: boolean;
}
const SEGMENT_COLORS = [
'rgba(34, 197, 94, 0.6)',
'rgba(59, 130, 246, 0.6)',
'rgba(168, 85, 247, 0.6)',
'rgba(249, 115, 22, 0.6)',
'rgba(236, 72, 153, 0.6)',
'rgba(20, 184, 166, 0.6)',
];
function getDiskUsagePercent(disk: Disk): number {
const total = disk.total ?? 0;
if (total > 0) {
return ((disk.used ?? 0) / total) * 100;
}
return getWorkloadDiskUsagePercent(disk) ?? 0;
}
// Unknown sentinels and invalid/incomplete byte readings cannot contribute
// to utilization, totals or severity. Keep their identity/capacity in the
// tooltip, with the same admission as the per-filesystem drawer rows.
export function isStackedDiskUsageUnknown(disk: Disk): boolean {
return getFilesystemByteUsagePercent(disk) === null;
}
const UNKNOWN_DISK_COLOR = 'rgba(148, 163, 184, 0.5)';
function getDiskLabel(disk: Disk, index: number): string {
return disk.mountpoint || disk.device || `Disk ${index + 1}`;
}
function getShortDiskLabel(label: string): string {
const trimmed = label.trim();
if (trimmed.startsWith('/dev/')) {
return trimmed.slice('/dev/'.length);
}
const parts = trimmed.split('/').filter(Boolean);
if (trimmed === '/') {
return '/';
}
if (trimmed.startsWith('/') && parts.length > 0) {
return parts[parts.length - 1];
}
if (trimmed.length <= 12) {
return trimmed;
}
return trimmed;
}
// Horizontal padding around the aggregate label inside the bar (px-0.5 in
// StackedDiskBar.tsx).
const LABEL_PADDING_PX = 4;
// Inline per-disk labels are text-[9px] font-semibold, in px-px slots that a
// gap-0.5 separates.
const INLINE_DISK_FONT_PX = 9;
const INLINE_DISK_SLOT_PADDING_PX = 2;
const INLINE_DISK_SLOT_GAP_PX = 2;
function estimateInlineTextWidth(text: string): number {
return estimateTextWidth(text, { fontPx: INLINE_DISK_FONT_PX }) + INLINE_DISK_SLOT_PADDING_PX;
}
function getInlineDiskText(shortLabel: string, percentLabel: string, slotWidth: number): string {
const fullText = `${shortLabel} ${percentLabel}`;
if (slotWidth <= 0 || estimateInlineTextWidth(fullText) <= slotWidth) {
return fullText;
}
if (estimateInlineTextWidth(percentLabel) <= slotWidth) {
return percentLabel;
}
if (estimateInlineTextWidth(shortLabel) <= slotWidth) {
return shortLabel;
}
return '';
}
function getStackedDiskColor(
percent: number,
index: number,
thresholds?: MetricDisplayThresholds | null,
): string {
const critical = thresholds?.critical ?? 90;
const warning = thresholds?.warning ?? 80;
if (percent >= critical) {
return getMetricColorRgba(percent, 'disk', thresholds);
}
if (percent >= warning) {
return getMetricColorRgba(percent, 'disk', thresholds);
}
return SEGMENT_COLORS[index % SEGMENT_COLORS.length];
}
function buildTooltipContent(
disks: Disk[],
options: {
aggregateDisk: Disk | undefined;
aggregateMode: boolean;
current: boolean;
unavailable: boolean;
inlineDiskMode: boolean;
miniMode: boolean;
thresholds?: MetricDisplayThresholds | null;
verticalBarsMode: boolean;
},
): StackedDiskTooltipItem[] {
const useUsageColors =
options.aggregateMode || options.inlineDiskMode || options.miniMode || options.verticalBarsMode;
if (disks.length > 0) {
return disks.map((disk, index) => {
if (options.unavailable || isStackedDiskUsageUnknown(disk)) {
return {
color: UNKNOWN_DISK_COLOR,
label: getDiskLabel(disk, index),
percent: '—',
total:
typeof disk.total === 'number' && Number.isFinite(disk.total) && disk.total > 0
? formatBytes(disk.total)
: '—',
used: '?',
};
}
const percentValue = getDiskUsagePercent(disk);
return {
color: !options.current
? UNKNOWN_DISK_COLOR
: useUsageColors
? getMetricColorRgba(percentValue, 'disk', options.thresholds)
: getStackedDiskColor(percentValue, index, options.thresholds),
label: getDiskLabel(disk, index),
percent: formatPercent(percentValue),
total: formatBytes(disk.total ?? 0),
used: formatBytes(disk.used ?? 0),
};
});
}
if (options.aggregateDisk) {
const aggregate = options.aggregateDisk;
const percentValue = getWorkloadDiskUsagePercent(aggregate);
const hasUsed =
typeof aggregate.used === 'number' && Number.isFinite(aggregate.used) && aggregate.used >= 0;
const hasTotal =
typeof aggregate.total === 'number' &&
Number.isFinite(aggregate.total) &&
aggregate.total > 0;
return [
{
color:
options.current && percentValue !== null
? getMetricColorRgba(percentValue, 'disk', options.thresholds)
: UNKNOWN_DISK_COLOR,
label: 'Total',
percent: options.unavailable || percentValue === null ? '—' : formatPercent(percentValue),
total: hasTotal ? formatBytes(aggregate.total!) : '—',
used: options.unavailable || !hasUsed ? '?' : formatBytes(aggregate.used!),
},
];
}
return [];
}
function getMaxDiskInfo(disks: Disk[]): StackedDiskMaxInfo | null {
if (disks.length === 0) {
return null;
}
let maxInfo: StackedDiskMaxInfo | null = null;
for (const [index, disk] of disks.entries()) {
const percent = getDiskUsagePercent(disk);
if (!maxInfo || percent > maxInfo.percent) {
maxInfo = {
label: getDiskLabel(disk, index),
percent,
total: disk.total ?? 0,
used: disk.used ?? 0,
};
}
}
return maxInfo;
}
export function buildStackedDiskBarPresentation(
props: StackedDiskBarProps,
containerWidth: number,
): StackedDiskBarPresentation {
const allDisks = props.disks ?? [];
const measuredDisks = allDisks.filter((disk) => !isStackedDiskUsageUnknown(disk));
// Independently supplied aggregate percentages keep their legacy fallback;
// they do not make an unmeasured per-filesystem byte row usable.
const aggregate = props.aggregateDisk;
const aggregatePercent = getWorkloadDiskUsagePercent(aggregate);
const hasAggregateUsage = aggregatePercent !== null;
// Retained numbers explain the last report, not live pressure. If every
// supplied filesystem is unmeasured, do not fall through to a fabricated 0%.
const unavailable =
props.reading?.state === 'unavailable' ||
((allDisks.length > 0 || Boolean(aggregate)) &&
measuredDisks.length === 0 &&
!hasAggregateUsage);
const current = !unavailable && (!props.reading || props.reading.state === 'current');
const valuePrefix = props.reading?.state === 'last-known' ? 'Last known ' : '';
const anomaly = current ? props.anomaly : null;
const aggregateDisk = unavailable ? undefined : aggregate;
const disks = unavailable ? [] : measuredDisks;
const hasDisks = disks.length > 0;
const hasMultipleDisks = disks.length > 1;
const aggregateMode = props.mode === 'aggregate';
const summaryStrategy = props.summaryStrategy ?? 'total';
const miniMode = props.mode === 'mini';
const explicitStackedMode = props.mode === 'stacked';
const verticalBarsMode = props.mode === 'vertical-bars' && hasDisks;
const inlineDiskMode =
(miniMode || hasMultipleDisks) && !aggregateMode && !explicitStackedMode && !verticalBarsMode;
const useStackedSegments = hasMultipleDisks && explicitStackedMode;
const inlineDiskSlotWidth =
disks.length > 0
? (containerWidth - INLINE_DISK_SLOT_GAP_PX * (disks.length - 1)) / disks.length
: 0;
// The producer owns aggregate capacity (including device-alias admission).
// Mount rows are a breakdown, not an independently additive inventory.
// Keep their observations for severity/tooltips and the explicit max mode;
// only fall back to summing measured rows when no usable aggregate exists.
const useAggregateSummary = !unavailable && aggregateMode && hasAggregateUsage;
const summarizeDisks = hasDisks && !useAggregateSummary;
const totalCapacity = summarizeDisks
? disks.reduce((sum, disk) => sum + (disk.total || 0), 0)
: (aggregateDisk?.total ?? 0);
const totalUsed = summarizeDisks
? disks.reduce((sum, disk) => sum + (disk.used || 0), 0)
: (aggregateDisk?.used ?? 0);
const overallPercent = summarizeDisks
? (totalUsed / totalCapacity) * 100
: unavailable
? 0
: (aggregatePercent ?? 0);
const anomalyRatio = formatAnomalyRatio(anomaly) ?? '';
const maxInfo = getMaxDiskInfo(disks);
// A reported disk without a usable reading must not drop a multi-disk host
// back to its aggregate: the measured disk may be the one that is full.
const useMaxSummary =
aggregateMode && allDisks.length > 1 && summaryStrategy === 'max' && maxInfo !== null;
const displayPercentValue = useMaxSummary && maxInfo ? maxInfo.percent : overallPercent;
const barPercent = Math.min(displayPercentValue, 100);
const maxLabelShort = maxInfo
? useMaxSummary
? 'max'
: `max ${formatPercent(maxInfo.percent)}`
: '';
const maxLabelFull = maxInfo
? `${valuePrefix ? 'Last known highest' : 'Highest'} usage: ${maxInfo.label} ${formatPercent(maxInfo.percent)}`
: '';
const displayLabel = unavailable ? 'N/A' : formatPercent(displayPercentValue);
const displaySublabel =
unavailable ||
(useMaxSummary && maxInfo) ||
!Number.isFinite(totalUsed) ||
!Number.isFinite(totalCapacity) ||
totalCapacity <= 0 ||
(!summarizeDisks &&
!(
typeof aggregateDisk?.used === 'number' &&
Number.isFinite(aggregateDisk.used) &&
aggregateDisk.used >= 0 &&
totalCapacity > 0
))
? ''
: `${formatBytes(totalUsed)}/${formatBytes(totalCapacity)}`;
const diskCountLabel = hasMultipleDisks ? `${disks.length} disks` : '';
const diskCountTitle = hasMultipleDisks
? `${disks.length} ${current ? 'operational' : 'last known'} disks in breakdown`
: '';
const showDiskCount = Boolean(props.showDiskCount && hasMultipleDisks);
// The max marker is a hint, never worth clipping the percentage for: on a
// narrow cell it drops and the tooltip still names the fullest disk.
const showMaxLabel =
(useMaxSummary || (aggregateMode && hasMultipleDisks)) &&
maxLabelShort.length > 0 &&
containerWidth >=
estimateTextWidth(displayLabel, { detail: ` ${maxLabelShort}` }) + LABEL_PADDING_PX;
// The anomaly marker shares the label's line whenever it renders.
const anomalyMarker = anomaly?.description && anomalyRatio ? ` ${anomalyRatio}` : '';
const showSublabel =
displaySublabel.length > 0 &&
containerWidth >=
estimateTextWidth(`${displayLabel}${anomalyMarker}`, {
detail: `${showMaxLabel ? ` ${maxLabelShort}` : ''} (${displaySublabel})${
showDiskCount ? ` ${diskCountLabel}` : ''
}`,
}) +
LABEL_PADDING_PX;
const barColor = !current
? UNKNOWN_DISK_COLOR
: (useMaxSummary || (aggregateMode && hasMultipleDisks)) && maxInfo
? getMetricColorRgba(maxInfo.percent, 'disk', props.thresholds)
: getMetricColorRgba(overallPercent, 'disk', props.thresholds);
const segments =
useStackedSegments && totalCapacity > 0
? disks.map((disk, index) => {
const diskUsagePercent = getDiskUsagePercent(disk);
return {
color: current
? getStackedDiskColor(diskUsagePercent, index, props.thresholds)
: UNKNOWN_DISK_COLOR,
disk,
diskUsagePercent,
index,
widthPercent: Math.min(((disk.used ?? 0) / totalCapacity) * 100, 100),
};
})
: [];
const miniDisks = disks.map((disk, index) => {
const percent = getDiskUsagePercent(disk);
const label = getDiskLabel(disk, index);
const percentLabel = formatPercent(percent);
const shortLabel = getShortDiskLabel(label);
return {
color: current ? getMetricColorRgba(percent, 'disk', props.thresholds) : UNKNOWN_DISK_COLOR,
inlineText: getInlineDiskText(shortLabel, percentLabel, inlineDiskSlotWidth),
label,
percent,
percentLabel,
shortLabel,
title: `${valuePrefix}${label}: ${percentLabel} (${formatBytes(disk.used ?? 0)}/${formatBytes(disk.total ?? 0)})`,
};
});
const verticalBars: StackedDiskVerticalBar[] = verticalBarsMode
? disks.map((disk, index) => {
const percent = getDiskUsagePercent(disk);
const label = getDiskLabel(disk, index);
return {
color: current
? getMetricColorRgba(percent, 'disk', props.thresholds)
: UNKNOWN_DISK_COLOR,
fillPercent: Math.max(0, Math.min(percent, 100)),
title: `${valuePrefix}${label}: ${formatPercent(percent)} (${formatBytes(disk.used ?? 0)}/${formatBytes(disk.total ?? 0)})`,
};
})
: [];
const verticalBarsLabel = verticalBarsMode && maxInfo ? formatPercent(maxInfo.percent) : '';
const verticalBarsLabelTitle = verticalBarsMode && maxInfo ? maxLabelFull : '';
const tooltipContent = buildTooltipContent(allDisks, {
aggregateDisk: props.aggregateDisk,
aggregateMode,
current,
unavailable,
inlineDiskMode,
miniMode,
thresholds: props.thresholds,
verticalBarsMode,
});
return {
aggregateMode,
anomalyClass: anomaly
? (ANOMALY_SEVERITY_CLASS[anomaly.severity] ?? 'text-yellow-400')
: 'text-yellow-400',
anomalyDescription: anomaly?.description,
anomalyRatio,
barColor,
barPercent,
containerClass: verticalBarsMode
? 'metric-text w-full h-4 min-w-0'
: inlineDiskMode && hasDisks
? 'metric-text w-full h-4 min-w-0'
: 'metric-text w-full h-4 flex items-center justify-center',
diskCountLabel,
diskCountTitle,
displayLabel,
displayPercentValue,
displaySublabel,
hasDisks,
hasMultipleDisks,
inlineDiskMode,
maxLabelFull,
maxLabelShort,
miniDisks,
miniMode,
segments,
showDiskCount: useStackedSegments || showDiskCount,
showMaxLabel,
showSublabel,
tooltipContent,
tooltipTitle: valuePrefix
? `${valuePrefix}${allDisks.length > 1 ? 'disk breakdown' : 'disk usage'}`
: allDisks.length > 1
? 'Disk Breakdown'
: 'Disk Usage',
tooltipMessage: props.reading?.message ?? props.statusMessage,
unavailable,
useStackedSegments,
verticalBars,
verticalBarsLabel,
verticalBarsLabelTitle,
verticalBarsMode,
};
}