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.

16.0 KB
Raw Blame
import type { Accessor } from 'solid-js';
import { getAllFilterOptionLabel } from '@/components/shared/filterOptionPresentation';
import type { StorageHealthFilter, StorageRecord } from '@/features/storageBackups/models';
import {
  DEFAULT_PHYSICAL_DISK_FACET_FILTER,
  normalizePhysicalDiskFacetFilter,
} from '@/features/storageBackups/diskPresentation';
import { isCephStorageRecord } from '@/features/storageBackups/cephRecordPresentation';
import type { Resource } from '@/types/resource';
import { getProxmoxData } from '@/utils/resourcePlatformData';
import { getResourceIdentityAliases } from '@/utils/resourceIdentity';
import { normalizeSourcePlatformQueryValue } from '@/utils/sourcePlatforms';
import { storageSourceMatchesFilter } from '@/utils/storageSources';
import { matchesPhysicalDiskNode } from './diskResourceUtils';
import type { StorageGroupKey, StorageSortKey } from './useStorageModel';
import type { StorageRouteStateFields } from './useStorageRouteState';

export type StorageView = 'pools' | 'disks';
export type StorageStatusFilterValue =
  'all' | 'attention' | 'available' | 'warning' | 'critical' | 'offline' | 'unknown';

export interface StorageOption {
  value: string;
  label: string;
}

export interface StorageFilterActivityState {
  search: string;
  sortKey: string;
  sortDirection: 'asc' | 'desc';
  groupBy?: StorageGroupKey;
  statusFilter?: StorageStatusFilterValue;
  sourceFilter?: string;
  diskRoleFilter?: string;
  diskGroupFilter?: string;
}

export const DEFAULT_STORAGE_VIEW: StorageView = 'pools';
export const DEFAULT_STORAGE_SELECTED_NODE_ID = 'all';
export const DEFAULT_STORAGE_SOURCE_FILTER = 'all';
export const DEFAULT_STORAGE_DISK_ROLE_FILTER = DEFAULT_PHYSICAL_DISK_FACET_FILTER;
export const DEFAULT_STORAGE_DISK_GROUP_FILTER = DEFAULT_PHYSICAL_DISK_FACET_FILTER;
export const DEFAULT_STORAGE_SORT_KEY: StorageSortKey = 'priority';
export const DEFAULT_STORAGE_SORT_DIRECTION: 'asc' | 'desc' = 'desc';
export const DEFAULT_STORAGE_GROUP_KEY: StorageGroupKey = 'none';
export const DEFAULT_STORAGE_STATUS_FILTER: StorageStatusFilterValue = 'all';

export type StoragePageNodeOption = {
  id: string;
  label: string;
  instance?: string;
  aliases?: string[];
};

export const DEFAULT_STORAGE_SORT_OPTIONS: Array<{ value: StorageSortKey; label: string }> = [
  { value: 'priority', label: 'Priority' },
  { value: 'name', label: 'Storage' },
  { value: 'state', label: 'State' },
  { value: 'usage', label: 'Usage %' },
  { value: 'type', label: 'Type' },
  { value: 'host', label: 'Host' },
  { value: 'protection', label: 'Protection' },
  { value: 'growth', label: 'Growth' },
];

export const STORAGE_STATUS_FILTER_OPTIONS: StorageOption[] = [
  { value: 'all', label: 'All' },
  { value: 'attention', label: 'Needs attention' },
  { value: 'available', label: 'Healthy' },
  { value: 'warning', label: 'Warning' },
  { value: 'critical', label: 'Critical' },
  { value: 'offline', label: 'Offline' },
  { value: 'unknown', label: 'Unknown' },
];

export const STORAGE_GROUP_BY_OPTIONS: StorageOption[] = [
  { value: 'none', label: 'Flat' },
  { value: 'node', label: 'By node' },
  { value: 'type', label: 'By type' },
  { value: 'status', label: 'By status' },
];

export const normalizeStorageHealthFilter = (value: string): StorageHealthFilter => {
  const normalized = (value || '').trim().toLowerCase();
  if (!normalized || normalized === 'all') return 'all';
  if (
    normalized === 'attention' ||
    normalized === 'needs-attention' ||
    normalized === 'issue' ||
    normalized === 'issues' ||
    normalized === 'unhealthy'
  ) {
    return 'attention';
  }
  if (normalized === 'available' || normalized === 'online' || normalized === 'healthy') {
    return 'healthy';
  }
  if (normalized === 'degraded' || normalized === 'warning') return 'warning';
  if (normalized === 'critical') return 'critical';
  if (normalized === 'offline') return 'offline';
  if (normalized === 'unknown') return 'unknown';
  return 'all';
};

const normalizeStorageRouteToken = (value: string): string => value.trim().toLowerCase();

const normalizeStorageRouteSelection = (value: string | undefined): string => {
  const normalized = (value || '').trim();
  return normalized.toLowerCase() === DEFAULT_STORAGE_SELECTED_NODE_ID
    ? DEFAULT_STORAGE_SELECTED_NODE_ID
    : normalized;
};

export const normalizeStorageSortKey = (value: string): StorageSortKey => {
  const normalized = normalizeStorageRouteToken(value);
  if (
    normalized === 'priority' ||
    normalized === 'name' ||
    normalized === 'state' ||
    normalized === 'usage' ||
    normalized === 'type' ||
    normalized === 'host' ||
    normalized === 'protection' ||
    normalized === 'growth'
  ) {
    return normalized;
  }
  // 'source' persisted from before the Source column was demoted to the row
  // expansion folds back to the default here.
  return 'priority';
};

export const getDefaultStorageSortDirection = (sortKey: StorageSortKey): 'asc' | 'desc' =>
  sortKey === 'priority' || sortKey === 'usage' || sortKey === 'growth' ? 'desc' : 'asc';

export const normalizeStorageGroupKey = (value: string): StorageGroupKey => {
  const normalized = normalizeStorageRouteToken(value);
  if (
    normalized === 'none' ||
    normalized === 'node' ||
    normalized === 'type' ||
    normalized === 'status'
  ) {
    return normalized;
  }
  return 'none';
};

export const normalizeStorageView = (value: string): StorageView =>
  normalizeStorageRouteToken(value) === 'disks' ? 'disks' : 'pools';

export const normalizeStorageSortDirection = (value: string): 'asc' | 'desc' =>
  normalizeStorageRouteToken(value) === 'asc' ? 'asc' : 'desc';

export const getStorageFilterGroupBy = (
  value: StorageGroupKey,
): 'node' | 'type' | 'status' | 'none' =>
  value === 'type' || value === 'status' || value === 'none' ? value : 'node';

export const getStorageStatusFilterValue = (
  value: StorageHealthFilter,
): StorageStatusFilterValue => {
  if (value === 'all') return 'all';
  if (value === 'attention') return 'attention';
  if (value === 'healthy') return 'available';
  return value;
};

export const toStorageHealthFilterValue = (
  value: StorageStatusFilterValue,
): StorageHealthFilter => {
  if (value === 'all') return 'all';
  if (value === 'attention') return 'attention';
  if (value === 'available') return 'healthy';
  return value;
};

export const countActiveStorageFilters = (state: StorageFilterActivityState): number => {
  let count = 0;
  if (state.search.trim() !== '') count++;
  if ((state.groupBy || 'none') !== 'none') count++;
  if ((state.statusFilter || 'all') !== 'all') count++;
  if ((state.sourceFilter || 'all') !== 'all') count++;
  if (
    (state.diskRoleFilter || DEFAULT_STORAGE_DISK_ROLE_FILTER) !== DEFAULT_STORAGE_DISK_ROLE_FILTER
  )
    count++;
  if (
    (state.diskGroupFilter || DEFAULT_STORAGE_DISK_GROUP_FILTER) !==
    DEFAULT_STORAGE_DISK_GROUP_FILTER
  )
    count++;
  return count;
};

export const hasActiveStorageFilters = (state: StorageFilterActivityState): boolean =>
  state.search.trim() !== '' ||
  state.sortKey !== DEFAULT_STORAGE_SORT_KEY ||
  state.sortDirection !== DEFAULT_STORAGE_SORT_DIRECTION ||
  (state.groupBy || DEFAULT_STORAGE_GROUP_KEY) !== DEFAULT_STORAGE_GROUP_KEY ||
  (state.statusFilter || DEFAULT_STORAGE_STATUS_FILTER) !== DEFAULT_STORAGE_STATUS_FILTER ||
  (state.sourceFilter || DEFAULT_STORAGE_SOURCE_FILTER) !== DEFAULT_STORAGE_SOURCE_FILTER ||
  (state.diskRoleFilter || DEFAULT_STORAGE_DISK_ROLE_FILTER) !== DEFAULT_STORAGE_DISK_ROLE_FILTER ||
  (state.diskGroupFilter || DEFAULT_STORAGE_DISK_GROUP_FILTER) !==
    DEFAULT_STORAGE_DISK_GROUP_FILTER;

export const getStorageNodeFilterLabel = (view: StorageView): string =>
  view === 'disks' ? getAllFilterOptionLabel('disk hosts') : getAllFilterOptionLabel('nodes');

export const readStorageRouteValue = (value: string | undefined, defaultValue: string): string => {
  const normalized = (value || '').trim();
  return normalized || defaultValue;
};

export const writeStorageRouteValue = (value: string, defaultValue: string): string | null =>
  value !== defaultValue ? value : null;

type StorageRouteFieldBuilderOptions = {
  view: Accessor<StorageView>;
  setView: (value: StorageView) => void;
  sourceFilter: Accessor<string>;
  setSourceFilter: (value: string) => void;
  healthFilter: Accessor<StorageHealthFilter>;
  setHealthFilter: (value: StorageHealthFilter) => void;
  diskRoleFilter: Accessor<string>;
  setDiskRoleFilter: (value: string) => void;
  diskGroupFilter: Accessor<string>;
  setDiskGroupFilter: (value: string) => void;
  selectedNodeId: Accessor<string>;
  setSelectedNodeId: (value: string) => void;
  groupBy: Accessor<StorageGroupKey>;
  setGroupBy: (value: StorageGroupKey) => void;
  sortKey: Accessor<StorageSortKey>;
  setSortKey: (value: StorageSortKey) => void;
  sortDirection: Accessor<'asc' | 'desc'>;
  setSortDirection: (value: 'asc' | 'desc') => void;
  search: Accessor<string>;
  setSearch: (value: string) => void;
};

export const buildStorageRouteFields = (
  options: StorageRouteFieldBuilderOptions,
): StorageRouteStateFields => ({
  tab: {
    get: options.view,
    set: options.setView,
    read: (parsed) => normalizeStorageView(parsed.tab),
    write: (value) => (value !== DEFAULT_STORAGE_VIEW ? value : null),
  },
  source: {
    get: options.sourceFilter,
    set: options.setSourceFilter,
    read: (parsed) =>
      normalizeSourcePlatformQueryValue(
        readStorageRouteValue(parsed.source, DEFAULT_STORAGE_SOURCE_FILTER),
      ) || DEFAULT_STORAGE_SOURCE_FILTER,
    write: (value) =>
      writeStorageRouteValue(
        normalizeSourcePlatformQueryValue(value) || DEFAULT_STORAGE_SOURCE_FILTER,
        DEFAULT_STORAGE_SOURCE_FILTER,
      ),
  },
  status: {
    get: options.healthFilter,
    set: options.setHealthFilter,
    read: (parsed) => normalizeStorageHealthFilter(parsed.status),
    write: (value) =>
      writeStorageRouteValue(getStorageStatusFilterValue(value), DEFAULT_STORAGE_STATUS_FILTER),
  },
  diskRole: {
    get: options.diskRoleFilter,
    set: options.setDiskRoleFilter,
    read: (parsed) => normalizePhysicalDiskFacetFilter(parsed.diskRole),
    write: (value) =>
      writeStorageRouteValue(
        normalizePhysicalDiskFacetFilter(value),
        DEFAULT_STORAGE_DISK_ROLE_FILTER,
      ),
  },
  diskGroup: {
    get: options.diskGroupFilter,
    set: options.setDiskGroupFilter,
    read: (parsed) => normalizePhysicalDiskFacetFilter(parsed.diskGroup),
    write: (value) =>
      writeStorageRouteValue(
        normalizePhysicalDiskFacetFilter(value),
        DEFAULT_STORAGE_DISK_GROUP_FILTER,
      ),
  },
  node: {
    get: options.selectedNodeId,
    set: options.setSelectedNodeId,
    read: (parsed) =>
      normalizeStorageRouteSelection(parsed.node) || DEFAULT_STORAGE_SELECTED_NODE_ID,
    write: (value) =>
      writeStorageRouteValue(
        normalizeStorageRouteSelection(value) || DEFAULT_STORAGE_SELECTED_NODE_ID,
        DEFAULT_STORAGE_SELECTED_NODE_ID,
      ),
  },
  group: {
    get: options.groupBy,
    set: options.setGroupBy,
    read: (parsed) => normalizeStorageGroupKey(parsed.group),
    write: (value) => writeStorageRouteValue(value, DEFAULT_STORAGE_GROUP_KEY),
  },
  sort: {
    get: options.sortKey,
    set: options.setSortKey,
    read: (parsed) => normalizeStorageSortKey(parsed.sort),
    write: (value) => writeStorageRouteValue(value, DEFAULT_STORAGE_SORT_KEY),
  },
  order: {
    get: options.sortDirection,
    set: options.setSortDirection,
    read: (parsed) => normalizeStorageSortDirection(parsed.order),
    write: (value) => writeStorageRouteValue(value, DEFAULT_STORAGE_SORT_DIRECTION),
  },
  query: {
    get: options.search,
    set: options.setSearch,
    read: (parsed) => (parsed.query || '').trim(),
    write: (value) => value.trim() || null,
  },
});

export const coerceSelectedStorageNodeId = (
  selectedNodeId: string,
  nodeOptions: StoragePageNodeOption[],
): string =>
  selectedNodeId === DEFAULT_STORAGE_SELECTED_NODE_ID ||
  nodeOptions.some((node) => node.id === selectedNodeId)
    ? selectedNodeId
    : DEFAULT_STORAGE_SELECTED_NODE_ID;

export const buildStorageNodeFilterOptions = (
  view: StorageView,
  nodeOptions: StoragePageNodeOption[],
): StorageOption[] => [
  { value: DEFAULT_STORAGE_SELECTED_NODE_ID, label: getStorageNodeFilterLabel(view) },
  ...nodeOptions.map((node) => ({ value: node.id, label: node.label })),
];

export const getStorageMetaBoolean = (
  record: StorageRecord,
  key: 'isCeph' | 'isZfs',
): boolean | null => {
  const details = (record.details || {}) as Record<string, unknown>;
  const value = details[key];
  return typeof value === 'boolean' ? value : null;
};

export const isStorageRecordCeph = (record: StorageRecord): boolean => {
  const isCephMeta = getStorageMetaBoolean(record, 'isCeph');
  if (isCephMeta !== null) return isCephMeta;
  return isCephStorageRecord(record);
};

export const buildStorageNodeOptions = (nodes: Resource[]): StoragePageNodeOption[] =>
  nodes.map((node) => ({
    id: node.id,
    label: node.name,
    instance: getProxmoxData(node)?.instance,
    aliases: getResourceIdentityAliases(node),
  }));

export const storageResourceMatchesSourceFilter = (
  resource: Resource,
  sourceFilter: string,
): boolean => {
  const selectedSource = normalizeSourcePlatformQueryValue(sourceFilter);
  if (!selectedSource || selectedSource === DEFAULT_STORAGE_SOURCE_FILTER) return true;

  const platformData = resource.platformData as { sources?: unknown } | undefined;
  const sources = Array.isArray(platformData?.sources)
    ? platformData.sources.filter((source): source is string => typeof source === 'string')
    : [];
  const candidates = [resource.platformType, resource.sourceType, ...sources];
  return candidates.some((candidate) =>
    storageSourceMatchesFilter(normalizeSourcePlatformQueryValue(candidate || ''), selectedSource),
  );
};

export const filterStorageDiskNodeOptions = (
  nodeOptions: StoragePageNodeOption[],
  physicalDisks: Resource[],
): StoragePageNodeOption[] =>
  nodeOptions.filter((node) =>
    physicalDisks.some((disk) =>
      matchesPhysicalDiskNode(disk, {
        id: node.id,
        name: node.label,
        instance: node.instance,
      }),
    ),
  );

export const getActiveStorageNodeOptions = (
  view: StorageView,
  nodeOptions: StoragePageNodeOption[],
  diskNodeOptions: StoragePageNodeOption[],
): StoragePageNodeOption[] => (view === 'disks' ? diskNodeOptions : nodeOptions);

export const buildStorageNodeOnlineByLabel = (nodes: Resource[]): Map<string, boolean> => {
  const map = new Map<string, boolean>();
  nodes.forEach((node) => {
    const key = (node.name || '').trim().toLowerCase();
    if (!key) return;
    const hasNodeStatus = typeof node.status === 'string' && node.status.trim().length > 0;
    const hasNodeUptime = typeof node.uptime === 'number';
    if (!hasNodeStatus && !hasNodeUptime) {
      return;
    }
    map.set(key, node.status === 'online' && (node.uptime || 0) > 0);
  });
  return map;
};

// Groups open by default and only the groups the operator collapsed are stored,
// so a live update that rebuilds the group list never reopens a collapsed one.
export const resolveExpandedStorageGroups = (
  allKeys: readonly string[],
  collapsed: ReadonlySet<string>,
): Set<string> => new Set(allKeys.filter((key) => !collapsed.has(key)));

export const haveSameStorageGroups = (a: ReadonlySet<string>, b: ReadonlySet<string>): boolean =>
  a.size === b.size && [...a].every((key) => b.has(key));

export const toggleCollapsedStorageGroup = (previous: Set<string>, key: string): Set<string> => {
  const next = new Set(previous);
  if (next.has(key)) next.delete(key);
  else next.add(key);
  return next;
};

export const countVisiblePhysicalDisksForNode = (
  selectedNodeId: string,
  nodeOptions: StoragePageNodeOption[],
  physicalDisks: Resource[],
): number => {
  if (selectedNodeId === 'all') return physicalDisks.length;
  const node = nodeOptions.find((candidate) => candidate.id === selectedNodeId);
  if (!node) return physicalDisks.length;
  return physicalDisks.filter((disk) =>
    matchesPhysicalDiskNode(disk, { id: node.id, name: node.label, instance: node.instance }),
  ).length;
};