mirror of
https://github.com/rcourtman/Pulse.git
synced 2026-11-29 09:10:58 +01:00
Show when vSphere host and network readings are stale
Bring VMware vSphere ESXi hosts, networks, and inline detail drawers up
to parity with vSphere datastores and TrueNAS for stale-reading
freshness and truthful status:
- Prefer live top-level resource.sourceStatus.vmware over cached REST
platformData.sourceStatus so live WebSocket staleness and recovery
update hosts, VMs, datastores, networks, and inline drawers
immediately without reloading the page.
- Preserve severe failure states (offline, stopped, error, failed,
faulted, critical, unhealthy) instead of downgrading red danger dots
to amber degraded when vCenter polling is also stale or impaired, and
lead offline+stale network health text with "Last reported offline".
- Show a non-colour "Stale data" cue beneath stale ESXi host and network
names (including on 360px phone layouts where the network Health
column is hidden) while keeping retained CPU, memory, uptime, VM
counts, and host-scoping controls visible.
- Surface vCenter stale/collection-error details in inline vSphere
drawers via Worth checking ("Readings") and defer retained ESXi host
metrics above the history charts with last-known values preserved
until live polling recovers.
- Share the provider stale-notice builder with TrueNAS and consolidate
repeated vSphere/drawer mapping helpers so production Total JS stays
within the existing bundle budget.
Contract-Neutral: presentation-only frontend freshness cues and drawer notices on existing canonical resource sourceStatus fields without altering API or backend contracts
Change-source: pulse-maintainer
This commit is contained in:
62
frontend-modern/browser-verification/48e4e1e15ef7e9e8.json
Normal file
62
frontend-modern/browser-verification/48e4e1e15ef7e9e8.json
Normal file
@@ -0,0 +1,62 @@
|
||||
{
|
||||
"version": 1,
|
||||
"base_sha": "c1d36efb6fa647ec9677a70c41078a4d16f30f4b",
|
||||
"verified_at": "2026-11-27T06:40:35Z",
|
||||
"result": "passed",
|
||||
"changed_paths": [
|
||||
"frontend-modern/src/components/Infrastructure/resourceDetailDrawerMetricsHistoryModel.ts",
|
||||
"frontend-modern/src/components/Infrastructure/resourceDetailDrawerOperationalModel.ts",
|
||||
"frontend-modern/src/components/Infrastructure/resourceDetailDrawerVmwareModel.ts",
|
||||
"frontend-modern/src/components/Infrastructure/resourceDetailMappers.ts",
|
||||
"frontend-modern/src/components/Infrastructure/useResourceDetailDrawerDerivedState.ts",
|
||||
"frontend-modern/src/features/vmware/VmwarePageSurface.tsx",
|
||||
"frontend-modern/src/features/vmware/VsphereHostsTable.tsx",
|
||||
"frontend-modern/src/features/vmware/VsphereNetworksTable.tsx",
|
||||
"frontend-modern/src/features/vmware/vmwarePageModel.ts",
|
||||
"frontend-modern/src/utils/truenasDatasetState.ts",
|
||||
"frontend-modern/src/utils/vmwareDisplay.ts"
|
||||
],
|
||||
"content_sha256": {
|
||||
"frontend-modern/src/components/Infrastructure/resourceDetailDrawerMetricsHistoryModel.ts": "908cfdd98f224e2fc036d7aca5e14d4121bb4ffd0823cb7ea3df51e79ceb29f4",
|
||||
"frontend-modern/src/components/Infrastructure/resourceDetailDrawerOperationalModel.ts": "b0372daa5397c8ba2ef51a3f2b27d1901795f4eae66c1203e7831dcfbe4158ae",
|
||||
"frontend-modern/src/components/Infrastructure/resourceDetailDrawerVmwareModel.ts": "57fa06a078e5cbe6f1c35ee148f214f747b7c0cfdf1711e4b728a3ab240326b4",
|
||||
"frontend-modern/src/components/Infrastructure/resourceDetailMappers.ts": "a077e69076aef90d07a04590f94b57bdeb547612d092bb6fb8433d04a25418c4",
|
||||
"frontend-modern/src/components/Infrastructure/useResourceDetailDrawerDerivedState.ts": "9e375bcded981ae8866a3e43f4ee3fc8724f0d33a5895486112b8f807b3a7c71",
|
||||
"frontend-modern/src/features/vmware/VmwarePageSurface.tsx": "ac73716b7efd6ab779c02faa62b7bb8da86593f24357a1b7708f17a5ceb5ac7a",
|
||||
"frontend-modern/src/features/vmware/VsphereHostsTable.tsx": "c174f43ff214b212ed3228881530894a40e054cb677964734339b8606ff9cfd0",
|
||||
"frontend-modern/src/features/vmware/VsphereNetworksTable.tsx": "5f8a2573f4ff0539522ff00e9b3d91407cd0e0c4dbfa94075df12a91bb412dba",
|
||||
"frontend-modern/src/features/vmware/vmwarePageModel.ts": "4ed3eb2e49b6316098d1dd80cdd24c15f07dd0b41e202b9e7acc54887597fcbf",
|
||||
"frontend-modern/src/utils/truenasDatasetState.ts": "00eb02dbd8a720e544a2b84c5c672d03117f9377420763d8c9b1418523669253",
|
||||
"frontend-modern/src/utils/vmwareDisplay.ts": "b5a422705ee515611fb3a46b9b50898578522ce287e91bc59c3ad6c270e09510"
|
||||
},
|
||||
"routes": [
|
||||
"/vmware/overview",
|
||||
"/vmware/networks",
|
||||
"/vmware/storage",
|
||||
"/truenas/overview"
|
||||
],
|
||||
"viewports": [
|
||||
{
|
||||
"width": 1440,
|
||||
"height": 940
|
||||
},
|
||||
{
|
||||
"width": 360,
|
||||
"height": 820
|
||||
}
|
||||
],
|
||||
"states": [
|
||||
"paired production builds of base c1d36efb6fa6 (dist sha256 49a3a5c3aba5...) and candidate (dist sha256 904a27314625...) served over local HTTP/WebSocket fixture in Chromium 141.0.7390.37 (1440x940 light theme, en-GB, UTC) and WebKit 26.0 (360x820 mobile touch dark theme, en-GB, UTC)",
|
||||
"/vmware/overview with stale collection-error host esxi-edge-01.lab (43% CPU, 68% Memory), offline+stale host esxi-edge-02.lab, and fresh host esxi-core-01.lab: candidate adds non-colour 'Stale data' cues beneath both stale hosts while retaining CPU/Memory bars and uptime, preserves red danger dot on offline+stale esxi-edge-02.lab (base downgraded it to amber), lifts wrapped 'Readings: vCenter collection error: vCenter session expired (401)' into the inline drawer Worth checking banner, and shows deferred CPU and Memory reading notices above the UTILIZATION chart",
|
||||
"/vmware/overview live WebSocket recovery of esxi-edge-01.lab (sourceStatus.vmware online, CPU 27%, Memory 55%) while platformData.sourceStatus remains stale without page reload: base stayed stuck amber in both row and drawer header; candidate clears 'Stale data', restores green status dots in row and drawer header, removes Worth checking Readings and deferred chart notices, and updates CPU/Memory bars live",
|
||||
"/vmware/networks with stale collection-error Edge-Trunk-VLAN40, offline+stale Backup-VLAN99, and fresh VM-Prod-Network: candidate adds non-colour 'Stale data' cues on both desktop light and 360px dark phone (where Health column is hidden), leads Backup-VLAN99 Health with red 'Last reported offline +1' (base hid it behind 'vCenter has not updated this recently +1'), surfaces the specific vCenter error in Health and drawer Worth checking, and recovers Edge-Trunk-VLAN40 to green dot and Healthy 2 / Attention 1 on live WebSocket update without reload",
|
||||
"/vmware/storage stale datastore nvme-edge-01 and /truenas/overview stale system truenas-prod-01: datastore Stale data cue, inline CAPACITY deferred notice, and TrueNAS Stale data cue remain intact with zero console errors, zero page errors, zero failed requests, and 0px horizontal overflow across all routes and viewports"
|
||||
],
|
||||
"interactions": [
|
||||
"loaded /vmware/overview on desktop (1440x940 light) and touch phone (360x820 dark), verified stale and offline+stale ESXi host rows, and expanded esxi-edge-01.lab inline drawer via its chevron toggle button",
|
||||
"delivered a live WebSocket rawData recovery frame for esxi-edge-01.lab while platformData.sourceStatus remained stale without reloading and verified immediate row, status dot, drawer Worth checking, and UTILIZATION chart recovery",
|
||||
"loaded /vmware/networks on desktop and phone, verified stale and offline+stale network rows, expanded Edge-Trunk-VLAN40 inline drawer, and delivered a live WebSocket rawData recovery frame verifying Healthy chip count, green dot, and drawer clearance without reload",
|
||||
"loaded /vmware/storage and expanded nvme-edge-01 inline drawer to confirm datastore stale cue and CAPACITY deferred notice parity",
|
||||
"loaded /truenas/overview on desktop and phone to confirm shared stale-notice helper preserves TrueNAS Stale data cue"
|
||||
]
|
||||
}
|
||||
@@ -57,6 +57,45 @@ describe('vSphere datastore History capacity provenance', () => {
|
||||
expect(getResourceMetricsHistoryCurrentMetrics(unrelated).usage).toBe(78.125);
|
||||
expect(getResourceMetricsHistoryDeferredMetrics(unrelated).usage).toBeUndefined();
|
||||
});
|
||||
|
||||
it('defers retained ESXi host metrics while vCenter is stale and restores live readings on recovery', () => {
|
||||
const staleHost = baseResource({
|
||||
id: 'esxi-01',
|
||||
type: 'agent',
|
||||
platformType: 'vmware-vsphere',
|
||||
sourceStatus: { vmware: { status: 'stale' } },
|
||||
cpu: { current: 42 },
|
||||
memory: { current: 64, used: 64, total: 100 },
|
||||
network: { rxBytes: 1200, txBytes: 800 },
|
||||
});
|
||||
|
||||
expect(getResourceMetricsHistoryCurrentMetrics(staleHost)).toMatchObject({
|
||||
cpu: undefined,
|
||||
memory: undefined,
|
||||
netin: undefined,
|
||||
netout: undefined,
|
||||
});
|
||||
expect(getResourceMetricsHistoryDeferredMetrics(staleHost)).toMatchObject({
|
||||
cpu: { lastKnownValue: 42, message: 'vCenter has not updated this host recently.' },
|
||||
memory: { lastKnownValue: 64, message: 'vCenter has not updated this host recently.' },
|
||||
netin: { lastKnownValue: 1200, message: 'vCenter has not updated this host recently.' },
|
||||
netout: { lastKnownValue: 800, message: 'vCenter has not updated this host recently.' },
|
||||
});
|
||||
|
||||
const recoveredHost = {
|
||||
...staleHost,
|
||||
sourceStatus: { vmware: { status: 'online' } },
|
||||
platformData: { sourceStatus: staleHost.sourceStatus },
|
||||
};
|
||||
expect(getResourceMetricsHistoryCurrentMetrics(recoveredHost)).toMatchObject({
|
||||
cpu: 42,
|
||||
memory: 64,
|
||||
netin: 1200,
|
||||
netout: 800,
|
||||
});
|
||||
expect(getResourceMetricsHistoryDeferredMetrics(recoveredHost).cpu).toBeUndefined();
|
||||
expect(getResourceMetricsHistoryDeferredMetrics(recoveredHost).memory).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('canonical drawer History honours selected guest observation provenance', () => {
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
buildVMwareDetailSections,
|
||||
buildVMwareDetailsSummary,
|
||||
} from '@/components/Infrastructure/resourceDetailDrawerVmwareModel';
|
||||
import type { ResourceVMwareMeta } from '@/types/resource';
|
||||
import type { Resource, ResourceVMwareMeta } from '@/types/resource';
|
||||
|
||||
const findSection = (sections: ReturnType<typeof buildVMwareDetailSections>, label: string) =>
|
||||
sections.find((section) => section.label === label);
|
||||
@@ -281,4 +281,44 @@ describe('resourceDetailDrawerVmwareModel', () => {
|
||||
running.flatMap((section) => section.rows).find((row) => row.label === 'Run state')?.tone,
|
||||
).toBe('warning');
|
||||
});
|
||||
|
||||
it('lifts a Readings warning when vCenter is stale and clears it on live recovery', () => {
|
||||
const vmware: ResourceVMwareMeta = {
|
||||
connectionName: 'Lab VC',
|
||||
entityType: 'host',
|
||||
overallStatus: 'green',
|
||||
};
|
||||
const staleHost = {
|
||||
id: 'esxi-01',
|
||||
type: 'agent',
|
||||
name: 'esxi-01',
|
||||
displayName: 'esxi-01',
|
||||
platformId: 'vmware-1',
|
||||
platformType: 'vmware-vsphere',
|
||||
sourceType: 'api',
|
||||
status: 'online',
|
||||
lastSeen: 1_700_000_000_000,
|
||||
sourceStatus: { vmware: { status: 'error', error: 'vCenter API timeout' } },
|
||||
vmware,
|
||||
} as Resource;
|
||||
|
||||
const staleState = findSection(buildVMwareDetailSections('agent', vmware, staleHost), 'State');
|
||||
expect(staleState?.rows[0]).toEqual({
|
||||
label: 'Readings',
|
||||
value: 'vCenter collection error: vCenter API timeout',
|
||||
tone: 'warning',
|
||||
wrap: true,
|
||||
});
|
||||
|
||||
const recoveredHost: Resource = {
|
||||
...staleHost,
|
||||
sourceStatus: { vmware: { status: 'online' } },
|
||||
platformData: { sourceStatus: staleHost.sourceStatus },
|
||||
};
|
||||
const recoveredState = findSection(
|
||||
buildVMwareDetailSections('agent', vmware, recoveredHost),
|
||||
'State',
|
||||
);
|
||||
expect(recoveredState?.rows.find((row) => row.label === 'Readings')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
getAgentFirstReportStatusIndicator,
|
||||
isTrueNASSystemResource,
|
||||
} from '@/utils/agentResources';
|
||||
import { getVmwareStaleNotice } from '@/utils/vmwareDisplay';
|
||||
|
||||
const finiteMetric = (value: number | undefined): number | undefined =>
|
||||
typeof value === 'number' && Number.isFinite(value) ? value : undefined;
|
||||
@@ -226,8 +227,21 @@ const resourceTemperature = (resource: Resource): number | undefined =>
|
||||
const isResourceTemperatureCurrent = (resource: Resource): boolean =>
|
||||
isPhysicalDiskTemperatureCurrent(resource.physicalDisk?.collection);
|
||||
|
||||
const hasRetainedVcenterCapacity = (resource: Resource): boolean =>
|
||||
resource.type === 'storage' && resource.sourceStatus?.vmware?.status === 'stale';
|
||||
const getRetainedVcenterReading = (resource: Resource) => {
|
||||
const isHost =
|
||||
resource.type === 'agent' &&
|
||||
(resource.platformType === 'vmware-vsphere' || Boolean(resource.vmware));
|
||||
if (!isHost && resource.type !== 'storage') return null;
|
||||
const stale = getVmwareStaleNotice(resource);
|
||||
return stale
|
||||
? {
|
||||
isHost,
|
||||
message: stale.error
|
||||
? `${stale.detail}.`
|
||||
: `vCenter has not updated this ${isHost ? 'host' : 'datastore'} recently.`,
|
||||
}
|
||||
: null;
|
||||
};
|
||||
|
||||
export const getResourceMetricsHistoryDeferredMetrics = (
|
||||
resource: Resource,
|
||||
@@ -252,11 +266,25 @@ export const getResourceMetricsHistoryDeferredMetrics = (
|
||||
message: disk.message,
|
||||
};
|
||||
}
|
||||
if (hasRetainedVcenterCapacity(resource)) {
|
||||
metrics.usage = {
|
||||
lastKnownValue: finiteMetric(getDiskPercent(resource)),
|
||||
message: 'vCenter has not updated this datastore recently.',
|
||||
};
|
||||
const retainedVcenter = getRetainedVcenterReading(resource);
|
||||
if (retainedVcenter) {
|
||||
const { isHost, message } = retainedVcenter;
|
||||
if (isHost) {
|
||||
for (const [metric, lastKnownValue] of Object.entries({
|
||||
cpu: finiteMetric(resource.cpu?.current),
|
||||
memory: resource.memory ? finiteMetric(getMemoryPercent(resource)) : undefined,
|
||||
netin: finiteMetric(resource.network?.rxBytes),
|
||||
netout: finiteMetric(resource.network?.txBytes),
|
||||
diskread: finiteMetric(resource.diskIO?.readRate),
|
||||
diskwrite: finiteMetric(resource.diskIO?.writeRate),
|
||||
})) {
|
||||
if (metric === 'cpu' || metric === 'memory' || lastKnownValue !== undefined) {
|
||||
metrics[metric] = { lastKnownValue, message };
|
||||
}
|
||||
}
|
||||
} else {
|
||||
metrics.usage = { lastKnownValue: finiteMetric(getDiskPercent(resource)), message };
|
||||
}
|
||||
}
|
||||
if (!isResourceTemperatureCurrent(resource)) {
|
||||
const temperature = resourceTemperature(resource);
|
||||
@@ -278,6 +306,8 @@ export const getResourceMetricsHistoryCurrentMetrics = (
|
||||
resource: Resource,
|
||||
): Record<string, number | undefined> => {
|
||||
if (getAgentFirstReportStatusIndicator(resource)) return {};
|
||||
const retainedVcenter = getRetainedVcenterReading(resource);
|
||||
const hideHost = retainedVcenter?.isHost === true;
|
||||
const disk = guestDiskReading(resource);
|
||||
const diskPercent =
|
||||
resource.disk && (!disk || disk.state === 'current')
|
||||
@@ -288,17 +318,17 @@ export const getResourceMetricsHistoryCurrentMetrics = (
|
||||
: undefined;
|
||||
const memory = memoryReading(resource);
|
||||
return {
|
||||
cpu: finiteMetric(resource.cpu?.current),
|
||||
cpu: hideHost ? undefined : finiteMetric(resource.cpu?.current),
|
||||
memory:
|
||||
resource.memory && (!memory || memory.state === 'current')
|
||||
!hideHost && resource.memory && (!memory || memory.state === 'current')
|
||||
? finiteMetric(getMemoryPercent(resource))
|
||||
: undefined,
|
||||
disk: diskPercent,
|
||||
usage: hasRetainedVcenterCapacity(resource) ? undefined : diskPercent,
|
||||
netin: finiteMetric(resource.network?.rxBytes),
|
||||
netout: finiteMetric(resource.network?.txBytes),
|
||||
diskread: finiteMetric(resource.diskIO?.readRate),
|
||||
diskwrite: finiteMetric(resource.diskIO?.writeRate),
|
||||
usage: retainedVcenter && !hideHost ? undefined : diskPercent,
|
||||
netin: hideHost ? undefined : finiteMetric(resource.network?.rxBytes),
|
||||
netout: hideHost ? undefined : finiteMetric(resource.network?.txBytes),
|
||||
diskread: hideHost ? undefined : finiteMetric(resource.diskIO?.readRate),
|
||||
diskwrite: hideHost ? undefined : finiteMetric(resource.diskIO?.writeRate),
|
||||
temperature,
|
||||
smart_temp: temperature,
|
||||
gpu: getResourceGPUUtilizationPercent(resource),
|
||||
|
||||
@@ -23,93 +23,63 @@ const SUPPORTED_BADGE_CLASS =
|
||||
const UNSUPPORTED_BADGE_CLASS =
|
||||
'inline-flex items-center rounded-sm px-2 py-0.5 text-[10px] font-medium whitespace-nowrap bg-surface-alt text-muted';
|
||||
|
||||
const K8S_CAPABILITY_SPECS: ReadonlyArray<
|
||||
readonly [keyof KubernetesMetricCapabilities, boolean, string, string]
|
||||
> = [
|
||||
['nodeCpuMemory', true, 'K8s Node CPU/Memory', 'Node CPU and memory metrics are available.'],
|
||||
[
|
||||
'nodeTelemetry',
|
||||
true,
|
||||
'Node Telemetry (Agent)',
|
||||
'Linked Pulse agent provides node uptime, temperature, disk, network, and disk I/O.',
|
||||
],
|
||||
['podCpuMemory', true, 'Pod CPU/Memory', 'Pod CPU and memory metrics are available.'],
|
||||
['podNetwork', true, 'Pod Network', 'Pod network throughput is available.'],
|
||||
['podEphemeralDisk', true, 'Pod Ephemeral Disk', 'Pod ephemeral storage usage is available.'],
|
||||
[
|
||||
'podDiskIo',
|
||||
false,
|
||||
'Pod Disk I/O Unsupported',
|
||||
'Pod disk read/write throughput is not collected by the Kubernetes integration path today.',
|
||||
],
|
||||
];
|
||||
|
||||
export const buildKubernetesCapabilityBadges = (
|
||||
capabilities?: KubernetesMetricCapabilities,
|
||||
): ResourceDetailDrawerOperationalBadge[] => {
|
||||
if (!capabilities) return [];
|
||||
|
||||
const badges: ResourceDetailDrawerOperationalBadge[] = [];
|
||||
|
||||
if (capabilities.nodeCpuMemory) {
|
||||
badges.push({
|
||||
label: 'K8s Node CPU/Memory',
|
||||
classes: SUPPORTED_BADGE_CLASS,
|
||||
title: 'Node CPU and memory metrics are available.',
|
||||
});
|
||||
}
|
||||
if (capabilities.nodeTelemetry) {
|
||||
badges.push({
|
||||
label: 'Node Telemetry (Agent)',
|
||||
classes: SUPPORTED_BADGE_CLASS,
|
||||
title: 'Linked Pulse agent provides node uptime, temperature, disk, network, and disk I/O.',
|
||||
});
|
||||
}
|
||||
if (capabilities.podCpuMemory) {
|
||||
badges.push({
|
||||
label: 'Pod CPU/Memory',
|
||||
classes: SUPPORTED_BADGE_CLASS,
|
||||
title: 'Pod CPU and memory metrics are available.',
|
||||
});
|
||||
}
|
||||
if (capabilities.podNetwork) {
|
||||
badges.push({
|
||||
label: 'Pod Network',
|
||||
classes: SUPPORTED_BADGE_CLASS,
|
||||
title: 'Pod network throughput is available.',
|
||||
});
|
||||
}
|
||||
if (capabilities.podEphemeralDisk) {
|
||||
badges.push({
|
||||
label: 'Pod Ephemeral Disk',
|
||||
classes: SUPPORTED_BADGE_CLASS,
|
||||
title: 'Pod ephemeral storage usage is available.',
|
||||
});
|
||||
}
|
||||
if (!capabilities.podDiskIo) {
|
||||
badges.push({
|
||||
label: 'Pod Disk I/O Unsupported',
|
||||
classes: UNSUPPORTED_BADGE_CLASS,
|
||||
title:
|
||||
'Pod disk read/write throughput is not collected by the Kubernetes integration path today.',
|
||||
});
|
||||
}
|
||||
|
||||
return badges;
|
||||
};
|
||||
): ResourceDetailDrawerOperationalBadge[] =>
|
||||
capabilities
|
||||
? K8S_CAPABILITY_SPECS.filter(
|
||||
([key, expectTrue]) => Boolean(capabilities[key]) === expectTrue,
|
||||
).map(([, expectTrue, label, title]) => ({
|
||||
label,
|
||||
classes: expectTrue ? SUPPORTED_BADGE_CLASS : UNSUPPORTED_BADGE_CLASS,
|
||||
title,
|
||||
}))
|
||||
: [];
|
||||
|
||||
export const buildSourceHealthSummary = (
|
||||
sourceStatus: SourceStatusMap,
|
||||
): ResourceDetailDrawerSummary | null => {
|
||||
const entries = Object.entries(sourceStatus);
|
||||
if (entries.length === 0) return null;
|
||||
|
||||
if (!entries.length) return null;
|
||||
let warning = 0;
|
||||
let unhealthy = 0;
|
||||
const parts: string[] = [];
|
||||
|
||||
for (const [source, status] of entries) {
|
||||
const parts = entries.map(([source, status]) => {
|
||||
const normalized = (status?.status || '').trim().toLowerCase();
|
||||
parts.push(`${source}:${normalized || 'unknown'}`);
|
||||
if (['online', 'running', 'healthy', 'connected', 'ok'].includes(normalized)) {
|
||||
continue;
|
||||
} else if (['degraded', 'warning', 'stale'].includes(normalized)) {
|
||||
warning += 1;
|
||||
} else {
|
||||
unhealthy += 1;
|
||||
}
|
||||
}
|
||||
|
||||
const total = entries.length;
|
||||
if (/^(degraded|warning|stale)$/.test(normalized)) warning += 1;
|
||||
else if (!/^(online|running|healthy|connected|ok)$/.test(normalized)) unhealthy += 1;
|
||||
return `${source}:${normalized || 'unknown'}`;
|
||||
});
|
||||
if (unhealthy > 0) {
|
||||
return {
|
||||
label: `${unhealthy}/${total} unhealthy`,
|
||||
label: `${unhealthy}/${entries.length} unhealthy`,
|
||||
className: 'text-red-600 dark:text-red-400',
|
||||
title: parts.join(' • '),
|
||||
};
|
||||
}
|
||||
if (warning > 0) {
|
||||
return {
|
||||
label: `${warning}/${total} degraded`,
|
||||
label: `${warning}/${entries.length} degraded`,
|
||||
className: 'text-amber-600 dark:text-amber-400',
|
||||
title: parts.join(' • '),
|
||||
};
|
||||
@@ -120,11 +90,7 @@ export const buildSourceHealthSummary = (
|
||||
export const buildSourceSummary = (
|
||||
_mergedSources: string[],
|
||||
sourceStatus: SourceStatusMap,
|
||||
): ResourceDetailDrawerSummary | null => {
|
||||
const health = buildSourceHealthSummary(sourceStatus);
|
||||
if (health) return health;
|
||||
return null;
|
||||
};
|
||||
): ResourceDetailDrawerSummary | null => buildSourceHealthSummary(sourceStatus);
|
||||
|
||||
export const buildHostDetailCards = (options: {
|
||||
hasProxmoxNode: boolean;
|
||||
@@ -156,27 +122,13 @@ export const buildHostDetailCards = (options: {
|
||||
};
|
||||
|
||||
export const buildHostDetailSummary = (hostDetailCards: string[]): string | null => {
|
||||
const labels = Array.from(new Set(hostDetailCards));
|
||||
const labels = Array.from(new Set(hostDetailCards), (label) =>
|
||||
label === 'raid' ? 'RAID' : label.charAt(0).toUpperCase() + label.slice(1),
|
||||
);
|
||||
if (labels.length === 0) return null;
|
||||
const presentation: Record<string, string> = {
|
||||
system: 'System',
|
||||
hardware: 'Hardware',
|
||||
storage: 'Storage',
|
||||
network: 'Network',
|
||||
disks: 'Disks',
|
||||
raid: 'RAID',
|
||||
temperatures: 'Temperatures',
|
||||
};
|
||||
const displayLabels = labels.map((label) => presentation[label] ?? label);
|
||||
|
||||
const categories =
|
||||
displayLabels.length === 1
|
||||
? displayLabels[0]
|
||||
: displayLabels.length === 2
|
||||
? `${displayLabels[0]} and ${displayLabels[1]}`
|
||||
: `${displayLabels.slice(0, -1).join(', ')}, and ${displayLabels[displayLabels.length - 1]}`;
|
||||
|
||||
return categories;
|
||||
return labels.length <= 2
|
||||
? labels.join(' and ')
|
||||
: `${labels.slice(0, -1).join(', ')}, and ${labels[labels.length - 1]}`;
|
||||
};
|
||||
|
||||
export const buildAccessSummary = (options: {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type {
|
||||
Resource,
|
||||
ResourceType,
|
||||
ResourceVMwareHardware,
|
||||
ResourceVMwareMeta,
|
||||
@@ -7,7 +8,7 @@ import type {
|
||||
ResourceVMwareTools,
|
||||
ResourceVMwareVirtualDisk,
|
||||
} from '@/types/resource';
|
||||
import { formatVmwareClusterServices } from '@/utils/vmwareDisplay';
|
||||
import { formatVmwareClusterServices, getVmwareStaleNotice } from '@/utils/vmwareDisplay';
|
||||
import {
|
||||
compactDetailRows as compactRows,
|
||||
compactDetailSections as compactSections,
|
||||
@@ -32,34 +33,20 @@ const wrapRow = (
|
||||
// Tools and vNIC state only mean something while the VM runs: a powered-off
|
||||
// VM has no running Tools and no connected adapters by design. Without a
|
||||
// reported power state the readings are taken at face value.
|
||||
const isPoweredOff = (vmware?: ResourceVMwareMeta): boolean => {
|
||||
const state = asTrimmedString(vmware?.powerState)
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z]/g, '');
|
||||
return state === 'poweredoff' || state === 'suspended' || state === 'off';
|
||||
};
|
||||
const isPoweredOff = (vmware?: ResourceVMwareMeta): boolean =>
|
||||
/^(poweredoff|suspended|off)$/.test(
|
||||
asTrimmedString(vmware?.powerState)
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z]/g, ''),
|
||||
);
|
||||
|
||||
const summarizeList = (values: string[] | undefined): string =>
|
||||
(values ?? []).map(asTrimmedString).filter(Boolean).join(', ');
|
||||
|
||||
const formatBoolLabel = (value?: boolean): string => {
|
||||
if (value === undefined) return '';
|
||||
return value ? 'Yes' : 'No';
|
||||
};
|
||||
const formatBoolLabel = (value?: boolean): string =>
|
||||
value === undefined ? '' : value ? 'Yes' : 'No';
|
||||
|
||||
const VMWARE_ENUM_ACRONYMS: Record<string, string> = {
|
||||
API: 'API',
|
||||
BIOS: 'BIOS',
|
||||
CPU: 'CPU',
|
||||
IP: 'IP',
|
||||
OS: 'OS',
|
||||
VM: 'VM',
|
||||
VMDK: 'VMDK',
|
||||
VMX: 'VMX',
|
||||
EFI: 'EFI',
|
||||
IPV4: 'IPv4',
|
||||
IPV6: 'IPv6',
|
||||
};
|
||||
const VMWARE_ENUM_ACRONYM = /^(API|BIOS|CPU|EFI|IP|OS|VM|VMDK|VMX)$/;
|
||||
|
||||
const formatEnumLabel = (value?: string | null): string => {
|
||||
const normalized = asTrimmedString(value);
|
||||
@@ -69,23 +56,22 @@ const formatEnumLabel = (value?: string | null): string => {
|
||||
.filter(Boolean)
|
||||
.map((part) => {
|
||||
const upper = part.toUpperCase();
|
||||
return (
|
||||
VMWARE_ENUM_ACRONYMS[upper] ?? part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()
|
||||
);
|
||||
if (upper === 'IPV4' || upper === 'IPV6') return `IPv${upper.slice(3)}`;
|
||||
return VMWARE_ENUM_ACRONYM.test(upper)
|
||||
? upper
|
||||
: part.charAt(0).toUpperCase() + part.slice(1).toLowerCase();
|
||||
})
|
||||
.join(' ');
|
||||
};
|
||||
|
||||
const formatMiB = (value?: number): string => {
|
||||
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) return '';
|
||||
return (
|
||||
formatDetailBytesValue(value * 1024 * 1024, {
|
||||
allowZero: true,
|
||||
precision: 'compact',
|
||||
trimWhole: true,
|
||||
}) ?? ''
|
||||
);
|
||||
};
|
||||
const formatMiB = (value?: number): string =>
|
||||
typeof value === 'number' && Number.isFinite(value) && value >= 0
|
||||
? (formatDetailBytesValue(value * 1024 * 1024, {
|
||||
allowZero: true,
|
||||
precision: 'compact',
|
||||
trimWhole: true,
|
||||
}) ?? '')
|
||||
: '';
|
||||
|
||||
const countSnapshotTree = (snapshots?: ResourceVMwareSnapshot[]): number =>
|
||||
(snapshots ?? []).reduce(
|
||||
@@ -93,30 +79,12 @@ const countSnapshotTree = (snapshots?: ResourceVMwareSnapshot[]): number =>
|
||||
0,
|
||||
);
|
||||
|
||||
const snapshotDisplayName = (snapshot: ResourceVMwareSnapshot): string =>
|
||||
asTrimmedString(snapshot.name) ||
|
||||
asTrimmedString(snapshot.snapshot) ||
|
||||
(typeof snapshot.id === 'number' ? `Snapshot ${snapshot.id}` : 'Snapshot');
|
||||
|
||||
const formatSnapshotDate = (value?: string | number): string => {
|
||||
if (value === undefined || value === null || value === '') return '';
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return asTrimmedString(String(value));
|
||||
const pad = (part: number) => String(part).padStart(2, '0');
|
||||
return `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(
|
||||
date.getUTCDate(),
|
||||
)} ${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())} UTC`;
|
||||
};
|
||||
|
||||
const snapshotValue = (snapshot: ResourceVMwareSnapshot): string => {
|
||||
const parts = [
|
||||
snapshot.current ? 'current' : '',
|
||||
asTrimmedString(snapshot.state),
|
||||
formatSnapshotDate(snapshot.createdAt),
|
||||
snapshot.quiesced === undefined ? '' : snapshot.quiesced ? 'quiesced' : 'not quiesced',
|
||||
asTrimmedString(snapshot.description),
|
||||
].filter(Boolean);
|
||||
return parts.join(' · ');
|
||||
return Number.isNaN(date.getTime())
|
||||
? asTrimmedString(String(value))
|
||||
: `${date.toISOString().slice(0, 16).replace('T', ' ')} UTC`;
|
||||
};
|
||||
|
||||
const flattenSnapshotRows = (
|
||||
@@ -125,9 +93,22 @@ const flattenSnapshotRows = (
|
||||
): DetailRow[] => {
|
||||
const rows: DetailRow[] = [];
|
||||
for (const snapshot of snapshots ?? []) {
|
||||
const name =
|
||||
asTrimmedString(snapshot.name) ||
|
||||
asTrimmedString(snapshot.snapshot) ||
|
||||
(typeof snapshot.id === 'number' ? `Snapshot ${snapshot.id}` : 'Snapshot');
|
||||
const value = [
|
||||
snapshot.current ? 'current' : '',
|
||||
asTrimmedString(snapshot.state),
|
||||
formatSnapshotDate(snapshot.createdAt),
|
||||
snapshot.quiesced === undefined ? '' : snapshot.quiesced ? 'quiesced' : 'not quiesced',
|
||||
asTrimmedString(snapshot.description),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ');
|
||||
const snapshotRow = wrapRow(
|
||||
`${depth > 0 ? `${'-'.repeat(depth)} ` : ''}${snapshotDisplayName(snapshot)}`,
|
||||
snapshotValue(snapshot) || asTrimmedString(snapshot.snapshot),
|
||||
`${depth > 0 ? `${'-'.repeat(depth)} ` : ''}${name}`,
|
||||
value || asTrimmedString(snapshot.snapshot),
|
||||
{ tone: snapshot.current ? 'accent' : 'default' },
|
||||
);
|
||||
if (snapshotRow) rows.push(snapshotRow);
|
||||
@@ -136,59 +117,48 @@ const flattenSnapshotRows = (
|
||||
return rows;
|
||||
};
|
||||
|
||||
const adapterDisplayName = (adapter: ResourceVMwareNetworkAdapter): string =>
|
||||
asTrimmedString(adapter.label) ||
|
||||
asTrimmedString(adapter.nic) ||
|
||||
asTrimmedString(adapter.macAddress) ||
|
||||
'Network adapter';
|
||||
|
||||
const adapterNetworkName = (adapter: ResourceVMwareNetworkAdapter): string =>
|
||||
asTrimmedString(adapter.networkName) ||
|
||||
asTrimmedString(adapter.networkId) ||
|
||||
asTrimmedString(adapter.opaqueNetworkId) ||
|
||||
asTrimmedString(adapter.hostDevice) ||
|
||||
asTrimmedString(adapter.backingType);
|
||||
|
||||
const adapterConnectionLabel = (adapter: ResourceVMwareNetworkAdapter): string => {
|
||||
const parts = [
|
||||
asTrimmedString(adapter.state),
|
||||
adapter.startConnected === undefined
|
||||
? ''
|
||||
: adapter.startConnected
|
||||
? 'starts connected'
|
||||
: 'does not start connected',
|
||||
adapter.allowGuestControl === undefined
|
||||
? ''
|
||||
: adapter.allowGuestControl
|
||||
? 'guest control'
|
||||
: 'no guest control',
|
||||
].filter(Boolean);
|
||||
return parts.join(' · ');
|
||||
};
|
||||
|
||||
const adapterValue = (adapter: ResourceVMwareNetworkAdapter): string => {
|
||||
const parts = [
|
||||
asTrimmedString(adapter.type),
|
||||
adapterNetworkName(adapter),
|
||||
asTrimmedString(adapter.macAddress),
|
||||
adapterConnectionLabel(adapter),
|
||||
].filter(Boolean);
|
||||
return parts.join(' · ');
|
||||
};
|
||||
|
||||
const adapterTone = (adapter: ResourceVMwareNetworkAdapter): DetailValueTone =>
|
||||
asTrimmedString(adapter.state).toLowerCase() === 'not_connected' ? 'warning' : 'default';
|
||||
|
||||
const networkAdapterRows = (
|
||||
adapters: ResourceVMwareNetworkAdapter[] | undefined,
|
||||
poweredOff: boolean,
|
||||
): DetailRow[] =>
|
||||
compactRows(
|
||||
(adapters ?? []).map((adapter) =>
|
||||
wrapRow(adapterDisplayName(adapter), adapterValue(adapter), {
|
||||
tone: poweredOff ? 'default' : adapterTone(adapter),
|
||||
}),
|
||||
),
|
||||
(adapters ?? []).map((adapter) => {
|
||||
const label =
|
||||
asTrimmedString(adapter.label) ||
|
||||
asTrimmedString(adapter.nic) ||
|
||||
asTrimmedString(adapter.macAddress) ||
|
||||
'Network adapter';
|
||||
const network =
|
||||
asTrimmedString(adapter.networkName) ||
|
||||
asTrimmedString(adapter.networkId) ||
|
||||
asTrimmedString(adapter.opaqueNetworkId) ||
|
||||
asTrimmedString(adapter.hostDevice) ||
|
||||
asTrimmedString(adapter.backingType);
|
||||
const value = [
|
||||
asTrimmedString(adapter.type),
|
||||
network,
|
||||
asTrimmedString(adapter.macAddress),
|
||||
asTrimmedString(adapter.state),
|
||||
adapter.startConnected === undefined
|
||||
? ''
|
||||
: adapter.startConnected
|
||||
? 'starts connected'
|
||||
: 'does not start connected',
|
||||
adapter.allowGuestControl === undefined
|
||||
? ''
|
||||
: adapter.allowGuestControl
|
||||
? 'guest control'
|
||||
: 'no guest control',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ');
|
||||
return wrapRow(label, value, {
|
||||
tone:
|
||||
!poweredOff && asTrimmedString(adapter.state).toLowerCase() === 'not_connected'
|
||||
? 'warning'
|
||||
: 'default',
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const getWarningTone = (hasWarning: boolean): DetailValueTone =>
|
||||
@@ -197,62 +167,38 @@ const getWarningTone = (hasWarning: boolean): DetailValueTone =>
|
||||
const hardwareSummary = (hardware?: ResourceVMwareHardware): string => {
|
||||
if (!hardware) return '';
|
||||
const upgradeStatus = asTrimmedString(hardware.upgradeStatus);
|
||||
if (upgradeStatus && !['NONE', 'OK'].includes(upgradeStatus.toUpperCase())) {
|
||||
return `Hardware ${formatEnumLabel(upgradeStatus).toLowerCase()}`;
|
||||
}
|
||||
return formatEnumLabel(hardware.version);
|
||||
return upgradeStatus && !['NONE', 'OK'].includes(upgradeStatus.toUpperCase())
|
||||
? `Hardware ${formatEnumLabel(upgradeStatus).toLowerCase()}`
|
||||
: formatEnumLabel(hardware.version);
|
||||
};
|
||||
|
||||
const cpuTopologyLabel = (vmware: ResourceVMwareMeta): string => {
|
||||
const parts = [];
|
||||
if (
|
||||
typeof vmware.cpuCount === 'number' &&
|
||||
Number.isFinite(vmware.cpuCount) &&
|
||||
vmware.cpuCount > 0
|
||||
) {
|
||||
parts.push(`${vmware.cpuCount} vCPU`);
|
||||
}
|
||||
if (
|
||||
typeof vmware.hardware?.cpuCoresPerSocket === 'number' &&
|
||||
Number.isFinite(vmware.hardware.cpuCoresPerSocket) &&
|
||||
vmware.hardware.cpuCoresPerSocket > 0
|
||||
) {
|
||||
parts.push(`${vmware.hardware.cpuCoresPerSocket} cores/socket`);
|
||||
}
|
||||
return parts.join(' · ');
|
||||
};
|
||||
const posNum = (value?: number): number | undefined =>
|
||||
typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined;
|
||||
|
||||
const hardwareRows = (vmware?: ResourceVMwareMeta): DetailRow[] => {
|
||||
if (!vmware?.hardware) return [];
|
||||
const hardware = vmware.hardware;
|
||||
const hardware = vmware?.hardware;
|
||||
if (!hardware) return [];
|
||||
const upgradeStatus = asTrimmedString(hardware.upgradeStatus).toUpperCase();
|
||||
const upgradeAttention = Boolean(upgradeStatus) && !['NONE', 'OK'].includes(upgradeStatus);
|
||||
const cpuTopology = [
|
||||
posNum(vmware.cpuCount) ? `${vmware.cpuCount} vCPU` : '',
|
||||
posNum(hardware.cpuCoresPerSocket) ? `${hardware.cpuCoresPerSocket} cores/socket` : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ');
|
||||
return compactRows([
|
||||
makeRow('Guest OS', formatEnumLabel(hardware.guestOs)),
|
||||
makeRow('Hardware version', formatEnumLabel(hardware.version)),
|
||||
makeRow('CPU topology', cpuTopologyLabel(vmware)),
|
||||
makeRow('Memory size', formatMiB(vmware?.memorySizeMib)),
|
||||
// Upgrade and clone status only surface when something is actionable;
|
||||
// when everything is in the default state these rows resolve to empty
|
||||
// strings and compactRows drops them. Capability toggles
|
||||
// (CPU/memory hot-add, boot config) live in the raw API and stay out
|
||||
// of the operator drawer because they don't change minute to minute
|
||||
// and operators don't act on them from Pulse.
|
||||
makeRow('CPU topology', cpuTopology),
|
||||
makeRow('Memory size', formatMiB(vmware.memorySizeMib)),
|
||||
makeRow('Upgrade status', upgradeAttention ? formatEnumLabel(hardware.upgradeStatus) : '', {
|
||||
tone: getWarningTone(upgradeAttention),
|
||||
}),
|
||||
makeRow('Upgrade error', asTrimmedString(hardware.upgradeErrorMessage), {
|
||||
tone: 'warning',
|
||||
wrap: true,
|
||||
wrapRow('Upgrade error', asTrimmedString(hardware.upgradeErrorMessage), { tone: 'warning' }),
|
||||
makeRow('Instant clone frozen', hardware.instantCloneFrozen ? 'Yes' : '', {
|
||||
tone: getWarningTone(hardware.instantCloneFrozen === true),
|
||||
}),
|
||||
makeRow(
|
||||
'Instant clone frozen',
|
||||
hardware.instantCloneFrozen === true ? formatBoolLabel(true) : '',
|
||||
{
|
||||
tone: getWarningTone(hardware.instantCloneFrozen === true),
|
||||
},
|
||||
),
|
||||
makeRow('Enter setup mode', hardware.enterSetupMode === true ? formatBoolLabel(true) : '', {
|
||||
makeRow('Enter setup mode', hardware.enterSetupMode ? 'Yes' : '', {
|
||||
tone: getWarningTone(hardware.enterSetupMode === true),
|
||||
}),
|
||||
]);
|
||||
@@ -266,103 +212,85 @@ const toolsSummary = (tools?: ResourceVMwareTools): string => {
|
||||
return `Tools ${formatEnumLabel(versionStatus).toLowerCase()}`;
|
||||
}
|
||||
const runState = asTrimmedString(tools.runState);
|
||||
if (runState) return `Tools ${formatEnumLabel(runState).toLowerCase()}`;
|
||||
return '';
|
||||
return runState ? `Tools ${formatEnumLabel(runState).toLowerCase()}` : '';
|
||||
};
|
||||
|
||||
const toolsRows = (tools: ResourceVMwareTools | undefined, poweredOff: boolean): DetailRow[] => {
|
||||
if (!tools) return [];
|
||||
const runState = asTrimmedString(tools.runState);
|
||||
const versionStatus = asTrimmedString(tools.versionStatus).toUpperCase();
|
||||
const versionAttention = Boolean(versionStatus) && !['CURRENT', 'OK'].includes(versionStatus);
|
||||
// Drawer surfaces what an operator scans for: is Tools running, is its
|
||||
// version current, has the guest asked for a reboot, did the last install
|
||||
// error. Install metadata (install type, upgrade policy, auto-update
|
||||
// capability, attempt count, reboot components / time) stays in the raw
|
||||
// API; we only surface it when something is actionable.
|
||||
return compactRows([
|
||||
makeRow('Run state', formatEnumLabel(tools.runState), {
|
||||
makeRow('Run state', formatEnumLabel(runState), {
|
||||
tone: getWarningTone(
|
||||
!poweredOff &&
|
||||
Boolean(asTrimmedString(tools.runState)) &&
|
||||
!['RUNNING', 'STARTED'].includes(asTrimmedString(tools.runState).toUpperCase()),
|
||||
Boolean(runState) &&
|
||||
!['RUNNING', 'STARTED'].includes(runState.toUpperCase()),
|
||||
),
|
||||
}),
|
||||
makeRow('Version status', versionAttention ? formatEnumLabel(tools.versionStatus) : '', {
|
||||
tone: getWarningTone(versionAttention),
|
||||
}),
|
||||
makeRow('Version', asTrimmedString(tools.version)),
|
||||
makeRow('Guest reboot', tools.guestRebootRequested === true ? 'Requested' : '', {
|
||||
makeRow('Guest reboot', tools.guestRebootRequested ? 'Requested' : '', {
|
||||
tone: getWarningTone(tools.guestRebootRequested === true),
|
||||
}),
|
||||
makeRow('Last install error', asTrimmedString(tools.errorMessage), {
|
||||
tone: 'warning',
|
||||
wrap: true,
|
||||
}),
|
||||
wrapRow('Last install error', asTrimmedString(tools.errorMessage), { tone: 'warning' }),
|
||||
]);
|
||||
};
|
||||
|
||||
const virtualDiskDisplayName = (disk: ResourceVMwareVirtualDisk): string =>
|
||||
asTrimmedString(disk.label) || asTrimmedString(disk.disk) || 'Virtual disk';
|
||||
|
||||
const formatVirtualDiskAddress = (disk: ResourceVMwareVirtualDisk): string => {
|
||||
const type = asTrimmedString(disk.type).toUpperCase();
|
||||
if (type === 'SCSI' && disk.scsiBus !== undefined && disk.scsiUnit !== undefined) {
|
||||
return `SCSI ${disk.scsiBus}:${disk.scsiUnit}`;
|
||||
}
|
||||
if (type === 'SATA' && disk.sataBus !== undefined && disk.sataUnit !== undefined) {
|
||||
return `SATA ${disk.sataBus}:${disk.sataUnit}`;
|
||||
}
|
||||
if (type === 'NVME' && disk.nvmeBus !== undefined && disk.nvmeUnit !== undefined) {
|
||||
return `NVMe ${disk.nvmeBus}:${disk.nvmeUnit}`;
|
||||
const pair: Record<string, [string, number | undefined, number | undefined]> = {
|
||||
SCSI: ['SCSI', disk.scsiBus, disk.scsiUnit],
|
||||
SATA: ['SATA', disk.sataBus, disk.sataUnit],
|
||||
NVME: ['NVMe', disk.nvmeBus, disk.nvmeUnit],
|
||||
};
|
||||
const busUnit = pair[type];
|
||||
if (busUnit && busUnit[1] !== undefined && busUnit[2] !== undefined) {
|
||||
return `${busUnit[0]} ${busUnit[1]}:${busUnit[2]}`;
|
||||
}
|
||||
if (type === 'IDE' && disk.idePrimary !== undefined && disk.ideMaster !== undefined) {
|
||||
return `IDE ${disk.idePrimary ? 'primary' : 'secondary'} ${
|
||||
disk.ideMaster ? 'master' : 'slave'
|
||||
}`;
|
||||
return `IDE ${disk.idePrimary ? 'primary' : 'secondary'} ${disk.ideMaster ? 'master' : 'slave'}`;
|
||||
}
|
||||
return type;
|
||||
};
|
||||
|
||||
const virtualDiskValue = (disk: ResourceVMwareVirtualDisk): string => {
|
||||
const parts = [
|
||||
formatVirtualDiskAddress(disk),
|
||||
formatDetailBytesValue(disk.capacityBytes, {
|
||||
allowZero: true,
|
||||
precision: 'compact',
|
||||
trimWhole: true,
|
||||
}),
|
||||
asTrimmedString(disk.datastoreName),
|
||||
asTrimmedString(disk.backingType),
|
||||
asTrimmedString(disk.vmdkFile),
|
||||
].filter(Boolean);
|
||||
return parts.join(' · ');
|
||||
};
|
||||
|
||||
const virtualDiskRows = (disks: ResourceVMwareVirtualDisk[] | undefined): DetailRow[] =>
|
||||
compactRows(
|
||||
(disks ?? []).map((disk) =>
|
||||
wrapRow(virtualDiskDisplayName(disk), virtualDiskValue(disk), { tone: 'default' }),
|
||||
wrapRow(
|
||||
asTrimmedString(disk.label) || asTrimmedString(disk.disk) || 'Virtual disk',
|
||||
[
|
||||
formatVirtualDiskAddress(disk),
|
||||
formatDetailBytesValue(disk.capacityBytes, {
|
||||
allowZero: true,
|
||||
precision: 'compact',
|
||||
trimWhole: true,
|
||||
}),
|
||||
asTrimmedString(disk.datastoreName),
|
||||
asTrimmedString(disk.backingType),
|
||||
asTrimmedString(disk.vmdkFile),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · '),
|
||||
{ tone: 'default' },
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const vmwareEntityLabel = (entityType?: string): string => {
|
||||
const normalized = asTrimmedString(entityType).toLowerCase();
|
||||
switch (normalized) {
|
||||
case 'host':
|
||||
case 'hostsystem':
|
||||
return 'Host';
|
||||
case 'vm':
|
||||
case 'virtualmachine':
|
||||
return 'VM';
|
||||
case 'datastore':
|
||||
return 'Datastore';
|
||||
case 'network':
|
||||
return 'Network';
|
||||
default:
|
||||
return asTrimmedString(entityType);
|
||||
}
|
||||
const ENTITY_LABELS: Record<string, string> = {
|
||||
host: 'Host',
|
||||
hostsystem: 'Host',
|
||||
vm: 'VM',
|
||||
virtualmachine: 'VM',
|
||||
datastore: 'Datastore',
|
||||
network: 'Network',
|
||||
};
|
||||
|
||||
const vmwareEntityLabel = (entityType?: string): string =>
|
||||
ENTITY_LABELS[asTrimmedString(entityType).toLowerCase()] ?? asTrimmedString(entityType);
|
||||
|
||||
const buildSignalValue = (count: number | undefined, label: string, summary?: string): string => {
|
||||
const parts: string[] = [];
|
||||
if (typeof count === 'number') {
|
||||
@@ -469,13 +397,16 @@ export const buildVMwareDetailsSummary = (
|
||||
export const buildVMwareDetailSections = (
|
||||
resourceType: ResourceType,
|
||||
vmware?: ResourceVMwareMeta,
|
||||
resource?: Resource,
|
||||
): DetailSection[] => {
|
||||
if (!vmware) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const staleNotice = resource ? getVmwareStaleNotice(resource) : null;
|
||||
const poweredOff = isPoweredOff(vmware);
|
||||
const stateRows = compactRows([
|
||||
staleNotice ? wrapRow('Readings', staleNotice.detail, { tone: 'warning' }) : null,
|
||||
wrapRow('Connection', asTrimmedString(vmware.connectionName)),
|
||||
wrapRow('vCenter', asTrimmedString(vmware.vcenterHost)),
|
||||
makeRow('Entity', vmwareEntityLabel(vmware.entityType)),
|
||||
|
||||
@@ -191,54 +191,54 @@ const getPreferredHostLabel = (resource: Resource): string =>
|
||||
getPreferredInfrastructureDisplayName(resource) ||
|
||||
resource.id;
|
||||
|
||||
const buildUsageParts = (
|
||||
total: number,
|
||||
used: number,
|
||||
free: number | undefined,
|
||||
fallbackUsage: number,
|
||||
) => ({
|
||||
total,
|
||||
used,
|
||||
free: free ?? Math.max(total - used, 0),
|
||||
usage: total > 0 ? used / total : fallbackUsage,
|
||||
});
|
||||
|
||||
export const buildMemory = (metric?: ResourceMetric, fallback?: Partial<Memory>): Memory => {
|
||||
const usageUnavailable = metric == null && fallback?.usageUnavailable === true;
|
||||
const total = metric?.total ?? fallback?.total ?? 0;
|
||||
const used = metric?.used ?? fallback?.used ?? 0;
|
||||
const free = metric?.free ?? fallback?.free ?? (usageUnavailable ? 0 : Math.max(total - used, 0));
|
||||
const usage = usageUnavailable ? 0 : total > 0 ? used / total : (fallback?.usage ?? 0);
|
||||
return {
|
||||
const parts = buildUsageParts(
|
||||
total,
|
||||
used,
|
||||
free,
|
||||
usage,
|
||||
...(usageUnavailable ? { usageUnavailable: true } : {}),
|
||||
usageUnavailable ? (fallback?.free ?? 0) : (metric?.free ?? fallback?.free),
|
||||
fallback?.usage ?? 0,
|
||||
);
|
||||
return {
|
||||
...parts,
|
||||
...(usageUnavailable ? { usage: 0, usageUnavailable: true } : {}),
|
||||
};
|
||||
};
|
||||
|
||||
export const buildDisk = (metric?: ResourceMetric, fallback?: Partial<Disk>): Disk => {
|
||||
const total = metric?.total ?? fallback?.total ?? 0;
|
||||
const used = metric?.used ?? fallback?.used ?? 0;
|
||||
const free = metric?.free ?? fallback?.free ?? Math.max(total - used, 0);
|
||||
const usage = total > 0 ? used / total : (fallback?.usage ?? 0);
|
||||
return {
|
||||
total,
|
||||
used,
|
||||
free,
|
||||
usage,
|
||||
mountpoint: fallback?.mountpoint,
|
||||
type: fallback?.type,
|
||||
device: fallback?.device,
|
||||
};
|
||||
};
|
||||
export const buildDisk = (metric?: ResourceMetric, fallback?: Partial<Disk>): Disk => ({
|
||||
...buildUsageParts(
|
||||
metric?.total ?? fallback?.total ?? 0,
|
||||
metric?.used ?? fallback?.used ?? 0,
|
||||
metric?.free ?? fallback?.free,
|
||||
fallback?.usage ?? 0,
|
||||
),
|
||||
mountpoint: fallback?.mountpoint,
|
||||
type: fallback?.type,
|
||||
device: fallback?.device,
|
||||
});
|
||||
|
||||
export const toAgentDisks = (disks?: AgentDiskInfo[]): Disk[] | undefined => {
|
||||
if (!disks || disks.length === 0) return undefined;
|
||||
return disks.map((disk) => {
|
||||
const total = disk.total ?? 0;
|
||||
const used = disk.used ?? 0;
|
||||
const free = disk.free ?? Math.max(total - used, 0);
|
||||
const usage = total > 0 ? used / total : 0;
|
||||
return {
|
||||
total,
|
||||
used,
|
||||
free,
|
||||
usage,
|
||||
mountpoint: disk.mountpoint ?? disk.device,
|
||||
type: disk.filesystem ?? disk.type,
|
||||
device: disk.device,
|
||||
};
|
||||
});
|
||||
if (!disks?.length) return undefined;
|
||||
return disks.map((disk) => ({
|
||||
...buildUsageParts(disk.total ?? 0, disk.used ?? 0, disk.free, 0),
|
||||
mountpoint: disk.mountpoint ?? disk.device,
|
||||
type: disk.filesystem ?? disk.type,
|
||||
device: disk.device,
|
||||
}));
|
||||
};
|
||||
|
||||
export const toNodeFromProxmox = (resource: Resource): Node | null => {
|
||||
@@ -332,14 +332,10 @@ export const formatSensorName = (name: string) => {
|
||||
return titleCaseDelimitedLabel(clean);
|
||||
};
|
||||
|
||||
const formatSensorHardwareName = (name: string) => {
|
||||
return titleCaseDelimitedLabel(name)
|
||||
.replace(/\bCpu\b/g, 'CPU')
|
||||
.replace(/\bDram\b/g, 'DRAM')
|
||||
.replace(/\bGpu\b/g, 'GPU')
|
||||
.replace(/\bVram\b/g, 'VRAM')
|
||||
.replace(/\bVrm\b/g, 'VRM');
|
||||
};
|
||||
const formatSensorHardwareName = (name: string) =>
|
||||
titleCaseDelimitedLabel(name).replace(/\b(Cpu|Dram|Gpu|Vram|Vrm)\b/g, (match) =>
|
||||
match.toUpperCase(),
|
||||
);
|
||||
|
||||
const formatPowerSensorLabel = (name: string) => {
|
||||
const label = formatSensorHardwareName(name);
|
||||
@@ -385,15 +381,17 @@ const formatPowerWatts = (value: number) => {
|
||||
return `${value.toFixed(1)} W`;
|
||||
};
|
||||
|
||||
const sortedFiniteEntries = (record?: Record<string, number>) =>
|
||||
Object.entries(record ?? {})
|
||||
.filter(([, value]) => Number.isFinite(value))
|
||||
.sort(([a], [b]) => a.localeCompare(b));
|
||||
|
||||
export const buildPowerRows = (power?: HostSensorSummary['powerWatts']) =>
|
||||
Object.entries(power ?? {})
|
||||
.map(([name, value]) => [name, formatPowerWatts(value)] as const)
|
||||
.filter(([, value]) => value)
|
||||
.sort(([a], [b]) => a.localeCompare(b))
|
||||
.map(([name, value]) => {
|
||||
const label = formatPowerSensorLabel(name);
|
||||
return { label, value, valueTitle: `${label} ${value}` };
|
||||
});
|
||||
sortedFiniteEntries(power).map(([name, raw]) => {
|
||||
const label = formatPowerSensorLabel(name);
|
||||
const value = formatPowerWatts(raw);
|
||||
return { label, value, valueTitle: `${label} ${value}` };
|
||||
});
|
||||
|
||||
const formatFanRPM = (value: number) => {
|
||||
if (!Number.isFinite(value)) return '';
|
||||
@@ -441,75 +439,36 @@ export const buildTemperatureRows = (
|
||||
: titleCaseDelimitedLabel(thermalState.pressure),
|
||||
});
|
||||
}
|
||||
const limits = thermalState?.limitsPercent;
|
||||
if (limits) {
|
||||
Object.entries(limits)
|
||||
.filter(([, value]) => Number.isFinite(value) && value < 100)
|
||||
.sort(([a], [b]) => a.localeCompare(b))
|
||||
.forEach(([name, value]) => {
|
||||
rows.push({
|
||||
label: formatSensorName(name),
|
||||
value: `${Math.round(value)}%`,
|
||||
valueTitle: `${formatSensorName(name)} ${Math.round(value)}%`,
|
||||
});
|
||||
});
|
||||
for (const [name, value] of sortedFiniteEntries(thermalState?.limitsPercent)) {
|
||||
if (value >= 100) continue;
|
||||
const label = formatSensorName(name);
|
||||
const pct = `${Math.round(value)}%`;
|
||||
rows.push({ label, value: pct, valueTitle: `${label} ${pct}` });
|
||||
}
|
||||
const gpus = sensors?.gpu;
|
||||
if (gpus) {
|
||||
gpus.forEach((gpu, index) => {
|
||||
const value = formatGPUStatsValue(gpu);
|
||||
if (!value) return;
|
||||
rows.push({
|
||||
label: formatGPUStatsLabel(gpu.id, index),
|
||||
value,
|
||||
valueTitle: value,
|
||||
});
|
||||
});
|
||||
}
|
||||
const temps = sensors?.temperatureCelsius;
|
||||
if (temps) {
|
||||
const entries = Object.entries(temps)
|
||||
.filter(([name]) => !typedGPUTemperatureKeys.has(name))
|
||||
.filter(([, temp]) => Number.isFinite(temp))
|
||||
.sort(([a], [b]) => a.localeCompare(b));
|
||||
entries.forEach(([name, temp]) => {
|
||||
sensors?.gpu?.forEach((gpu, index) => {
|
||||
const value = formatGPUStatsValue(gpu);
|
||||
if (value) rows.push({ label: formatGPUStatsLabel(gpu.id, index), value, valueTitle: value });
|
||||
});
|
||||
for (const [name, temp] of sortedFiniteEntries(sensors?.temperatureCelsius)) {
|
||||
if (!typedGPUTemperatureKeys.has(name)) {
|
||||
rows.push({
|
||||
label: formatSensorName(name),
|
||||
value: formatTemperature(temp),
|
||||
valueTitle: `${temp.toFixed(1)}°C`,
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const [name, value] of sortedFiniteEntries(sensors?.additional)) {
|
||||
rows.push({
|
||||
label: formatSensorHardwareName(name),
|
||||
value: formatTemperature(value),
|
||||
valueTitle: `${value.toFixed(1)}°C`,
|
||||
});
|
||||
}
|
||||
|
||||
const additional = sensors?.additional;
|
||||
if (additional) {
|
||||
Object.entries(additional)
|
||||
.filter(([, value]) => Number.isFinite(value))
|
||||
.sort(([a], [b]) => a.localeCompare(b))
|
||||
.forEach(([name, value]) => {
|
||||
const label = formatSensorHardwareName(name);
|
||||
rows.push({
|
||||
label,
|
||||
value: formatTemperature(value),
|
||||
valueTitle: `${value.toFixed(1)}°C`,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const fans = sensors?.fanRpm;
|
||||
if (fans) {
|
||||
Object.entries(fans)
|
||||
.map(([name, value]) => [name, formatFanRPM(value)] as const)
|
||||
.filter(([, value]) => value)
|
||||
.sort(([a], [b]) => a.localeCompare(b))
|
||||
.forEach(([name, value]) => {
|
||||
const label = formatFanSensorLabel(name);
|
||||
rows.push({
|
||||
label,
|
||||
value,
|
||||
valueTitle: `${label} ${value}`,
|
||||
});
|
||||
});
|
||||
for (const [name, raw] of sortedFiniteEntries(sensors?.fanRpm)) {
|
||||
const label = formatFanSensorLabel(name);
|
||||
const value = formatFanRPM(raw);
|
||||
rows.push({ label, value, valueTitle: `${label} ${value}` });
|
||||
}
|
||||
|
||||
rows.push(...buildPowerRows(sensors?.powerWatts));
|
||||
|
||||
@@ -127,10 +127,10 @@ export const useResourceDetailDrawerDerivedState = (
|
||||
const lastSeen = createMemo(() => formatRelativeTime(resource().lastSeen, { now: now() }));
|
||||
const lastSeenAbsolute = createMemo(() => formatAbsoluteTime(resource().lastSeen));
|
||||
|
||||
const platformBadge = createMemo(() => getPlatformBadge(resource().platformType));
|
||||
const sourceBadge = createMemo(() => getSourceBadge(resource().sourceType));
|
||||
const typeBadge = createMemo(() => getTypeBadge(resource().type));
|
||||
const platformData = createMemo(() => resource().platformData as PlatformData | undefined);
|
||||
const platformBadge = () => getPlatformBadge(resource().platformType);
|
||||
const sourceBadge = () => getSourceBadge(resource().sourceType);
|
||||
const typeBadge = () => getTypeBadge(resource().type);
|
||||
const platformData = () => resource().platformData as PlatformData | undefined;
|
||||
const unifiedSourceBadges = createMemo(() => {
|
||||
const sources = resource().sources;
|
||||
return getUnifiedSourceBadges(
|
||||
@@ -138,7 +138,7 @@ export const useResourceDetailDrawerDerivedState = (
|
||||
);
|
||||
});
|
||||
const systemIdentityBadges = createMemo(() => getInfrastructureSystemIdentityBadges(resource()));
|
||||
const hasUnifiedSources = createMemo(() => unifiedSourceBadges().length > 0);
|
||||
const hasUnifiedSources = () => unifiedSourceBadges().length > 0;
|
||||
const headerBadges = createMemo(() => {
|
||||
const identityBadges =
|
||||
systemIdentityBadges().length > 0
|
||||
@@ -181,34 +181,27 @@ export const useResourceDetailDrawerDerivedState = (
|
||||
(policyBadges().length > 0 || Boolean(governanceSummary())),
|
||||
);
|
||||
|
||||
const agentMeta = createMemo(
|
||||
() => resource().agent ?? (platformData()?.agent as AgentPlatformData | undefined),
|
||||
);
|
||||
const kubernetesMeta = createMemo(
|
||||
() =>
|
||||
resource().kubernetes ?? (platformData()?.kubernetes as KubernetesPlatformData | undefined),
|
||||
);
|
||||
const vmwareData = createMemo(
|
||||
() => resource().vmware ?? (platformData()?.vmware as ResourceVMwareMeta | undefined),
|
||||
);
|
||||
const agentMeta = () =>
|
||||
resource().agent ?? (platformData()?.agent as AgentPlatformData | undefined);
|
||||
const kubernetesMeta = () =>
|
||||
resource().kubernetes ?? (platformData()?.kubernetes as KubernetesPlatformData | undefined);
|
||||
const vmwareData = () =>
|
||||
resource().vmware ?? (platformData()?.vmware as ResourceVMwareMeta | undefined);
|
||||
const kubernetesCapabilityBadges = createMemo(() =>
|
||||
buildKubernetesCapabilityBadges(kubernetesMeta()?.metricCapabilities),
|
||||
);
|
||||
|
||||
const proxmoxNode = createMemo(() => toNodeFromProxmox(resource()));
|
||||
const proxmoxNetworkInterfaces = createMemo(
|
||||
() =>
|
||||
resource().proxmox?.networkInterfaces ??
|
||||
(platformData()?.proxmox as { networkInterfaces?: HostNetworkInterface[] } | undefined)
|
||||
?.networkInterfaces ??
|
||||
[],
|
||||
);
|
||||
const proxmoxNetworkInterfaces = () =>
|
||||
resource().proxmox?.networkInterfaces ??
|
||||
(platformData()?.proxmox as { networkInterfaces?: HostNetworkInterface[] } | undefined)
|
||||
?.networkInterfaces ??
|
||||
[];
|
||||
const agentInfo = createMemo(() => toAgentFromResource(resource(), agentMeta()));
|
||||
// A silent agent's sensors and disk usage are its last report, even on a
|
||||
// row another source keeps online.
|
||||
const agentReadingsLastKnownReason = createMemo(() =>
|
||||
resource().agent?.stale ? HOST_AGENT_STOPPED_REPORTING_REASON : undefined,
|
||||
);
|
||||
const agentReadingsLastKnownReason = () =>
|
||||
resource().agent?.stale ? HOST_AGENT_STOPPED_REPORTING_REASON : undefined;
|
||||
const temperatureRows = createMemo(() =>
|
||||
buildTemperatureRows(agentInfo()?.sensors, {
|
||||
lastKnownReason: agentReadingsLastKnownReason(),
|
||||
@@ -216,12 +209,10 @@ export const useResourceDetailDrawerDerivedState = (
|
||||
);
|
||||
const customSensorRows = createMemo(() => buildCustomSensorRows(agentInfo()?.sensors));
|
||||
|
||||
const dockerHostData = createMemo(() => platformData()?.docker as DockerPlatformData | undefined);
|
||||
const dockerHostSourceId = createMemo(
|
||||
() => (dockerHostData()?.hostSourceId || '').trim() || null,
|
||||
);
|
||||
const dockerUpdatesAvailable = createMemo(() => dockerHostData()?.updatesAvailableCount ?? 0);
|
||||
const dockerContainerCount = createMemo(() => dockerHostData()?.containerCount ?? 0);
|
||||
const dockerHostData = () => platformData()?.docker as DockerPlatformData | undefined;
|
||||
const dockerHostSourceId = () => (dockerHostData()?.hostSourceId || '').trim() || null;
|
||||
const dockerUpdatesAvailable = () => dockerHostData()?.updatesAvailableCount ?? 0;
|
||||
const dockerContainerCount = () => dockerHostData()?.containerCount ?? 0;
|
||||
const dockerUpdatesCheckedRelative = createMemo(() => {
|
||||
const raw = dockerHostData()?.updatesLastCheckedAt;
|
||||
if (!raw) return '';
|
||||
@@ -229,20 +220,19 @@ export const useResourceDetailDrawerDerivedState = (
|
||||
if (!Number.isFinite(parsed)) return '';
|
||||
return formatRelativeTime(parsed, { now: now() });
|
||||
});
|
||||
const dockerHostCommand = createMemo(() => dockerHostData()?.command);
|
||||
const dockerHostCommandActive = createMemo(() => {
|
||||
const status = (dockerHostCommand()?.status || '').trim().toLowerCase();
|
||||
return ['queued', 'dispatched', 'acknowledged', 'in_progress'].includes(status);
|
||||
});
|
||||
const dockerUpdateActionsDisabled = createMemo(() => shouldHideDockerUpdateActions());
|
||||
const dockerUpdateActionsLoading = createMemo(() => !areSystemSettingsLoaded());
|
||||
const dockerHostCommand = () => dockerHostData()?.command;
|
||||
const dockerHostCommandActive = () =>
|
||||
['queued', 'dispatched', 'acknowledged', 'in_progress'].includes(
|
||||
(dockerHostCommand()?.status || '').trim().toLowerCase(),
|
||||
);
|
||||
const dockerUpdateActionsDisabled = () => shouldHideDockerUpdateActions();
|
||||
const dockerUpdateActionsLoading = () => !areSystemSettingsLoaded();
|
||||
|
||||
const resourceDependencies = createMemo(() => resourceIntelligence()?.dependencies ?? []);
|
||||
const resourceDependents = createMemo(() => resourceIntelligence()?.dependents ?? []);
|
||||
const resourceCorrelations = createMemo(() => resourceIntelligence()?.correlations ?? []);
|
||||
const resourceRelationships = createMemo(
|
||||
() => options.resourceRelationships?.() ?? resource().relationships ?? [],
|
||||
);
|
||||
const resourceDependencies = () => resourceIntelligence()?.dependencies ?? [];
|
||||
const resourceDependents = () => resourceIntelligence()?.dependents ?? [];
|
||||
const resourceCorrelations = () => resourceIntelligence()?.correlations ?? [];
|
||||
const resourceRelationships = () =>
|
||||
options.resourceRelationships?.() ?? resource().relationships ?? [];
|
||||
const hasMeaningfulResourceIntelligence = createMemo(() => {
|
||||
const intel = resourceIntelligence();
|
||||
if (!intel) return false;
|
||||
@@ -281,10 +271,10 @@ export const useResourceDetailDrawerDerivedState = (
|
||||
return summary.join(' · ');
|
||||
});
|
||||
|
||||
const pbsData = createMemo(() => platformData()?.pbs);
|
||||
const pmgData = createMemo(() => platformData()?.pmg);
|
||||
const pbsJobTotal = createMemo(() => getPbsJobTotal(pbsData()));
|
||||
const pmgQueueBacklog = createMemo(() => getPmgQueueBacklog(pmgData()));
|
||||
const pbsData = () => platformData()?.pbs;
|
||||
const pmgData = () => platformData()?.pmg;
|
||||
const pbsJobTotal = () => getPbsJobTotal(pbsData());
|
||||
const pmgQueueBacklog = () => getPmgQueueBacklog(pmgData());
|
||||
const pmgUpdatedRelative = createMemo(() => {
|
||||
const raw = pmgData()?.lastUpdated;
|
||||
if (!raw) return '';
|
||||
@@ -294,24 +284,25 @@ export const useResourceDetailDrawerDerivedState = (
|
||||
});
|
||||
const pbsVisibleJobBreakdown = createMemo(() => buildPbsVisibleJobBreakdown(pbsData()));
|
||||
const pbsActiveTasks = createMemo(() => buildPbsActiveTasks(pbsData()));
|
||||
const pbsActiveTaskCount = createMemo(() => pbsActiveTasks().length);
|
||||
const pbsActiveTaskCount = () => pbsActiveTasks().length;
|
||||
const pmgVisibleQueueBreakdown = createMemo(() => buildPmgVisibleQueueBreakdown(pmgData()));
|
||||
const pmgVisibleMailBreakdown = createMemo(() => buildPmgVisibleMailBreakdown(pmgData()));
|
||||
|
||||
const mergedSources = createMemo(() => platformData()?.sources ?? []);
|
||||
const sourceStatus = createMemo<NonNullable<PlatformData['sourceStatus']>>(
|
||||
() => platformData()?.sourceStatus ?? {},
|
||||
);
|
||||
const mergedSources = () => platformData()?.sources ?? [];
|
||||
const sourceStatus = createMemo<NonNullable<PlatformData['sourceStatus']>>(() => ({
|
||||
...platformData()?.sourceStatus,
|
||||
...resource().sourceStatus,
|
||||
}));
|
||||
const sourceSummary = createMemo(() => buildSourceSummary(mergedSources(), sourceStatus()));
|
||||
|
||||
const identityView = createMemo(() => buildResourceIdentityView(resource()));
|
||||
const identityAliasValues = createMemo(() => identityView().identityAliasValues);
|
||||
const identityIpValues = createMemo(() => identityView().identityIpValues);
|
||||
const primaryIdentityRows = createMemo(() => identityView().primaryIdentityRows);
|
||||
const identityCardHasRichData = createMemo(() => identityView().identityCardHasRichData);
|
||||
const aliasPreviewValues = createMemo(() => identityView().aliasPreviewValues);
|
||||
const hasAliasOverflow = createMemo(() => identityView().hasAliasOverflow);
|
||||
const hasMergedSources = createMemo(() => mergedSources().length > 1);
|
||||
const identityAliasValues = () => identityView().identityAliasValues;
|
||||
const identityIpValues = () => identityView().identityIpValues;
|
||||
const primaryIdentityRows = () => identityView().primaryIdentityRows;
|
||||
const identityCardHasRichData = () => identityView().identityCardHasRichData;
|
||||
const aliasPreviewValues = () => identityView().aliasPreviewValues;
|
||||
const hasAliasOverflow = () => identityView().hasAliasOverflow;
|
||||
const hasMergedSources = () => mergedSources().length > 1;
|
||||
const discoveryConfig = createMemo(() => toDiscoveryConfig(resource()));
|
||||
const guestReadPrecaution = createMemo(() => getResourceGuestReadPrecaution(resource()));
|
||||
|
||||
@@ -328,21 +319,19 @@ export const useResourceDetailDrawerDerivedState = (
|
||||
temperatureRowCount: temperatureRows().length + customSensorRows().length,
|
||||
}),
|
||||
);
|
||||
const hasHostDetails = createMemo(() => hostDetailCards().length > 0);
|
||||
const hostDetailSummary = createMemo(() => buildHostDetailSummary(hostDetailCards()));
|
||||
const hasServiceDetails = createMemo(
|
||||
() => resource().type === 'docker-host' || Boolean(pbsData()) || Boolean(pmgData()),
|
||||
);
|
||||
const serviceDetailsSummary = createMemo(() => {
|
||||
return getServiceDetailsSummary({
|
||||
const hasHostDetails = () => hostDetailCards().length > 0;
|
||||
const hostDetailSummary = () => buildHostDetailSummary(hostDetailCards());
|
||||
const hasServiceDetails = () =>
|
||||
resource().type === 'docker-host' || Boolean(pbsData()) || Boolean(pmgData());
|
||||
const serviceDetailsSummary = () =>
|
||||
getServiceDetailsSummary({
|
||||
resourceType: resource().type,
|
||||
docker: dockerHostData(),
|
||||
pbs: pbsData(),
|
||||
pmg: pmgData(),
|
||||
});
|
||||
});
|
||||
const vmwareDetailSections = createMemo(() =>
|
||||
buildVMwareDetailSections(resource().type, vmwareData()),
|
||||
buildVMwareDetailSections(resource().type, vmwareData(), resource()),
|
||||
);
|
||||
const { getTrueNASDiskTemperatureThresholds } = useAlertsActivation();
|
||||
const trueNASDetailSections = createMemo(() =>
|
||||
@@ -357,20 +346,16 @@ export const useResourceDetailDrawerDerivedState = (
|
||||
getResourceMetricsHistoryDeferredMetrics(resource()),
|
||||
);
|
||||
const metricsHistoryGroups = createMemo(() => getResourceMetricsHistoryGroups(resource()));
|
||||
const hasMetricsHistory = createMemo(() => resourceSupportsMetricsHistory(resource()));
|
||||
const hasMetricsHistory = () => resourceSupportsMetricsHistory(resource());
|
||||
const relatedLinks = createMemo(() => buildRelatedLinks(resource(), displayName()));
|
||||
const accessSummary = createMemo(() =>
|
||||
const accessSummary = () =>
|
||||
buildAccessSummary({
|
||||
hasWebInterface: Boolean(discoveryConfig()),
|
||||
links: relatedLinks(),
|
||||
}),
|
||||
);
|
||||
const hasAccessContext = createMemo(
|
||||
() => Boolean(discoveryConfig()) || relatedLinks().length > 0,
|
||||
);
|
||||
const hasRuntimeOperationalContext = createMemo(() =>
|
||||
buildHasRuntimeOperationalContext(kubernetesCapabilityBadges()),
|
||||
);
|
||||
});
|
||||
const hasAccessContext = () => Boolean(discoveryConfig()) || relatedLinks().length > 0;
|
||||
const hasRuntimeOperationalContext = () =>
|
||||
buildHasRuntimeOperationalContext(kubernetesCapabilityBadges());
|
||||
|
||||
const sourceSections = createMemo(() => buildSourceSections(platformData()));
|
||||
const identityMatchInfo = createMemo(() => buildIdentityMatchInfo(platformData()));
|
||||
|
||||
@@ -227,25 +227,15 @@ export function VmwarePageSurface() {
|
||||
enabled: () => shouldHydrateTab(tab),
|
||||
realtimeEnabled: () => shouldHydrateTab(tab),
|
||||
});
|
||||
const overviewResources = createTabResources('overview');
|
||||
const storageResources = createTabResources('storage');
|
||||
const networkResources = createTabResources('networks');
|
||||
const healthResources = createTabResources('health');
|
||||
const activityResources = createTabResources('activity');
|
||||
const resourceState = createMemo(() => {
|
||||
switch (activeTab()) {
|
||||
case 'storage':
|
||||
return storageResources;
|
||||
case 'networks':
|
||||
return networkResources;
|
||||
case 'health':
|
||||
return healthResources;
|
||||
case 'activity':
|
||||
return activityResources;
|
||||
default:
|
||||
return overviewResources;
|
||||
}
|
||||
});
|
||||
const tabResources = {
|
||||
overview: createTabResources('overview'),
|
||||
storage: createTabResources('storage'),
|
||||
networks: createTabResources('networks'),
|
||||
health: createTabResources('health'),
|
||||
activity: createTabResources('activity'),
|
||||
};
|
||||
const healthResources = tabResources.health;
|
||||
const resourceState = () => tabResources[activeTab()];
|
||||
const resources = () => resourceState().resources();
|
||||
const loading = () => resourceState().loading();
|
||||
const error = () => resourceState().error();
|
||||
|
||||
@@ -10,7 +10,7 @@ import { useWebSocket } from '@/contexts/appRuntime';
|
||||
import { useAlertsActivation } from '@/stores/alertsActivation';
|
||||
import { unifiedPlatformOverrideIdCandidates } from '@/features/alerts/alertOverridesModel';
|
||||
import { asTrimmedString } from '@/utils/stringUtils';
|
||||
import { formatVmwareClusterServices } from '@/utils/vmwareDisplay';
|
||||
import { formatVmwareClusterServices, getVmwareStaleNotice } from '@/utils/vmwareDisplay';
|
||||
import {
|
||||
formatVmwarePowerState,
|
||||
getVmwareResourceDisplayStatus,
|
||||
@@ -87,16 +87,22 @@ type MobilePowerException = {
|
||||
title: string;
|
||||
};
|
||||
|
||||
const MOBILE_POWER_EXCEPTIONS: Record<string, MobilePowerException> = {
|
||||
poweredoff: { label: 'Off', tone: 'danger', title: 'Power state: Off' },
|
||||
off: { label: 'Off', tone: 'danger', title: 'Power state: Off' },
|
||||
suspended: { label: 'Suspended', tone: 'warning', title: 'Power state: Suspended' },
|
||||
};
|
||||
|
||||
const getMobilePowerException = (powerState: string | undefined): MobilePowerException | null => {
|
||||
const normalized = normalizeVmwarePowerStateToken(powerState);
|
||||
if (normalized === 'poweredon' || normalized === 'on') return null;
|
||||
if (normalized === 'poweredoff' || normalized === 'off') {
|
||||
return { label: 'Off', tone: 'danger', title: 'Power state: Off' };
|
||||
}
|
||||
if (normalized === 'suspended') {
|
||||
return { label: 'Suspended', tone: 'warning', title: 'Power state: Suspended' };
|
||||
}
|
||||
return { label: 'Unknown', tone: 'muted', title: 'Power state: Unknown' };
|
||||
return (
|
||||
MOBILE_POWER_EXCEPTIONS[normalized] ?? {
|
||||
label: 'Unknown',
|
||||
tone: 'muted',
|
||||
title: 'Power state: Unknown',
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
const getVsphereHostSortValue = (
|
||||
@@ -373,6 +379,7 @@ export const VsphereHostsTable: Component<{
|
||||
const vmCount = () =>
|
||||
vmCountByHost().get(asTrimmedString(meta()?.managedObjectId) || '') ?? 0;
|
||||
const mobilePowerException = () => getMobilePowerException(meta()?.powerState);
|
||||
const staleNotice = () => getVmwareStaleNotice(host);
|
||||
const displayStatus = () => getVmwareResourceDisplayStatus(host);
|
||||
const indicator = () => getSimpleStatusIndicator(displayStatus());
|
||||
const metricsKey = () => buildMetricKeyForUnifiedResource(host);
|
||||
@@ -441,22 +448,34 @@ export const VsphereHostsTable: Component<{
|
||||
title={displayStatus() || 'unknown'}
|
||||
ariaHidden
|
||||
/>
|
||||
<span
|
||||
class="min-w-0 truncate font-semibold text-base-content"
|
||||
title={name()}
|
||||
>
|
||||
<Show when={props.vmScope} fallback={name()}>
|
||||
{(scope) => (
|
||||
<PlatformHostScopeNameButton
|
||||
name={name()}
|
||||
workloadNoun="VMs"
|
||||
controlsId={scope().sectionId}
|
||||
selected={isVmScopeSelected()}
|
||||
onSelect={() => scope().onShow(host)}
|
||||
/>
|
||||
<div class="min-w-0">
|
||||
<span
|
||||
class="block truncate font-semibold text-base-content"
|
||||
title={name()}
|
||||
>
|
||||
<Show when={props.vmScope} fallback={name()}>
|
||||
{(scope) => (
|
||||
<PlatformHostScopeNameButton
|
||||
name={name()}
|
||||
workloadNoun="VMs"
|
||||
controlsId={scope().sectionId}
|
||||
selected={isVmScopeSelected()}
|
||||
onSelect={() => scope().onShow(host)}
|
||||
/>
|
||||
)}
|
||||
</Show>
|
||||
</span>
|
||||
<Show when={staleNotice()}>
|
||||
{(notice) => (
|
||||
<span
|
||||
class="block text-[10px] font-medium text-amber-800 dark:text-amber-300"
|
||||
title={notice().detail}
|
||||
>
|
||||
{notice().badge}
|
||||
</span>
|
||||
)}
|
||||
</Show>
|
||||
</span>
|
||||
</div>
|
||||
<Show when={mobilePowerException()}>
|
||||
{(power) => (
|
||||
<MetadataBadge
|
||||
|
||||
@@ -280,12 +280,19 @@ export const VsphereNetworksTable: Component<{
|
||||
variant={indicator().variant}
|
||||
title={indicator().label}
|
||||
/>
|
||||
<span
|
||||
class="truncate font-medium text-base-content"
|
||||
title={networkTitle()}
|
||||
>
|
||||
{name()}
|
||||
</span>
|
||||
<div class="min-w-0">
|
||||
<span
|
||||
class="block truncate font-medium text-base-content"
|
||||
title={networkTitle()}
|
||||
>
|
||||
{name()}
|
||||
</span>
|
||||
<Show when={issue()?.stale}>
|
||||
<span class="block text-[10px] font-medium text-amber-800 dark:text-amber-300">
|
||||
Stale data
|
||||
</span>
|
||||
</Show>
|
||||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell
|
||||
|
||||
@@ -162,6 +162,60 @@ describe('VsphereHostsTable', () => {
|
||||
expect(container.querySelector('[data-vsphere-host-row="host-healthy"]')).toBeNull();
|
||||
expect(screen.getByText('1 of 2 hosts')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows Stale data on live stale hosts, preserves offline danger, and clears on live recovery', () => {
|
||||
const stale = { vmware: { status: 'stale', error: 'vCenter poll timed out' } };
|
||||
const staleHost = makeHost({
|
||||
id: 'host-stale',
|
||||
name: 'esxi-stale.lab.local',
|
||||
sourceStatus: stale,
|
||||
});
|
||||
const offlineStale = makeHost({
|
||||
id: 'host-offline',
|
||||
name: 'esxi-offline.lab.local',
|
||||
status: 'offline',
|
||||
sourceStatus: stale,
|
||||
});
|
||||
const healthyHost = makeHost({ id: 'host-fresh', name: 'esxi-fresh.lab.local' });
|
||||
const [hosts, setHosts] = createSignal([staleHost, offlineStale, healthyHost]);
|
||||
|
||||
const { container } = render(() => (
|
||||
<VsphereHostsTable
|
||||
hosts={hosts()}
|
||||
scope={hosts()}
|
||||
emptyIcon={<span />}
|
||||
emptyTitle="No hosts"
|
||||
emptyDescription="No hosts"
|
||||
showToolbar={false}
|
||||
/>
|
||||
));
|
||||
|
||||
const row = (id: string) => within(container.querySelector(`[data-vsphere-host-row="${id}"]`)!);
|
||||
expect(row('host-stale').getByText('Stale data')).toHaveAttribute(
|
||||
'title',
|
||||
'vCenter has not updated this recently: vCenter poll timed out',
|
||||
);
|
||||
expect(row('host-stale').getByTitle('degraded')).toHaveClass('bg-amber-500');
|
||||
expect(row('host-stale').getByTestId('responsive-metric-cell')).toBeInTheDocument();
|
||||
expect(row('host-stale').getByTestId('stacked-memory-bar')).toBeInTheDocument();
|
||||
|
||||
expect(row('host-offline').getByText('Stale data')).toBeInTheDocument();
|
||||
expect(row('host-offline').getByTitle('offline')).toHaveClass('bg-red-500');
|
||||
expect(row('host-fresh').queryByText('Stale data')).not.toBeInTheDocument();
|
||||
|
||||
setHosts([
|
||||
{
|
||||
...staleHost,
|
||||
sourceStatus: { vmware: { status: 'online' } },
|
||||
platformData: { sourceStatus: stale },
|
||||
},
|
||||
offlineStale,
|
||||
healthyHost,
|
||||
]);
|
||||
|
||||
expect(row('host-stale').queryByText('Stale data')).not.toBeInTheDocument();
|
||||
expect(row('host-stale').getByTitle('online')).toHaveClass('bg-emerald-500');
|
||||
});
|
||||
it('shows the vCenter column by connection name only when several vCenters are connected', () => {
|
||||
const lab = makeHost({ id: 'host-1' });
|
||||
lab.vmware = { ...lab.vmware!, connectionId: 'vc-lab', connectionName: 'Lab vCenter' };
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { cleanup, fireEvent, render, screen, within } from '@solidjs/testing-library';
|
||||
import { createSignal } from 'solid-js';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { VsphereNetworksTable } from '@/features/vmware/VsphereNetworksTable';
|
||||
@@ -146,4 +147,57 @@ describe('VsphereNetworksTable', () => {
|
||||
expect(health('Archive Network')).toHaveAttribute('data-vsphere-health', 'danger');
|
||||
expect(health('Archive Network')).toHaveAttribute('title', 'vCenter health is red');
|
||||
});
|
||||
|
||||
it('qualifies stale realtime networks, preserves offline severity, and clears on live recovery', async () => {
|
||||
const stale = { vmware: { status: 'error', error: 'vCenter session expired' } };
|
||||
const quiet = makeNetwork({ id: 'Edge Trunk', sourceStatus: stale });
|
||||
const down = makeNetwork({ id: 'Backup VLAN', status: 'offline', sourceStatus: stale });
|
||||
const fresh = makeNetwork({ id: 'VM Network' });
|
||||
const [networks, setNetworks] = createSignal([quiet, down, fresh]);
|
||||
|
||||
render(() => (
|
||||
<VsphereNetworksTable
|
||||
networks={networks()}
|
||||
scope={networks()}
|
||||
emptyIcon={<span />}
|
||||
emptyTitle="No networks"
|
||||
emptyDescription="No networks"
|
||||
/>
|
||||
));
|
||||
|
||||
const row = (name: string) => within(screen.getByText(name, { exact: true }).closest('tr')!);
|
||||
expect(row('Edge Trunk').getByText('Stale data')).toBeInTheDocument();
|
||||
expect(
|
||||
row('Edge Trunk').getByTitle('vCenter collection error: vCenter session expired'),
|
||||
).toBeInTheDocument();
|
||||
expect(row('Backup VLAN').getByText('Stale data')).toBeInTheDocument();
|
||||
expect(row('Backup VLAN').getByTitle('Attention')).toHaveClass('bg-red-500');
|
||||
expect(
|
||||
screen.getByText('Backup VLAN').closest('tr')?.querySelector('[data-vsphere-health]'),
|
||||
).toHaveAttribute(
|
||||
'title',
|
||||
'Last reported offline\nvCenter collection error: vCenter session expired',
|
||||
);
|
||||
expect(row('VM Network').queryByText('Stale data')).not.toBeInTheDocument();
|
||||
|
||||
await fireEvent.click(screen.getByRole('button', { name: 'Healthy, 1' }));
|
||||
expect(screen.queryByText('Edge Trunk', { exact: true })).not.toBeInTheDocument();
|
||||
|
||||
setNetworks([
|
||||
{
|
||||
...quiet,
|
||||
sourceStatus: { vmware: { status: 'online' } },
|
||||
platformData: { sourceStatus: stale },
|
||||
},
|
||||
down,
|
||||
fresh,
|
||||
]);
|
||||
|
||||
expect(row('Edge Trunk').queryByText('Stale data')).not.toBeInTheDocument();
|
||||
expect(row('Edge Trunk').getByTitle('Online')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Healthy, 2' })).toHaveAttribute(
|
||||
'aria-pressed',
|
||||
'true',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -284,6 +284,24 @@ describe('vmwarePageModel', () => {
|
||||
});
|
||||
|
||||
expect(mapVmwareNetworkStatus(staleConnection)).toBe('attention');
|
||||
|
||||
const offlineStaleHost = makeResource({
|
||||
id: 'esxi-offline-stale',
|
||||
type: 'agent',
|
||||
status: 'offline',
|
||||
sourceStatus: { vmware: { status: 'stale' } },
|
||||
});
|
||||
expect(getVmwareResourceDisplayStatus(offlineStaleHost)).toBe('offline');
|
||||
|
||||
const recoveredNetwork = makeResource({
|
||||
id: 'network-recovered',
|
||||
type: 'network',
|
||||
vmware: { entityType: 'network', overallStatus: 'green' },
|
||||
sourceStatus: { vmware: { status: 'online' } },
|
||||
platformData: { sourceStatus: { 'vmware-vsphere': { status: 'stale' } } },
|
||||
});
|
||||
expect(getVmwareResourceDisplayStatus(recoveredNetwork)).toBe('online');
|
||||
expect(mapVmwareNetworkStatus(recoveredNetwork)).toBe('healthy');
|
||||
});
|
||||
|
||||
it('filters vSphere VMs using vCenter VM metadata', () => {
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { resolveResourcePlatformType } from '@/utils/sourcePlatforms';
|
||||
import { hasImpairedResourceSource } from '@/utils/resourceSourceHealth';
|
||||
import { formatVmwareClusterServices } from '@/utils/vmwareDisplay';
|
||||
import {
|
||||
formatVmwareClusterServices,
|
||||
getVmwareStaleNotice,
|
||||
isVmwareSourceImpaired,
|
||||
type VmwareStaleNotice,
|
||||
} from '@/utils/vmwareDisplay';
|
||||
import type { Resource, ResourceChange, ResourceIncident, ResourceType } from '@/types/resource';
|
||||
import type { PlatformIssue } from '@/features/platformPage/PlatformIssueReason';
|
||||
import { getSimpleStatusIndicator, type StatusIndicator } from '@/utils/status';
|
||||
@@ -232,8 +236,20 @@ export const getVsphereHostWorkloadScope = (
|
||||
});
|
||||
};
|
||||
|
||||
export const getVmwareResourceDisplayStatus = (resource: Resource): string =>
|
||||
hasImpairedResourceSource(resource, 'vmware-vsphere') ? 'degraded' : resource.status;
|
||||
const SEVERE_VMWARE_RESOURCE_STATUSES = new Set([
|
||||
'offline',
|
||||
'stopped',
|
||||
'error',
|
||||
'failed',
|
||||
'faulted',
|
||||
'critical',
|
||||
'unhealthy',
|
||||
]);
|
||||
|
||||
export const getVmwareResourceDisplayStatus = (resource: Resource): string => {
|
||||
if (SEVERE_VMWARE_RESOURCE_STATUSES.has(normalize(resource.status))) return resource.status;
|
||||
return isVmwareSourceImpaired(resource) ? 'degraded' : resource.status;
|
||||
};
|
||||
|
||||
const trimString = (value: unknown): string => (typeof value === 'string' ? value.trim() : '');
|
||||
|
||||
@@ -338,10 +354,8 @@ export function mapVmwareIncidentSeverity(
|
||||
severity: string | undefined,
|
||||
): VmwareIncidentSeverityBucket {
|
||||
const normalized = normalize(severity);
|
||||
if (['critical', 'crit', 'fatal', 'error', 'failed', 'failure', 'red'].includes(normalized)) {
|
||||
return 'critical';
|
||||
}
|
||||
if (['warning', 'warn', 'alert', 'degraded', 'yellow'].includes(normalized)) return 'warning';
|
||||
if (/^(crit(ical)?|fatal|error|fail(ed|ure)|red)$/.test(normalized)) return 'critical';
|
||||
if (/^(warn(ing)?|alert|degraded|yellow)$/.test(normalized)) return 'warning';
|
||||
return 'info';
|
||||
}
|
||||
|
||||
@@ -352,23 +366,24 @@ export function normalizeVmwarePowerStateToken(value: string | undefined): strin
|
||||
.replace(/[\s_-]/g, '');
|
||||
}
|
||||
|
||||
const POWER_STATE_INFO: Record<string, [string, 'success' | 'warning' | 'danger']> = {
|
||||
poweredon: ['On', 'success'],
|
||||
on: ['On', 'success'],
|
||||
poweredoff: ['Off', 'danger'],
|
||||
off: ['Off', 'danger'],
|
||||
suspended: ['Suspended', 'warning'],
|
||||
};
|
||||
|
||||
export function formatVmwarePowerState(value: string | undefined): string {
|
||||
const normalized = normalizeVmwarePowerStateToken(value);
|
||||
if (normalized === 'poweredon' || normalized === 'on') return 'On';
|
||||
if (normalized === 'poweredoff' || normalized === 'off') return 'Off';
|
||||
if (normalized === 'suspended') return 'Suspended';
|
||||
const trimmed = (value || '').trim();
|
||||
return trimmed || 'Unknown';
|
||||
return (
|
||||
POWER_STATE_INFO[normalizeVmwarePowerStateToken(value)]?.[0] ?? (trimString(value) || 'Unknown')
|
||||
);
|
||||
}
|
||||
|
||||
export function getVmwarePowerStateVariant(
|
||||
state: string | undefined,
|
||||
): 'success' | 'warning' | 'danger' | 'muted' {
|
||||
const normalized = normalizeVmwarePowerStateToken(state);
|
||||
if (normalized === 'poweredon' || normalized === 'on') return 'success';
|
||||
if (normalized === 'poweredoff' || normalized === 'off') return 'danger';
|
||||
if (normalized === 'suspended') return 'warning';
|
||||
return 'muted';
|
||||
return POWER_STATE_INFO[normalizeVmwarePowerStateToken(state)]?.[1] ?? 'muted';
|
||||
}
|
||||
|
||||
const ATTENTION_STATUSES = new Set(['degraded', 'warning', 'critical', 'paused']);
|
||||
@@ -379,7 +394,7 @@ const isAttentionOverall = (overall: string): boolean =>
|
||||
export function mapVmwareVirtualMachineStatus(
|
||||
resource: Resource,
|
||||
): Exclude<VmwareVirtualMachineStatusFilter, 'all'> {
|
||||
if (hasImpairedResourceSource(resource, 'vmware-vsphere')) return 'attention';
|
||||
if (isVmwareSourceImpaired(resource)) return 'attention';
|
||||
const powerState = normalizeToken(resource.vmware?.powerState);
|
||||
const status = normalize(getVmwareResourceDisplayStatus(resource));
|
||||
const overall = normalize(resource.vmware?.overallStatus);
|
||||
@@ -402,10 +417,6 @@ export function mapVmwareVirtualMachineStatus(
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
// Realtime rows carry the vCenter sighting at the top level; older rows may
|
||||
// only carry the REST compatibility copy. A new poll wins over that old copy.
|
||||
const datastoreSighting = (resource: Resource): string | undefined =>
|
||||
resource.sourceStatus?.vmware?.status;
|
||||
const datastoreInaccessible = (resource: Resource): boolean =>
|
||||
resource.vmware?.datastoreAccessible === false || normalize(resource.status) === 'offline';
|
||||
|
||||
@@ -425,10 +436,7 @@ export function mapVmwareDatastoreStatus(
|
||||
return 'maintenance';
|
||||
}
|
||||
if (datastoreInaccessible(resource)) return 'inaccessible';
|
||||
const sighting = datastoreSighting(resource);
|
||||
if (sighting ? sighting !== 'online' : hasImpairedResourceSource(resource, 'vmware-vsphere')) {
|
||||
return 'attention';
|
||||
}
|
||||
if (isVmwareSourceImpaired(resource)) return 'attention';
|
||||
if (isAttentionOverall(overall) || ATTENTION_STATUSES.has(status)) return 'attention';
|
||||
if (resource.vmware?.datastoreAccessible === true || ['online', 'running'].includes(status)) {
|
||||
return 'accessible';
|
||||
@@ -455,19 +463,15 @@ export function mapVmwareNetworkStatus(
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
const VCENTER_NO_RECENT_UPDATE = 'vCenter has not updated this recently';
|
||||
|
||||
// The datastore table shows canonical staleness beside the name. Do not let
|
||||
// the compatibility copy supersede it or displace a visible alarm reason.
|
||||
// Stale rows show the non-colour Stale data cue beside the name. Keep alarms
|
||||
// and outages ahead of the generic staleness line while surfacing collection
|
||||
// errors or filling in when staleness is the only attention reason.
|
||||
const vmwareAttentionReasons = (
|
||||
resource: Resource,
|
||||
leading: string[] = [],
|
||||
sighting?: string,
|
||||
staleNotice: VmwareStaleNotice | null = null,
|
||||
): string[] => {
|
||||
const reasons =
|
||||
!sighting && hasImpairedResourceSource(resource, 'vmware-vsphere')
|
||||
? [VCENTER_NO_RECENT_UPDATE, ...leading]
|
||||
: leading;
|
||||
const reasons = [...leading];
|
||||
const push = (value: unknown) => {
|
||||
const text = trimString(value);
|
||||
if (text && !reasons.some((existing) => existing.toLowerCase() === text.toLowerCase())) {
|
||||
@@ -489,7 +493,7 @@ const vmwareAttentionReasons = (
|
||||
if (ATTENTION_OVERALL_STATUSES.has(overall)) push(`vCenter health is ${overall}`);
|
||||
else if (alarms > 0) push(`${alarms} active vCenter alarm${alarms === 1 ? '' : 's'}`);
|
||||
}
|
||||
if (!reasons.length && sighting && sighting !== 'online') push(VCENTER_NO_RECENT_UPDATE);
|
||||
if (staleNotice && (!reasons.length || staleNotice.error)) push(staleNotice.detail);
|
||||
return reasons;
|
||||
};
|
||||
|
||||
@@ -521,16 +525,18 @@ const DATASTORE_ISSUE_LABELS = {
|
||||
attention: 'Attention',
|
||||
} as const;
|
||||
|
||||
export function getVmwareDatastoreIssue(
|
||||
resource: Resource,
|
||||
): (PlatformIssue & { stale: boolean }) | null {
|
||||
export type VmwareRowIssue = PlatformIssue & {
|
||||
stale: boolean;
|
||||
};
|
||||
|
||||
export function getVmwareDatastoreIssue(resource: Resource): VmwareRowIssue | null {
|
||||
const bucket = mapVmwareDatastoreStatus(resource);
|
||||
if (bucket === 'accessible' || bucket === 'unknown') return null;
|
||||
// The bucket picks one filter, but a datastore in maintenance can also be
|
||||
// unreachable or carry a critical alarm: each condition gives its reason,
|
||||
// and the worst sets the colour.
|
||||
const sighting = datastoreSighting(resource);
|
||||
const stale = sighting === 'stale';
|
||||
const staleNotice = getVmwareStaleNotice(resource);
|
||||
const stale = staleNotice !== null;
|
||||
const inaccessible = datastoreInaccessible(resource);
|
||||
const leading: string[] = [];
|
||||
if (inaccessible)
|
||||
@@ -542,7 +548,7 @@ export function getVmwareDatastoreIssue(
|
||||
: 'In maintenance mode',
|
||||
);
|
||||
}
|
||||
const reasons = vmwareAttentionReasons(resource, leading, sighting);
|
||||
const reasons = vmwareAttentionReasons(resource, leading, staleNotice);
|
||||
return {
|
||||
tone: inaccessible || hasCriticalVmwareSignal(resource) ? 'danger' : 'warning',
|
||||
label: DATASTORE_ISSUE_LABELS[bucket],
|
||||
@@ -551,14 +557,18 @@ export function getVmwareDatastoreIssue(
|
||||
};
|
||||
}
|
||||
|
||||
export function getVmwareNetworkIssue(resource: Resource): PlatformIssue | null {
|
||||
export function getVmwareNetworkIssue(resource: Resource): VmwareRowIssue | null {
|
||||
if (mapVmwareNetworkStatus(resource) !== 'attention') return null;
|
||||
const offline = normalize(getVmwareResourceDisplayStatus(resource)) === 'offline';
|
||||
const reasons = vmwareAttentionReasons(resource);
|
||||
const staleNotice = getVmwareStaleNotice(resource);
|
||||
const stale = staleNotice !== null;
|
||||
const offline = normalize(resource.status) === 'offline';
|
||||
const leading = offline ? [stale ? 'Last reported offline' : 'vCenter reports it offline'] : [];
|
||||
const reasons = vmwareAttentionReasons(resource, leading, staleNotice);
|
||||
return {
|
||||
tone: offline || hasCriticalVmwareSignal(resource) ? 'danger' : 'warning',
|
||||
label: 'Attention',
|
||||
reasons: reasons.length > 0 ? reasons : ['vCenter reports a problem'],
|
||||
stale,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -661,15 +671,13 @@ export function buildVmwareIncidentRows(resources: Resource[]): VmwareIncidentRo
|
||||
}
|
||||
}
|
||||
|
||||
return rows.sort((a, b) => {
|
||||
const severityDelta = incidentSeverityRank(b.severity) - incidentSeverityRank(a.severity);
|
||||
if (severityDelta !== 0) return severityDelta;
|
||||
const priorityDelta = b.priority - a.priority;
|
||||
if (priorityDelta !== 0) return priorityDelta;
|
||||
const entityDelta = a.entityType.localeCompare(b.entityType);
|
||||
if (entityDelta !== 0) return entityDelta;
|
||||
return a.resourceName.localeCompare(b.resourceName);
|
||||
});
|
||||
return rows.sort(
|
||||
(a, b) =>
|
||||
incidentSeverityRank(b.severity) - incidentSeverityRank(a.severity) ||
|
||||
b.priority - a.priority ||
|
||||
a.entityType.localeCompare(b.entityType) ||
|
||||
a.resourceName.localeCompare(b.resourceName),
|
||||
);
|
||||
}
|
||||
|
||||
export type VmwareHealthPosture = {
|
||||
@@ -702,39 +710,22 @@ export function buildVmwareHealthPosture(
|
||||
return posture;
|
||||
}
|
||||
|
||||
const isVmwareActivityChange = (change: ResourceChange): boolean => {
|
||||
if (change.kind !== 'activity') return false;
|
||||
if (trimString(change.sourceAdapter) === 'vmware_adapter') return true;
|
||||
const activityType = metadataString(change.metadata, 'activity_type');
|
||||
if (activityType.startsWith('vmware_')) return true;
|
||||
return Boolean(
|
||||
metadataString(
|
||||
change.metadata,
|
||||
'vmwareTask',
|
||||
'vmwareTaskName',
|
||||
'vmwareTaskState',
|
||||
'vmwareEvent',
|
||||
'vmwareEventType',
|
||||
'vmwareEventMessage',
|
||||
),
|
||||
);
|
||||
};
|
||||
const VMWARE_TASK_KEYS = ['vmwareTask', 'vmwareTaskName', 'vmwareTaskState'] as const;
|
||||
const VMWARE_EVENT_KEYS = ['vmwareEvent', 'vmwareEventType', 'vmwareEventMessage'] as const;
|
||||
|
||||
const isVmwareActivityChange = (change: ResourceChange): boolean =>
|
||||
change.kind === 'activity' &&
|
||||
(trimString(change.sourceAdapter) === 'vmware_adapter' ||
|
||||
metadataString(change.metadata, 'activity_type').startsWith('vmware_') ||
|
||||
Boolean(metadataString(change.metadata, ...VMWARE_TASK_KEYS, ...VMWARE_EVENT_KEYS)));
|
||||
|
||||
const mapVmwareActivityKind = (
|
||||
activityType: string,
|
||||
metadata: Record<string, unknown> | undefined,
|
||||
): VmwareActivityKind => {
|
||||
const normalized = normalizeToken(activityType);
|
||||
if (
|
||||
normalized.includes('task') ||
|
||||
metadataString(metadata, 'vmwareTask', 'vmwareTaskName', 'vmwareTaskState')
|
||||
) {
|
||||
return 'task';
|
||||
}
|
||||
if (
|
||||
normalized.includes('event') ||
|
||||
metadataString(metadata, 'vmwareEvent', 'vmwareEventType', 'vmwareEventMessage')
|
||||
) {
|
||||
if (normalized.includes('task') || metadataString(metadata, ...VMWARE_TASK_KEYS)) return 'task';
|
||||
if (normalized.includes('event') || metadataString(metadata, ...VMWARE_EVENT_KEYS)) {
|
||||
return 'event';
|
||||
}
|
||||
return 'activity';
|
||||
@@ -742,19 +733,9 @@ const mapVmwareActivityKind = (
|
||||
|
||||
export function mapVmwareActivityStateBucket(state: string): VmwareActivityStateBucket {
|
||||
const normalized = normalizeToken(state);
|
||||
if (
|
||||
['error', 'failed', 'failure', 'cancelled', 'canceled', 'timedout', 'timeout', 'red'].includes(
|
||||
normalized,
|
||||
)
|
||||
) {
|
||||
return 'failed';
|
||||
}
|
||||
if (['running', 'queued', 'pending', 'inprogress', 'started'].includes(normalized)) {
|
||||
return 'running';
|
||||
}
|
||||
if (['success', 'succeeded', 'complete', 'completed', 'ok', 'green'].includes(normalized)) {
|
||||
return 'success';
|
||||
}
|
||||
if (/^(error|fail(ed|ure)|cancell?ed|timed?out|red)$/.test(normalized)) return 'failed';
|
||||
if (/^(running|queued|pending|inprogress|started)$/.test(normalized)) return 'running';
|
||||
if (/^(succe(ss|eded)|completed?|ok|green)$/.test(normalized)) return 'success';
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
@@ -764,23 +745,31 @@ const parseActivitySortTime = (change: ResourceChange): number => {
|
||||
return Number.isFinite(parsed) ? parsed : 0;
|
||||
};
|
||||
|
||||
const appendSourceAliasKeys = (
|
||||
keys: Set<string>,
|
||||
connectionId: unknown,
|
||||
entityType: unknown,
|
||||
managedObjectId: unknown,
|
||||
includeStorageAlias: boolean,
|
||||
): void => {
|
||||
const sourceAlias = vmwareSourceAlias(connectionId, entityType, managedObjectId);
|
||||
addLookupKey(keys, sourceAlias);
|
||||
addLookupKey(keys, managedObjectId);
|
||||
if (includeStorageAlias && sourceAlias) addLookupKey(keys, `storage:${sourceAlias}`);
|
||||
};
|
||||
|
||||
const vmwareActivityResourceKeys = (resource: Resource): Set<string> => {
|
||||
const keys = new Set<string>();
|
||||
addLookupKey(keys, resource.id);
|
||||
addLookupKey(keys, resource.canonicalIdentity?.primaryId);
|
||||
for (const alias of resource.canonicalIdentity?.aliases ?? []) {
|
||||
addLookupKey(keys, alias);
|
||||
}
|
||||
const sourceAlias = vmwareSourceAlias(
|
||||
for (const alias of resource.canonicalIdentity?.aliases ?? []) addLookupKey(keys, alias);
|
||||
appendSourceAliasKeys(
|
||||
keys,
|
||||
resource.vmware?.connectionId,
|
||||
resource.vmware?.entityType,
|
||||
resource.vmware?.managedObjectId,
|
||||
resource.type === 'storage',
|
||||
);
|
||||
addLookupKey(keys, sourceAlias);
|
||||
addLookupKey(keys, resource.vmware?.managedObjectId);
|
||||
if (sourceAlias && resource.type === 'storage') {
|
||||
addLookupKey(keys, `storage:${sourceAlias}`);
|
||||
}
|
||||
return keys;
|
||||
};
|
||||
|
||||
@@ -788,16 +777,13 @@ const vmwareActivityChangeKeys = (change: ResourceChange): Set<string> => {
|
||||
const keys = new Set<string>();
|
||||
addLookupKey(keys, change.resourceId);
|
||||
const metadata = change.metadata;
|
||||
const sourceAlias = vmwareSourceAlias(
|
||||
appendSourceAliasKeys(
|
||||
keys,
|
||||
metadataString(metadata, 'vmwareConnectionId'),
|
||||
metadataString(metadata, 'vmwareEntityType'),
|
||||
metadataString(metadata, 'vmwareManagedObjectId'),
|
||||
true,
|
||||
);
|
||||
addLookupKey(keys, sourceAlias);
|
||||
addLookupKey(keys, metadataString(metadata, 'vmwareManagedObjectId'));
|
||||
if (sourceAlias) {
|
||||
addLookupKey(keys, `storage:${sourceAlias}`);
|
||||
}
|
||||
return keys;
|
||||
};
|
||||
|
||||
@@ -838,28 +824,17 @@ const buildActivityRow = (
|
||||
change: ResourceChange,
|
||||
index: number,
|
||||
): VmwareActivityRow => {
|
||||
const metadata = change.metadata;
|
||||
const activityType = metadataString(metadata, 'activity_type');
|
||||
const activityKind = mapVmwareActivityKind(activityType, metadata);
|
||||
const m = (...keys: string[]) => metadataString(change.metadata, ...keys);
|
||||
const activityType = m('activity_type');
|
||||
const activityKind = mapVmwareActivityKind(activityType, change.metadata);
|
||||
// An event reads as vCenter's own message. The provider titles new events
|
||||
// with it; records stored before that carry the event class as their title.
|
||||
const title =
|
||||
(activityKind === 'event' ? metadataString(metadata, 'vmwareEventMessage') : '') ||
|
||||
metadataString(metadata, 'activity_title', 'vmwareTaskName', 'vmwareEventType') ||
|
||||
(activityKind === 'event' ? m('vmwareEventMessage') : '') ||
|
||||
m('activity_title', 'vmwareTaskName', 'vmwareEventType') ||
|
||||
trimString(change.reason) ||
|
||||
'vSphere activity';
|
||||
const state =
|
||||
metadataString(metadata, 'activity_state', 'vmwareTaskState') || trimString(change.to);
|
||||
const message =
|
||||
metadataString(metadata, 'activity_message', 'vmwareTaskError', 'vmwareEventMessage') ||
|
||||
trimString(change.reason);
|
||||
const description = metadataString(metadata, 'vmwareTaskDescription', 'vmwareEventMessage');
|
||||
const eventType = metadataString(metadata, 'vmwareEventType');
|
||||
const actor = trimString(change.actor) || metadataString(metadata, 'vmwareEventUser');
|
||||
const nativeId = metadataString(metadata, 'activity_native_id', 'vmwareTask', 'vmwareEvent');
|
||||
const observedAt = trimString(change.observedAt);
|
||||
const occurredAt = trimString(change.occurredAt) || undefined;
|
||||
|
||||
const state = m('activity_state', 'vmwareTaskState') || trimString(change.to);
|
||||
return {
|
||||
id: `${resource.id}:activity:${change.id || index}`,
|
||||
resource,
|
||||
@@ -867,27 +842,23 @@ const buildActivityRow = (
|
||||
resourceId: resource.id,
|
||||
resourceName: vmwareResourceDisplayName(resource),
|
||||
resourceType: resource.type,
|
||||
entityType:
|
||||
metadataString(metadata, 'vmwareEntityType') ||
|
||||
trimString(resource.vmware?.entityType) ||
|
||||
resource.type,
|
||||
entityType: m('vmwareEntityType') || trimString(resource.vmware?.entityType) || resource.type,
|
||||
managedObjectId:
|
||||
metadataString(metadata, 'vmwareManagedObjectId') ||
|
||||
trimString(resource.vmware?.managedObjectId) ||
|
||||
resource.id,
|
||||
m('vmwareManagedObjectId') || trimString(resource.vmware?.managedObjectId) || resource.id,
|
||||
activityKind,
|
||||
activityType,
|
||||
stateBucket: mapVmwareActivityStateBucket(state),
|
||||
title,
|
||||
eventType,
|
||||
eventType: m('vmwareEventType'),
|
||||
state,
|
||||
message,
|
||||
description,
|
||||
actor,
|
||||
nativeId: nativeId || change.id,
|
||||
message:
|
||||
m('activity_message', 'vmwareTaskError', 'vmwareEventMessage') || trimString(change.reason),
|
||||
description: m('vmwareTaskDescription', 'vmwareEventMessage'),
|
||||
actor: trimString(change.actor) || m('vmwareEventUser'),
|
||||
nativeId: m('activity_native_id', 'vmwareTask', 'vmwareEvent') || change.id,
|
||||
source: trimString(change.sourceAdapter) || trimString(change.sourceType) || 'vmware',
|
||||
occurredAt,
|
||||
observedAt,
|
||||
occurredAt: trimString(change.occurredAt) || undefined,
|
||||
observedAt: trimString(change.observedAt),
|
||||
sortTime: parseActivitySortTime(change),
|
||||
};
|
||||
};
|
||||
@@ -921,13 +892,12 @@ export function buildVmwareActivityRows(
|
||||
}
|
||||
}
|
||||
|
||||
return rows.sort((left, right) => {
|
||||
const timeDelta = right.sortTime - left.sortTime;
|
||||
if (timeDelta !== 0) return timeDelta;
|
||||
const resourceDelta = left.resourceName.localeCompare(right.resourceName);
|
||||
if (resourceDelta !== 0) return resourceDelta;
|
||||
return left.id.localeCompare(right.id);
|
||||
});
|
||||
return rows.sort(
|
||||
(left, right) =>
|
||||
right.sortTime - left.sortTime ||
|
||||
left.resourceName.localeCompare(right.resourceName) ||
|
||||
left.id.localeCompare(right.id),
|
||||
);
|
||||
}
|
||||
|
||||
const buildSearchHaystack = (parts: readonly unknown[]): string =>
|
||||
@@ -1087,27 +1057,31 @@ export function filterVmwareVirtualMachines(
|
||||
);
|
||||
}
|
||||
|
||||
const commonRowSearchFields = (row: VmwareIncidentRow | VmwareActivityRow): readonly unknown[] => [
|
||||
row.resourceId,
|
||||
row.resourceName,
|
||||
row.resourceType,
|
||||
row.entityType,
|
||||
row.managedObjectId,
|
||||
row.source,
|
||||
row.resource.vmware?.connectionName,
|
||||
row.resource.vmware?.vcenterHost,
|
||||
row.resource.vmware?.datacenterName,
|
||||
row.resource.vmware?.clusterName,
|
||||
row.resource.vmware?.runtimeHostName,
|
||||
...(row.resource.tags ?? []),
|
||||
];
|
||||
|
||||
const incidentSearchHaystack = (row: VmwareIncidentRow): string =>
|
||||
buildSearchHaystack([
|
||||
row.resourceId,
|
||||
row.resourceName,
|
||||
row.resourceType,
|
||||
row.entityType,
|
||||
row.managedObjectId,
|
||||
...commonRowSearchFields(row),
|
||||
row.severity,
|
||||
row.code,
|
||||
row.source,
|
||||
row.summary,
|
||||
row.label,
|
||||
row.category,
|
||||
row.action,
|
||||
row.resource.vmware?.connectionName,
|
||||
row.resource.vmware?.vcenterHost,
|
||||
row.resource.vmware?.datacenterName,
|
||||
row.resource.vmware?.clusterName,
|
||||
row.resource.vmware?.runtimeHostName,
|
||||
row.resource.vmware?.activeAlarmSummary,
|
||||
...(row.resource.tags ?? []),
|
||||
]);
|
||||
|
||||
export function filterVmwareIncidents(
|
||||
@@ -1130,11 +1104,7 @@ export function filterVmwareIncidents(
|
||||
const activitySearchHaystack = (row: VmwareActivityRow): string =>
|
||||
buildSearchHaystack([
|
||||
row.id,
|
||||
row.resourceId,
|
||||
row.resourceName,
|
||||
row.resourceType,
|
||||
row.entityType,
|
||||
row.managedObjectId,
|
||||
...commonRowSearchFields(row),
|
||||
row.activityKind,
|
||||
row.activityType,
|
||||
row.title,
|
||||
@@ -1144,14 +1114,7 @@ const activitySearchHaystack = (row: VmwareActivityRow): string =>
|
||||
row.description,
|
||||
row.actor,
|
||||
row.nativeId,
|
||||
row.source,
|
||||
row.resource.vmware?.connectionName,
|
||||
row.resource.vmware?.vcenterHost,
|
||||
row.resource.vmware?.datacenterName,
|
||||
row.resource.vmware?.clusterName,
|
||||
row.resource.vmware?.runtimeHostName,
|
||||
...(row.change.relatedResources ?? []),
|
||||
...(row.resource.tags ?? []),
|
||||
]);
|
||||
|
||||
export function filterVmwareActivity(
|
||||
|
||||
@@ -23,32 +23,43 @@ export const getTrueNASDatasetStateSummary = (
|
||||
return null;
|
||||
};
|
||||
|
||||
const CONNECTED_STATUS = /^(online|running|healthy|connected|ok)$/;
|
||||
const ERROR_STATUS = /^(error|failed|unauthorized)$/;
|
||||
const CONNECTED_STATUS = /^(online|running|healthy|connected|ok)$/i;
|
||||
const ERROR_STATUS = /^(error|failed|unauthorized)$/i;
|
||||
|
||||
export type TrueNASStaleNotice = {
|
||||
export type ProviderStaleNotice = {
|
||||
badge: string;
|
||||
detail: string;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export type TrueNASStaleNotice = ProviderStaleNotice;
|
||||
|
||||
export const buildProviderStaleNotice = (
|
||||
entry: { status?: unknown; error?: unknown } | undefined,
|
||||
provider: string,
|
||||
): ProviderStaleNotice | null => {
|
||||
const status = typeof entry?.status === 'string' ? entry.status.trim() : '';
|
||||
if (!entry || CONNECTED_STATUS.test(status)) return null;
|
||||
const error = asTrimmedString(entry.error);
|
||||
const prefix =
|
||||
error && ERROR_STATUS.test(status)
|
||||
? `${provider} collection error`
|
||||
: `${provider} has not updated this recently`;
|
||||
return {
|
||||
badge: 'Stale data',
|
||||
detail: error ? `${prefix}: ${error}` : prefix,
|
||||
...(error ? { error } : {}),
|
||||
};
|
||||
};
|
||||
|
||||
// Prefer top-level sourceStatus written by live WebSocket and REST adaptation,
|
||||
// falling back to platformData.sourceStatus for older fixtures so live recovery
|
||||
// clears a stale REST copy without waiting for a reload.
|
||||
export const getTrueNASStaleNotice = (resource: Resource): TrueNASStaleNotice | null => {
|
||||
const entry = resource.sourceStatus?.truenas ?? getResourceSourceStatus(resource, 'truenas');
|
||||
if (!entry) return null;
|
||||
const status = typeof entry.status === 'string' ? entry.status.trim().toLowerCase() : '';
|
||||
if (CONNECTED_STATUS.test(status)) return null;
|
||||
const error = asTrimmedString(entry.error);
|
||||
const prefix =
|
||||
error && ERROR_STATUS.test(status)
|
||||
? 'TrueNAS collection error'
|
||||
: 'TrueNAS has not updated this recently';
|
||||
return {
|
||||
badge: 'Stale data',
|
||||
detail: error ? `${prefix}: ${error}` : prefix,
|
||||
};
|
||||
};
|
||||
export const getTrueNASStaleNotice = (resource: Resource): TrueNASStaleNotice | null =>
|
||||
buildProviderStaleNotice(
|
||||
resource.sourceStatus?.truenas ?? getResourceSourceStatus(resource, 'truenas'),
|
||||
'TrueNAS',
|
||||
);
|
||||
|
||||
export const isTrueNASSourceImpaired = (resource: Resource): boolean =>
|
||||
getTrueNASStaleNotice(resource) !== null;
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import type { ResourceVMwareMeta } from '@/types/resource';
|
||||
import type { Resource, ResourceVMwareMeta } from '@/types/resource';
|
||||
import { getResourceSourceStatus } from '@/utils/resourceSourceHealth';
|
||||
import { buildProviderStaleNotice, type ProviderStaleNotice } from '@/utils/truenasDatasetState';
|
||||
|
||||
export const formatVmwareClusterServices = (meta: ResourceVMwareMeta | undefined): string => {
|
||||
const parts: string[] = [];
|
||||
@@ -10,3 +12,19 @@ export const formatVmwareClusterServices = (meta: ResourceVMwareMeta | undefined
|
||||
}
|
||||
return parts.join(' · ');
|
||||
};
|
||||
|
||||
export type VmwareStaleNotice = ProviderStaleNotice;
|
||||
|
||||
// Prefer top-level sourceStatus written by live WebSocket and REST adaptation,
|
||||
// falling back to platformData.sourceStatus for older fixtures so live recovery
|
||||
// clears a stale REST copy without waiting for a reload.
|
||||
export const getVmwareStaleNotice = (resource: Resource): VmwareStaleNotice | null =>
|
||||
buildProviderStaleNotice(
|
||||
resource.sourceStatus?.vmware ??
|
||||
resource.sourceStatus?.['vmware-vsphere'] ??
|
||||
getResourceSourceStatus(resource, 'vmware-vsphere'),
|
||||
'vCenter',
|
||||
);
|
||||
|
||||
export const isVmwareSourceImpaired = (resource: Resource): boolean =>
|
||||
getVmwareStaleNotice(resource) !== null;
|
||||
|
||||
Reference in New Issue
Block a user