Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

12.7 KB
Raw Blame
import { createMemo } from 'solid-js';

import { useBreakpoint } from '@/hooks/useBreakpoint';
import { useAnomalyForMetric } from '@/hooks/useAnomalies';
import { useAlertsActivation } from '@/stores/alertsActivation';
import type { Container } from '@/types/api';
import type { DisplayMetricType } from '@/utils/metricThresholds';
import { buildMetricKey } from '@/utils/metricsKeys';
import { getGuestHealthIndicator, isGuestRunning } from '@/utils/status';
import { formatBytes } from '@/utils/format';
import { getContainerRuntimeBadgeForRuntime } from '@/utils/resourceBadgePresentation';
import { getWorkloadGuestDiskRead } from '@/utils/workloadGuestPresentation';
import { getWorkloadDiskUsagePercent } from '@/utils/workloadDiskUsage';
import {
  getCanonicalWorkloadId,
  getWorkloadPlatformScopes,
  getWorkloadMetricsKind,
  isDockerManagedAppContainer,
  resolveWorkloadType,
} from '@/utils/workloads';
import { getAvailabilityProbePresentation } from '@/utils/availabilityProbePresentation';
import { useRelativeTimeNow } from '@/utils/relativeTimeClock';
import { getWorkloadTypeBadge } from '@/components/shared/workloadTypeBadges';

import {
  getWorkloadAlertPolicyTags,
  getWorkloadAlertResourceIdCandidates,
  getWorkloadAlertThresholdScope,
  getWorkloadDockerHostId,
} from './workloadTopology';
import {
  DEFAULT_FIRST_CELL_INDENT,
  EMPTY_IO_EMPHASIS,
  GROUPED_FIRST_CELL_INDENT,
  getOutlierEmphasis,
  getWorkloadDisplayId,
  getWorkloadInfoValue,
  type GuestRowProps,
} from './guestRowModel';

export function useGuestRowState(props: GuestRowProps) {
  const now = useRelativeTimeNow();
  const { isMobile } = useBreakpoint();
  const alertsActivation = useAlertsActivation();

  const guestId = createMemo(() => getCanonicalWorkloadId(props.guest));

  const visibleColumnIdSet = createMemo(() =>
    props.visibleColumnIds ? new Set(props.visibleColumnIds) : null,
  );

  const isColVisible = (colId: string) => {
    const set = visibleColumnIdSet();
    if (!set) return true;
    return set.has(colId);
  };

  const workloadType = createMemo(() => resolveWorkloadType(props.guest));
  const metricsKey = createMemo(() =>
    buildMetricKey(getWorkloadMetricsKind(props.guest), guestId()),
  );
  const alertThresholdScope = createMemo(() => getWorkloadAlertThresholdScope(props.guest));
  const alertResourceIdCandidates = createMemo(() =>
    getWorkloadAlertResourceIdCandidates(props.guest),
  );
  const alertPolicyTags = createMemo(() => getWorkloadAlertPolicyTags(props.guest));
  const metricThresholds = (metric: DisplayMetricType) =>
    createMemo(() =>
      alertsActivation.getMetricThresholds(
        alertThresholdScope(),
        metric,
        alertResourceIdCandidates(),
        alertPolicyTags(),
      ),
    );
  const cpuThresholds = metricThresholds('cpu');
  const memoryThresholds = metricThresholds('memory');
  const diskThresholds = metricThresholds('disk');

  const cpuAnomaly = useAnomalyForMetric(guestId, () => 'cpu');
  const memoryAnomaly = useAnomalyForMetric(guestId, () => 'memory');
  const diskAnomaly = useAnomalyForMetric(guestId, () => 'disk');

  const customUrl = createMemo(() => props.customUrl?.trim() ?? '');

  const displayId = createMemo(() => getWorkloadDisplayId(props.guest));

  const ipAddresses = createMemo(() => props.guest.ipAddresses ?? []);
  const networkInterfaces = createMemo(() => props.guest.networkInterfaces ?? []);
  const hasNetworkInterfaces = createMemo(() => networkInterfaces().length > 0);
  const osName = createMemo(() => props.guest.osName?.trim() ?? '');
  const osVersion = createMemo(() => props.guest.osVersion?.trim() ?? '');
  const agentVersion = createMemo(() => props.guest.agentVersion?.trim() ?? '');
  const hasOsInfo = createMemo(() => osName().length > 0 || osVersion().length > 0);
  const dockerImage = createMemo(() => props.guest.image?.trim() ?? '');
  const namespace = createMemo(() => props.guest.namespace?.trim() ?? '');
  const contextLabel = createMemo(() => props.guest.contextLabel?.trim() ?? '');
  const clusterName = createMemo(() => props.guest.clusterName?.trim() ?? '');
  const isPveWorkload = createMemo(() => {
    const type = workloadType();
    return type === 'vm' || type === 'system-container';
  });

  const infoValue = createMemo(() => getWorkloadInfoValue(props.guest));

  const infoTooltip = createMemo(() => {
    if (workloadType() === 'app-container') return dockerImage();
    return infoValue();
  });

  const supportsBackup = createMemo(() => {
    const type = workloadType();
    if (type !== 'vm' && type !== 'system-container') return false;

    // The shared backup scalar is currently sourced only from Proxmox
    // vzdump/PBS inventory. An API-backed VM from another provider (notably
    // vSphere) has no value here because the provider does not expose that
    // contract; absence must remain unknown rather than becoming "never".
    // Rows without canonical platform metadata are the legacy Proxmox shape
    // and retain their existing backup presentation during migration.
    const platformScopes = getWorkloadPlatformScopes(props.guest);
    return platformScopes.length === 0 || platformScopes.includes('proxmox-pve');
  });

  const appContainerRuntimeBadge = createMemo(() => {
    if (workloadType() !== 'app-container') return null;
    return getContainerRuntimeBadgeForRuntime(props.guest.containerRuntime);
  });

  const isOCIContainer = createMemo(() => {
    if (workloadType() !== 'system-container') return false;
    const containerMeta = props.guest as Partial<Pick<Container, 'isOci'>>;
    return props.guest.type === 'oci-container' || containerMeta.isOci === true;
  });

  const ociImage = createMemo(() => {
    if (!isOCIContainer()) return null;

    const template = (props.guest as Partial<Pick<Container, 'osTemplate'>>).osTemplate;
    if (!template) return null;

    let image = template;
    if (image.startsWith('oci:')) image = image.slice(4);
    if (image.startsWith('docker:')) image = image.slice(7);
    return image;
  });

  const typeInfo = createMemo(() => {
    const type = workloadType();

    if (type === 'system-container' && isOCIContainer()) {
      return getWorkloadTypeBadge('system-container', {
        title: `OCI Container${ociImage() ? ` • ${ociImage()}` : ''}`,
      });
    }

    if (type === 'app-container') {
      const platform = (props.guest.platformType || '').trim().toLowerCase();
      const runtime = (props.guest.containerRuntime || '').trim();
      const normalized = runtime.toLowerCase();
      const title =
        normalized === 'podman'
          ? 'Podman Container'
          : normalized === 'docker'
            ? 'Docker Container'
            : runtime
              ? `${runtime} Container`
              : platform === 'truenas'
                ? 'TrueNAS App Container'
                : 'Application Container';
      return getWorkloadTypeBadge('app-container', { title });
    }

    return getWorkloadTypeBadge(type);
  });

  const diskRead = createMemo(() => props.guest.diskRead || 0);
  const diskWrite = createMemo(() => props.guest.diskWrite || 0);
  const networkIn = createMemo(() => props.guest.networkIn || 0);
  const networkOut = createMemo(() => props.guest.networkOut || 0);
  const ioEmphasis = createMemo(() => props.ioEmphasis ?? EMPTY_IO_EMPHASIS);
  const diskIOTotal = createMemo(() => diskRead() + diskWrite());
  const networkTotal = createMemo(() => networkIn() + networkOut());
  const diskIOEmphasis = createMemo(() => getOutlierEmphasis(diskIOTotal(), ioEmphasis().diskIO));
  const networkEmphasis = createMemo(() =>
    getOutlierEmphasis(networkTotal(), ioEmphasis().network),
  );

  const memoryExtraLines = createMemo(() => {
    if (!props.guest.memory) return undefined;

    const lines: string[] = [];
    const total = props.guest.memory.total ?? 0;
    if (
      props.guest.memory.balloon &&
      props.guest.memory.balloon > 0 &&
      props.guest.memory.balloon !== total
    ) {
      lines.push(`Balloon: ${formatBytes(props.guest.memory.balloon)}`);
    }
    if (props.guest.memory.swapTotal && props.guest.memory.swapTotal > 0) {
      const swapUsed = props.guest.memory.swapUsed ?? 0;
      lines.push(`Swap: ${formatBytes(swapUsed)} / ${formatBytes(props.guest.memory.swapTotal)}`);
    }
    return lines.length > 0 ? lines : undefined;
  });

  const memoryTooltip = createMemo(() => memoryExtraLines()?.join('\n') ?? undefined);
  const memoryPercentOnly = createMemo(() => {
    const memory = props.guest.memory;
    if (!memory) return undefined;
    if ((memory.total ?? 0) > 0) return undefined;

    const usage = memory.usage ?? 0;
    if (!Number.isFinite(usage) || usage <= 0) return undefined;
    return Math.max(0, Math.min(usage, 100));
  });

  const diskPercent = createMemo(() => getWorkloadDiskUsagePercent(props.guest.disk));

  // The cell's filesystem bars and aggregate follow the drawer's rule: a
  // linked agent's filesystems follow that agent, Proxmox's its read reason.
  const diskUsageRead = createMemo(() =>
    getWorkloadGuestDiskRead(props.guest, workloadType() === 'vm'),
  );

  const hasDiskUsage = createMemo(() => {
    const guest = props.guest;
    if (!guest.disk || guest.telemetryAvailability?.disk === false) return false;
    // A generic canonical merge can retain the previous numeric metric while
    // its source reports no usable guest reading. Only a last known reading
    // may keep that number visible.
    if (diskUsageRead().state === 'unavailable') return false;
    const percent = diskPercent();
    return percent !== null;
  });

  const parentOnline = createMemo(() => props.parentNodeOnline !== false);
  const isRunning = createMemo(() => isGuestRunning(props.guest, parentOnline()));
  const guestStatus = createMemo(() => getGuestHealthIndicator(props.guest, parentOnline()));
  const lockLabel = createMemo(() => (props.guest.lock || '').trim());

  const hasUnacknowledgedAlert = createMemo(() => !!props.alertStyles?.hasUnacknowledgedAlert);
  const hasAcknowledgedOnlyAlert = createMemo(() => !!props.alertStyles?.hasAcknowledgedOnlyAlert);
  const showAlertHighlight = createMemo(
    () => hasUnacknowledgedAlert() || hasAcknowledgedOnlyAlert(),
  );

  const alertAccentTone = createMemo<'critical' | 'warning' | 'info' | 'acknowledged' | undefined>(
    () => {
      if (!showAlertHighlight()) return undefined;
      if (hasUnacknowledgedAlert()) {
        return props.alertStyles?.severity ?? 'warning';
      }
      return 'acknowledged';
    },
  );

  const rowClass = createMemo(() => {
    const base = 'transition-all duration-200 relative group cursor-pointer';

    if (props.isExpanded) {
      return `${base} bg-blue-50 dark:bg-blue-900/25 z-10 hover:shadow-xs`;
    }

    const hover = 'hover:shadow-xs';
    const alertBg = hasUnacknowledgedAlert()
      ? props.alertStyles?.severity === 'critical'
        ? 'bg-red-50 dark:bg-red-950/25'
        : props.alertStyles?.severity === 'info'
          ? 'bg-blue-50 dark:bg-blue-950/25'
          : 'bg-yellow-50 dark:bg-yellow-950/25'
      : '';
    const defaultHover = hasUnacknowledgedAlert() ? '' : 'hover:bg-surface-hover';
    const stoppedDimming = !isRunning() ? 'opacity-60' : '';

    return [base, hover, defaultHover, alertBg, stoppedDimming].filter(Boolean).join(' ');
  });

  const firstCellIndent = createMemo(() =>
    props.isGroupedView ? GROUPED_FIRST_CELL_INDENT : DEFAULT_FIRST_CELL_INDENT,
  );

  const dockerHostId = createMemo(() =>
    isDockerManagedAppContainer(props.guest) ? getWorkloadDockerHostId(props.guest) : '',
  );

  const availabilityPresentation = createMemo(() => {
    const availability = props.guest.availability;
    if (!availability) return null;
    return getAvailabilityProbePresentation(
      {
        type: props.guest.type as never,
        platformType: (props.guest.platformType ?? '') as never,
        status: props.guest.status as never,
        availability,
        platformData: { availability },
      },
      new Date(now()),
    );
  });

  return {
    appContainerRuntimeBadge,
    cpuAnomaly,
    cpuThresholds,
    customUrl,
    diskAnomaly,
    diskIOEmphasis,
    diskPercent,
    diskRead,
    diskThresholds,
    diskUsageRead,
    diskWrite,
    displayId,
    dockerHostId,
    dockerImage,
    firstCellIndent,
    guestId,
    guestStatus,
    hasDiskUsage,
    hasNetworkInterfaces,
    hasOsInfo,
    infoTooltip,
    infoValue,
    ipAddresses,
    isColVisible,
    isMobile,
    isOCIContainer,
    isPveWorkload,
    isRunning,
    lockLabel,
    memoryAnomaly,
    memoryPercentOnly,
    memoryThresholds,
    memoryTooltip,
    metricsKey,
    namespace,
    networkEmphasis,
    networkIn,
    networkInterfaces,
    networkOut,
    ociImage,
    osName,
    osVersion,
    alertAccentTone,
    supportsBackup,
    typeInfo,
    workloadType,
    contextLabel,
    clusterName,
    agentVersion,
    rowClass,
    availabilityPresentation,
  };
}