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.0 KB
Raw Blame
import { Show, createMemo, type Component, type JSX } from 'solid-js';
import { StatusDot } from '@/components/shared/StatusDot';
import { TableCell, TableRow } from '@/components/shared/Table';
import { getSimpleStatusIndicator } from '@/utils/status';
import { asTrimmedString } from '@/utils/stringUtils';
import {
  PlatformWindowedRows,
  PLATFORM_HEALTH_FILTER_OPTIONS,
  PlatformResponsiveTableLabel,
  PlatformSortableTableHead,
  PlatformTableEmptyState,
  PlatformTableToolbar,
  createPlatformTableFilterState,
  createPlatformTableSortState,
  formatPlatformTableBytesValue,
  formatPlatformTableTextValue,
  getPlatformTableCellClassForKind,
  PlatformTableShell,
  type PlatformTableSortValue,
  withPlatformStatusCounts,
} from '@/features/platformPage/sharedPlatformPage';
import {
  PlatformResourceDetailToggleButton,
  PlatformResourceDetailTableRow,
  createPlatformResourceDetailState,
  createPlatformResourceLabelResolver,
  getPlatformResourceDetailRowClass,
} from '@/features/platformPage/PlatformResourceDetailTableRow';
import type { Resource } from '@/types/resource';
import {
  filterKubernetesResources,
  kubernetesScopeLabel,
  type KubernetesResourceStatusFilter,
  isSingleKubernetesCluster,
} from './kubernetesPageModel';
import { KubernetesScopeText } from './KubernetesScopeText';

// Kubernetes storage is intentionally not rendered by the generic
// inventory table. StorageClass, PersistentVolume, and
// PersistentVolumeClaim expose different API fields, and operators need
// to see binding mode, reclaim policy, access modes, requested capacity,
// and claim/volume bindings without mentally decoding a catch-all
// "detail" column.

const ACCESS_MODE_LABELS: Record<string, string> = {
  ReadOnlyMany: 'ROX',
  ReadWriteMany: 'RWX',
  ReadWriteOnce: 'RWO',
  ReadWriteOncePod: 'RWOP',
};

const storageName = (resource: Resource): string =>
  asTrimmedString(resource.displayName) || asTrimmedString(resource.name) || resource.id;

const storageKind = (resource: Resource): string => {
  if (resource.type === 'k8s-storage-class') return 'StorageClass';
  if (resource.type === 'k8s-persistent-volume') return 'PV';
  if (resource.type === 'k8s-persistent-volume-claim') return 'PVC';
  return resource.kubernetes?.resourceKind || resource.type;
};

const bindingOrPhase = (resource: Resource): string => {
  if (resource.type === 'k8s-storage-class') {
    return formatPlatformTableTextValue(resource.kubernetes?.volumeBindingMode || 'Immediate');
  }
  return formatPlatformTableTextValue(resource.kubernetes?.phase);
};

const storageClass = (resource: Resource): string => {
  if (resource.type === 'k8s-storage-class') return storageName(resource);
  return formatPlatformTableTextValue(resource.kubernetes?.storageClass);
};

const capacityLabel = (resource: Resource): string => {
  const capacity = resource.kubernetes?.capacityBytes;
  const requested = resource.kubernetes?.requestedBytes;
  if (resource.type === 'k8s-persistent-volume-claim') {
    if (
      typeof capacity === 'number' &&
      capacity > 0 &&
      typeof requested === 'number' &&
      requested > 0
    ) {
      if (capacity !== requested) {
        return `${formatPlatformTableBytesValue(capacity)} / ${formatPlatformTableBytesValue(requested)} req`;
      }
      return formatPlatformTableBytesValue(capacity);
    }
    if (typeof requested === 'number' && requested > 0) {
      return `${formatPlatformTableBytesValue(requested)} req`;
    }
  }
  if (typeof capacity === 'number' && capacity > 0) return formatPlatformTableBytesValue(capacity);
  return '—';
};

const summarizeAccessModes = (
  accessModes: string[] | undefined,
): { label: string; title: string } => {
  const modes = (accessModes ?? [])
    .map((mode) => asTrimmedString(mode))
    .filter((mode): mode is string => typeof mode === 'string' && mode.length > 0);
  if (modes.length === 0) return { label: '—', title: '' };
  return {
    label: modes.map((mode) => ACCESS_MODE_LABELS[mode] || mode).join(', '),
    title: modes.join(', '),
  };
};

const policyLabel = (resource: Resource): { label: string; title: string } => {
  const accessModes = summarizeAccessModes(resource.kubernetes?.accessModes);
  const parts = accessModes.label === '—' ? [] : [accessModes.label];
  const titleParts = accessModes.title ? [accessModes.title] : [];
  const reclaimPolicy = asTrimmedString(resource.kubernetes?.reclaimPolicy);
  if (reclaimPolicy) {
    parts.push(reclaimPolicy);
    titleParts.push(`Reclaim: ${reclaimPolicy}`);
  }
  if (
    resource.type === 'k8s-storage-class' &&
    resource.kubernetes?.allowVolumeExpansion !== undefined
  ) {
    const expansion = resource.kubernetes.allowVolumeExpansion ? 'Expandable' : 'Fixed';
    parts.push(expansion);
    titleParts.push(`Volume expansion: ${expansion}`);
  }
  return { label: parts.join(' · ') || '—', title: titleParts.join(' · ') };
};

const bindingTarget = (resource: Resource): { label: string; title: string } => {
  if (resource.type === 'k8s-storage-class') {
    const provisioner = formatPlatformTableTextValue(resource.kubernetes?.provisioner);
    const parameterKeys = resource.kubernetes?.parameterKeys ?? [];
    return {
      label: provisioner,
      title:
        parameterKeys.length > 0
          ? `${provisioner} · params: ${parameterKeys.join(', ')}`
          : provisioner,
    };
  }
  if (resource.type === 'k8s-persistent-volume') {
    const claim = [resource.kubernetes?.claimNamespace, resource.kubernetes?.claimName]
      .map((value) => asTrimmedString(value))
      .filter(Boolean)
      .join('/');
    return { label: claim || 'Unclaimed', title: claim || 'Unclaimed' };
  }
  const volumeName = asTrimmedString(resource.kubernetes?.volumeName);
  return { label: volumeName || 'Unbound', title: volumeName || 'Unbound' };
};

// Access / policy is a composite label (access modes + reclaim policy +
// expansion), so it stays non-sortable. Size sorts on the same bytes the
// capacity label renders (capacity, falling back to the PVC request).
const KUBERNETES_STORAGE_SORT_KEYS = [
  'resource',
  'kind',
  'scope',
  'phase',
  'class',
  'size',
  'provider',
] as const;

type KubernetesStorageSortKey = (typeof KUBERNETES_STORAGE_SORT_KEYS)[number];

const getKubernetesStorageSortValue = (
  resource: Resource,
  key: KubernetesStorageSortKey,
): PlatformTableSortValue => {
  switch (key) {
    case 'resource':
      return storageName(resource);
    case 'kind':
      return storageKind(resource);
    case 'scope':
      return kubernetesScopeLabel(resource);
    case 'phase': {
      const phase = bindingOrPhase(resource);
      return phase === '—' ? null : phase;
    }
    case 'class': {
      const klass = storageClass(resource);
      return klass === '—' ? null : klass;
    }
    case 'size': {
      const capacity = resource.kubernetes?.capacityBytes;
      if (typeof capacity === 'number' && capacity > 0) return capacity;
      const requested = resource.kubernetes?.requestedBytes;
      if (
        resource.type === 'k8s-persistent-volume-claim' &&
        typeof requested === 'number' &&
        requested > 0
      ) {
        return requested;
      }
      return null;
    }
    case 'provider': {
      const target = bindingTarget(resource).label;
      return target === '—' ? null : target;
    }
    default:
      key satisfies never;
      return null;
  }
};

export const KubernetesStorageTable: Component<{
  resources: Resource[];
  emptyIcon: JSX.Element;
  emptyTitle: string;
  emptyDescription: string;
  title?: string;
  showToolbar?: boolean;
}> = (props) => {
  const singleCluster = createMemo(() => isSingleKubernetesCluster(props.resources));
  const tableState = createPlatformTableFilterState({
    resources: () => props.resources,
    initialStatus: 'all' as KubernetesResourceStatusFilter,
    filter: filterKubernetesResources,
  });
  const drawer = createPlatformResourceDetailState({ idPrefix: 'kubernetes-storage-drawer' });
  const resolveResourceLabel = createPlatformResourceLabelResolver(() => props.resources);
  const sort = createPlatformTableSortState({
    storageKey: 'kubernetesStorage',
    sortKeys: KUBERNETES_STORAGE_SORT_KEYS,
    descendingFirst: ['size'],
  });
  const sortedRows = createMemo(() =>
    sort.sortRows(tableState.filtered(), getKubernetesStorageSortValue),
  );

  return (
    <Show
      when={props.resources.length > 0}
      fallback={
        <PlatformTableEmptyState
          icon={props.emptyIcon}
          title={props.emptyTitle}
          description={props.emptyDescription}
        />
      }
    >
      <div class="space-y-3">
        <Show when={props.showToolbar !== false}>
          <PlatformTableToolbar
            search={tableState.search}
            onSearchChange={tableState.setSearch}
            searchPlaceholder="Search storage inventory"
            searchSuggestions={tableState.searchSuggestions}
            status={tableState.status()}
            onStatusChange={tableState.setStatus}
            statusOptions={withPlatformStatusCounts(
              PLATFORM_HEALTH_FILTER_OPTIONS,
              tableState.countForStatus,
            )}
            visible={tableState.visible()}
            total={tableState.total()}
            rowNoun="storage resources"
          />
        </Show>

        <Show
          when={tableState.filtered().length > 0}
          fallback={
            <PlatformTableEmptyState
              icon={props.emptyIcon}
              title="No volume resources match current filters"
              description="Adjust the search or status filter to see more Kubernetes volume resources."
            />
          }
        >
          <PlatformTableShell
            title={props.title ?? 'Storage Classes, Volumes, and Claims'}
            tableClass="min-w-full table-fixed text-xs md:min-w-[1120px]"
            header={
              <>
                <PlatformSortableTableHead
                  kind="name"
                  sort={sort}
                  sortKey="resource"
                  class="platform-table-mobile-w-30 md:w-[22%]"
                >
                  Resource
                </PlatformSortableTableHead>
                <PlatformSortableTableHead
                  kind="text"
                  sort={sort}
                  sortKey="kind"
                  class="platform-table-mobile-w-15 md:w-[10%]"
                >
                  Kind
                </PlatformSortableTableHead>
                <PlatformSortableTableHead
                  kind="text"
                  sort={sort}
                  sortKey="scope"
                  class="hidden sm:table-cell md:w-[13%]"
                >
                  Scope
                </PlatformSortableTableHead>
                <PlatformSortableTableHead
                  kind="text"
                  sort={sort}
                  sortKey="phase"
                  class="platform-table-mobile-w-20 md:w-[14%]"
                >
                  <PlatformResponsiveTableLabel compact="State" full="Binding / phase" />
                </PlatformSortableTableHead>
                <PlatformSortableTableHead
                  kind="text"
                  sort={sort}
                  sortKey="class"
                  class="platform-table-mobile-w-20 md:w-[10%]"
                >
                  Class
                </PlatformSortableTableHead>
                <PlatformSortableTableHead
                  kind="numeric-value"
                  sort={sort}
                  sortKey="size"
                  class="platform-table-mobile-w-15 md:w-[8%]"
                >
                  Size
                </PlatformSortableTableHead>
                <PlatformSortableTableHead
                  kind="text"
                  sort={sort}
                  class="hidden md:table-cell md:w-[12%]"
                >
                  Access / policy
                </PlatformSortableTableHead>
                <PlatformSortableTableHead
                  kind="text"
                  sort={sort}
                  sortKey="provider"
                  class="hidden md:table-cell md:w-[14%]"
                >
                  Provider / binding
                </PlatformSortableTableHead>
              </>
            }
            body={
              <>
                <PlatformWindowedRows items={sortedRows} estimatedRowHeight={32}>
                  {(resource) => {
                    const indicator = () => getSimpleStatusIndicator(resource.status);
                    const name = () => storageName(resource);
                    const kind = () => storageKind(resource);
                    const policy = () => policyLabel(resource);
                    const target = () => bindingTarget(resource);
                    const detailRowId = () => drawer.detailRowId(resource);
                    const isExpanded = () => drawer.isExpanded(resource);

                    return (
                      <>
                        <TableRow
                          class={`${getPlatformResourceDetailRowClass(isExpanded())} text-[11px] sm:text-xs`}
                          data-kubernetes-storage-row={resource.id}
                          onClick={() => drawer.toggle(resource)}
                        >
                          <TableCell class={getPlatformTableCellClassForKind('name')}>
                            <div class="flex min-w-0 items-center gap-2">
                              <PlatformResourceDetailToggleButton
                                expanded={isExpanded()}
                                resourceLabel={name()}
                                controlsId={detailRowId()}
                                onToggle={() => drawer.toggle(resource)}
                              />
                              <StatusDot
                                size="sm"
                                variant={indicator().variant}
                                title={resource.status || 'unknown'}
                                ariaHidden
                              />
                              <span class="truncate font-semibold text-base-content" title={name()}>
                                {name()}
                              </span>
                            </div>
                          </TableCell>
                          <TableCell
                            class={`${getPlatformTableCellClassForKind('text')} text-base-content`}
                          >
                            {kind()}
                          </TableCell>
                          <TableCell
                            class={`${getPlatformTableCellClassForKind('text')} hidden text-base-content sm:table-cell`}
                          >
                            <KubernetesScopeText
                              resource={resource}
                              singleCluster={singleCluster()}
                              class="block truncate"
                            />
                          </TableCell>
                          <TableCell
                            class={`${getPlatformTableCellClassForKind('text')} text-base-content`}
                          >
                            {bindingOrPhase(resource)}
                          </TableCell>
                          <TableCell
                            class={`${getPlatformTableCellClassForKind('text')} text-base-content`}
                          >
                            {storageClass(resource)}
                          </TableCell>
                          <TableCell
                            class={`${getPlatformTableCellClassForKind('numeric-value')} text-base-content tabular-nums`}
                          >
                            {capacityLabel(resource)}
                          </TableCell>
                          <TableCell
                            class={`${getPlatformTableCellClassForKind('text')} hidden text-base-content md:table-cell`}
                          >
                            <span class="block truncate" title={policy().title}>
                              {policy().label}
                            </span>
                          </TableCell>
                          <TableCell
                            class={`${getPlatformTableCellClassForKind('text')} hidden text-base-content md:table-cell`}
                          >
                            <span class="block truncate" title={target().title}>
                              {target().label}
                            </span>
                          </TableCell>
                        </TableRow>
                        <PlatformResourceDetailTableRow
                          resource={resource}
                          statusIndicator={indicator()}
                          open={isExpanded()}
                          detailRowId={detailRowId()}
                          colSpan={8}
                          resolveResourceLabel={resolveResourceLabel}
                          onClose={() => drawer.close(resource)}
                        />
                      </>
                    );
                  }}
                </PlatformWindowedRows>
              </>
            }
          />
        </Show>
      </div>
    </Show>
  );
};

export default KubernetesStorageTable;