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.

17.2 KB
Raw Blame
import type { Agent, Node } from '@/types/api';
import {
  requiresGovernedResourceDisplay,
  type Resource,
  type ResourceCanonicalIdentity,
} from '@/types/resource';
import type { NodeConfig } from '@/types/nodes';
import { getResourcePolicyDisplayLabel } from '@/utils/resourcePolicyPresentation';
import {
  getActionableAgentIdFromResource,
  getActionableDockerRuntimeIdFromResource,
  getActionableKubernetesClusterIdFromResource,
  getPreferredResourceClusterName,
  getPreferredResourceKubernetesContext,
  isTrueNASSystemResource,
  getPlatformAgentRecord,
  getPlatformDataRecord,
} from '@/utils/agentResources';
import { asTrimmedString } from '@/utils/stringUtils';

export type ResourceIdentityRow = {
  label: string;
  value: string;
};

type APINormalizedIdentityResource = {
  id: string;
  name?: string;
  proxmox?: {
    nodeName?: string;
  };
  agent?: {
    hostname?: string;
  };
  docker?: {
    hostname?: string;
  };
};

type NamedEntity = {
  id: string;
  displayName?: string;
  hostname?: string;
  name?: string;
};

const dedupeTrimmedValues = (values: Array<string | undefined>): string[] => {
  const seen = new Set<string>();
  const deduped: string[] = [];
  for (const value of values) {
    if (!value) continue;
    const trimmed = value.trim();
    if (!trimmed) continue;
    const normalized = trimmed.toLowerCase();
    if (seen.has(normalized)) continue;
    seen.add(normalized);
    deduped.push(trimmed);
  }

  return deduped;
};

const formatIdentityTarget = (resourceType?: string, resourceId?: string): string | null => {
  const type = asTrimmedString(resourceType);
  const id = asTrimmedString(resourceId);
  return type && id ? `${type}:${id}` : null;
};

const getCanonicalIdentityRecord = (resource: Resource): ResourceCanonicalIdentity | undefined => {
  return resource.canonicalIdentity;
};

export const getPrimaryResourceIdentity = (resource: Resource): string => {
  const canonical = getCanonicalIdentityRecord(resource);
  const canonicalPrimaryId = asTrimmedString(canonical?.primaryId);
  if (canonicalPrimaryId) return canonicalPrimaryId;

  const metricsIdentity = formatIdentityTarget(
    resource.metricsTarget?.resourceType,
    resource.metricsTarget?.resourceId,
  );
  if (metricsIdentity) return metricsIdentity;

  const discoveryIdentity = formatIdentityTarget(
    resource.discoveryTarget?.resourceType,
    resource.discoveryTarget?.resourceId,
  );
  if (discoveryIdentity) return discoveryIdentity;

  const dockerRuntimeId = getActionableDockerRuntimeIdFromResource(resource);
  if (resource.type === 'docker-host' && dockerRuntimeId) {
    return `docker-host:${dockerRuntimeId}`;
  }

  const kubernetesId = getActionableKubernetesClusterIdFromResource(resource);
  if (
    kubernetesId &&
    (resource.type === 'k8s-cluster' || resource.type === 'k8s-node' || resource.type === 'pod')
  ) {
    return `k8s:${kubernetesId}`;
  }

  const agentId = getActionableAgentIdFromResource(resource);
  if (agentId) return `agent:${agentId}`;

  const platformData = getPlatformDataRecord(resource);
  const pbs = platformData?.pbs as Record<string, unknown> | undefined;
  const pmg = platformData?.pmg as Record<string, unknown> | undefined;
  const pbsInstanceId = asTrimmedString(pbs?.instanceId);
  if (pbsInstanceId) return `pbs:${pbsInstanceId}`;
  const pmgInstanceId = asTrimmedString(pmg?.instanceId);
  if (pmgInstanceId) return `pmg:${pmgInstanceId}`;

  return resource.id;
};

export const getResourceIdentityAliases = (resource: Resource): string[] => {
  const canonical = getCanonicalIdentityRecord(resource);
  const platformData = getPlatformDataRecord(resource);
  const platformAgent = getPlatformAgentRecord(resource);
  const proxmox = platformData?.proxmox as Record<string, unknown> | undefined;
  const pbs = platformData?.pbs as Record<string, unknown> | undefined;
  const pmg = platformData?.pmg as Record<string, unknown> | undefined;
  const canonicalAliases = Array.isArray(canonical?.aliases)
    ? canonical.aliases
        .map((alias) => asTrimmedString(alias))
        .filter((alias): alias is string => Boolean(alias))
    : [];
  // Broadcast payloads no longer duplicate superseded canonical ids into the
  // alias list, so identity resolution has to consult them explicitly.
  const canonicalSupersededIds = Array.isArray(canonical?.supersededIds)
    ? canonical.supersededIds
        .map((id) => asTrimmedString(id))
        .filter((id): id is string => Boolean(id))
    : [];

  const raw = [
    ...canonicalAliases,
    ...canonicalSupersededIds,
    resource.metricsTarget?.resourceId,
    resource.discoveryTarget?.agentId,
    resource.discoveryTarget?.resourceId,
    getActionableDockerRuntimeIdFromResource(resource),
    getActionableKubernetesClusterIdFromResource(resource),
    getActionableAgentIdFromResource(resource),
    asTrimmedString(platformData?.linkedAgentId),
    asTrimmedString(proxmox?.nodeName),
    asTrimmedString(platformAgent?.agentId),
    asTrimmedString(platformAgent?.hostname),
    asTrimmedString(pbs?.instanceId),
    asTrimmedString(pbs?.hostname),
    asTrimmedString(pmg?.instanceId),
    asTrimmedString(pmg?.hostname),
    resource.identity?.hostname,
    resource.identity?.machineId,
  ];

  return dedupeTrimmedValues(raw);
};

export const getAgentLikeMetadataIds = (agent: Agent): string[] => {
  const agentRecord = agent as unknown as Record<string, unknown>;
  const discoveryTarget = agentRecord.discoveryTarget as Record<string, unknown> | undefined;
  const platformData = agentRecord.platformData as Record<string, unknown> | undefined;
  const platformAgent = platformData?.agent as Record<string, unknown> | undefined;

  return dedupeTrimmedValues([
    asTrimmedString(discoveryTarget?.resourceId),
    asTrimmedString(discoveryTarget?.agentId),
    asTrimmedString(platformAgent?.agentId),
    asTrimmedString(platformData?.agentId),
    asTrimmedString(platformData?.linkedAgentId),
    asTrimmedString(agent.id),
  ]);
};

const getAgentLikeDiscoveryHostname = (agent?: Agent): string | undefined => {
  if (!agent) return undefined;
  const agentRecord = agent as unknown as Record<string, unknown>;
  const canonical = agentRecord.canonicalIdentity as Record<string, unknown> | undefined;
  const discoveryTarget = agentRecord.discoveryTarget as Record<string, unknown> | undefined;
  const platformData = agentRecord.platformData as Record<string, unknown> | undefined;
  const platformAgent = platformData?.agent as Record<string, unknown> | undefined;

  return (
    asTrimmedString(canonical?.hostname) ||
    asTrimmedString(discoveryTarget?.hostname) ||
    asTrimmedString(agent.hostname) ||
    asTrimmedString(platformAgent?.hostname)
  );
};

export const getInfrastructureMetadataId = (
  node: Pick<Node, 'id' | 'name' | 'linkedAgentId'>,
  agent?: Agent,
): string => {
  const agentMetadataId = agent ? getAgentLikeMetadataIds(agent)[0] : undefined;
  return agentMetadataId || asTrimmedString(node.linkedAgentId) || node.id || node.name;
};

export const getInfrastructureDiscoveryHostname = (
  node: Pick<Node, 'name'>,
  agent?: Pick<Agent, 'hostname'>,
): string => getAgentLikeDiscoveryHostname(agent as Agent | undefined) || node.name;

export const getPreferredConfiguredNodeLabel = (
  node: Pick<NodeConfig, 'displayName' | 'name' | 'host' | 'id'>,
): string =>
  asTrimmedString(node.displayName) ||
  asTrimmedString(node.name) ||
  asTrimmedString(node.host) ||
  node.id;

export const getPreferredNamedEntityLabel = (entity: NamedEntity): string =>
  asTrimmedString(entity.displayName) ||
  asTrimmedString(entity.hostname) ||
  asTrimmedString(entity.name) ||
  entity.id;

export const getPreferredNormalizedPlatformId = (resource: APINormalizedIdentityResource): string =>
  asTrimmedString(resource.proxmox?.nodeName) ||
  asTrimmedString(resource.agent?.hostname) ||
  asTrimmedString(resource.docker?.hostname) ||
  asTrimmedString(resource.name) ||
  resource.id;

export const getPrimaryResourceIdentityRows = (resource: Resource): ResourceIdentityRow[] => {
  const canonical = getCanonicalIdentityRecord(resource);
  const rows: ResourceIdentityRow[] = [];
  const primaryIdentity = getPrimaryResourceIdentity(resource);
  const hostname = asTrimmedString(canonical?.hostname) || resource.identity?.hostname;
  if (hostname) {
    rows.push({ label: 'Hostname', value: hostname });
  }
  const redundantPrimaryIdentityValues = dedupeTrimmedValues([
    asTrimmedString(resource.displayName),
    asTrimmedString(canonical?.displayName),
    asTrimmedString(resource.name),
    hostname,
    asTrimmedString(resource.platformId),
  ]);
  if (
    primaryIdentity &&
    !redundantPrimaryIdentityValues.some(
      (value) => value.toLowerCase() === primaryIdentity.toLowerCase(),
    )
  ) {
    rows.push({ label: 'Primary ID', value: primaryIdentity });
  }
  if (resource.identity?.machineId) {
    rows.push({ label: 'Machine ID', value: resource.identity.machineId });
  }
  if (resource.clusterId) {
    rows.push({ label: 'Cluster', value: resource.clusterId });
  }
  if (resource.parentId) {
    rows.push({ label: 'Parent', value: resource.parentId });
  }

  // Discovery and metrics targets usually point at the resource itself, so
  // they show only when they name something not already on screen: the
  // drawer header's name, the rows above, or the Platform ID row.
  const shownIdentity = (value: string): boolean =>
    [
      getPreferredInfrastructureDisplayName(resource),
      shouldShowResourcePlatformId(resource) ? asTrimmedString(resource.platformId) : undefined,
      ...rows.map((row) => row.value),
    ].some((shown) => Boolean(shown) && shown!.toLowerCase() === value.toLowerCase());

  const discoveryIdentity = formatIdentityTarget(
    resource.discoveryTarget?.resourceType,
    resource.discoveryTarget?.resourceId,
  );
  if (discoveryIdentity && !shownIdentity(discoveryIdentity)) {
    rows.push({ label: 'Discovery', value: discoveryIdentity });
  }

  const metricsIdentity = formatIdentityTarget(
    resource.metricsTarget?.resourceType,
    resource.metricsTarget?.resourceId,
  );
  if (metricsIdentity && !shownIdentity(metricsIdentity)) {
    rows.push({ label: 'Metrics Target', value: metricsIdentity });
  }

  return rows;
};

export const getPreferredResourceHostname = (resource: Resource): string | undefined => {
  const canonical = getCanonicalIdentityRecord(resource);
  const platformData = getPlatformDataRecord(resource);
  const platformAgent = getPlatformAgentRecord(resource);
  const docker = platformData?.docker as Record<string, unknown> | undefined;
  const pbs = platformData?.pbs as Record<string, unknown> | undefined;
  const pmg = platformData?.pmg as Record<string, unknown> | undefined;

  return (
    asTrimmedString(canonical?.hostname) ||
    resource.identity?.hostname ||
    asTrimmedString(platformAgent?.hostname) ||
    asTrimmedString(docker?.hostname) ||
    asTrimmedString(pbs?.hostname) ||
    asTrimmedString(pmg?.hostname) ||
    asTrimmedString(resource.name) ||
    asTrimmedString(resource.platformId)
  );
};

export const shouldShowResourcePlatformId = (resource: Resource): boolean => {
  const canonical = getCanonicalIdentityRecord(resource);
  const platformData = getPlatformDataRecord(resource);
  const platformAgent = getPlatformAgentRecord(resource);
  const docker = platformData?.docker as Record<string, unknown> | undefined;
  const pbs = platformData?.pbs as Record<string, unknown> | undefined;
  const pmg = platformData?.pmg as Record<string, unknown> | undefined;
  const platformId = asTrimmedString(resource.platformId);

  if (!platformId) return false;

  const redundantIdentityValues = dedupeTrimmedValues([
    asTrimmedString(resource.displayName),
    asTrimmedString(canonical?.displayName),
    asTrimmedString(resource.name),
    asTrimmedString(canonical?.hostname),
    resource.identity?.hostname,
    asTrimmedString(platformAgent?.hostname),
    asTrimmedString(docker?.hostname),
    asTrimmedString(pbs?.hostname),
    asTrimmedString(pmg?.hostname),
  ]);

  return !redundantIdentityValues.some((value) => value.toLowerCase() === platformId.toLowerCase());
};

export { getPreferredResourceKubernetesContext };
export { getPreferredResourceClusterName };

export const getPreferredResourceDisplayName = (resource: Resource): string =>
  requiresGovernedResourceDisplay(resource.policy)
    ? getResourcePolicyDisplayLabel(resource)
    : asTrimmedString(resource.displayName) ||
      asTrimmedString(getCanonicalIdentityRecord(resource)?.displayName) ||
      getPreferredResourceHostname(resource) ||
      getPrimaryResourceIdentity(resource);

export const getPreferredInfrastructureDisplayName = (resource: Resource): string =>
  asTrimmedString(resource.displayName) ||
  asTrimmedString(getCanonicalIdentityRecord(resource)?.displayName) ||
  getPreferredResourceHostname(resource) ||
  getPrimaryResourceIdentity(resource);

const IPV4_PATTERN = /^\d{1,3}(\.\d{1,3}){3}$/;

const normalizeIPAddress = (value: string): string => {
  const trimmed = value.trim().replace(/^\[|\]$/g, '');
  if (!trimmed) return '';
  const withoutPrefix = trimmed.split('/', 1)[0] ?? '';
  return withoutPrefix.split('%', 1)[0] ?? '';
};

const isValidIPv4 = (ip: string): boolean => {
  if (!IPV4_PATTERN.test(ip)) return false;
  return ip.split('.').every((part) => {
    const value = Number(part);
    return Number.isInteger(value) && value >= 0 && value <= 255;
  });
};

const isRfc1918Private = (ip: string): boolean => {
  if (!isValidIPv4(ip)) return false;
  const [a, b] = ip.split('.').map(Number);
  return a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168);
};

const isCarrierGradeNat = (ip: string): boolean => {
  if (!isValidIPv4(ip)) return false;
  const [a, b] = ip.split('.').map(Number);
  return a === 100 && b >= 64 && b <= 127;
};

const isUnusableIPAddress = (ip: string): boolean => {
  const normalized = ip.toLowerCase();
  if (isValidIPv4(ip)) {
    const [a, b] = ip.split('.').map(Number);
    return a === 0 || a === 127 || a >= 224 || (a === 169 && b === 254);
  }
  return (
    normalized === '::' ||
    normalized === '::1' ||
    normalized.startsWith('fe80:') ||
    normalized.startsWith('ff')
  );
};

const isVirtualNetworkInterface = (name: string): boolean =>
  /^(?:lo|docker\d*|br-[0-9a-f]+|virbr\d*|veth|cni|flannel|cali|podman|tailscale|zt|wg|tun|tap|utun)/i.test(
    name.trim(),
  );

const addressPreference = (ip: string): number => {
  if (isUnusableIPAddress(ip)) return 100;
  if (isRfc1918Private(ip)) return 0;
  if (isValidIPv4(ip)) return isCarrierGradeNat(ip) ? 30 : 10;
  return ip.includes(':') ? 20 : 90;
};

type AddressCandidate = {
  ip: string;
  score: number;
  order: number;
};

/**
 * Pick the address that most likely represents the machine on its operator-facing
 * network. Physical-interface addresses outrank container bridges and tunnels;
 * routable IPv4 outranks link-local and IPv6 fallback addresses.
 */
export const getPreferredResourceIP = (resource: Resource): string | undefined => {
  const candidates: AddressCandidate[] = [];
  let order = 0;
  for (const networkInterface of resource.agent?.networkInterfaces ?? []) {
    const interfacePenalty = isVirtualNetworkInterface(networkInterface.name) ? 50 : 0;
    for (const value of networkInterface.addresses ?? []) {
      const ip = normalizeIPAddress(value);
      if (!ip) continue;
      candidates.push({ ip, score: addressPreference(ip) + interfacePenalty, order: order++ });
    }
  }
  for (const value of resource.identity?.ips ?? []) {
    const ip = normalizeIPAddress(value);
    if (!ip) continue;
    candidates.push({ ip, score: addressPreference(ip) + 25, order: order++ });
  }

  return candidates
    .filter(
      (candidate, index) =>
        candidates.findIndex((other) => other.ip.toLowerCase() === candidate.ip.toLowerCase()) ===
        index,
    )
    .sort((left, right) => left.score - right.score || left.order - right.order)[0]?.ip;
};

/**
 * When a management URL uses a bare hostname (e.g. "https://pi:8006") that a
 * browser may not resolve, substitute the resource's known LAN IP.
 */
export const resolveGuestUrlWithIdentity = (url: string, resource: Resource): string => {
  if (!url) return url;
  const match = url.match(/^(https?:\/\/)([^:/]+)(:\d+)?(\/.*)?$/i);
  if (!match) return url;
  const [, protocol, hostname, port, path = ''] = match;
  if (IPV4_PATTERN.test(hostname) || hostname.includes(':')) return url;
  if (hostname.includes('.')) return url;
  const ip = getPreferredResourceIP(resource);
  return ip ? `${protocol}${ip}${port || ''}${path}` : url;
};

export const getPreferredWorkloadsAgentHint = (resource: Resource): string | undefined => {
  const platformData = getPlatformDataRecord(resource);
  const proxmox = platformData?.proxmox as Record<string, unknown> | undefined;
  const docker = platformData?.docker as Record<string, unknown> | undefined;
  const truenas = platformData?.truenas as Record<string, unknown> | undefined;

  if (resource.type === 'docker-host') {
    return (
      asTrimmedString(docker?.hostname) || getPreferredResourceHostname(resource) || resource.id
    );
  }

  if (isTrueNASSystemResource(resource)) {
    return (
      asTrimmedString(truenas?.hostname) || getPreferredResourceHostname(resource) || resource.id
    );
  }

  if (resource.type === 'agent') {
    return (
      asTrimmedString(proxmox?.nodeName) || getPreferredResourceHostname(resource) || resource.id
    );
  }

  return undefined;
};