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.

19.5 KB
Raw Blame
import { createMemo, Show, type Component, type JSX } from 'solid-js';
import { StatusDot } from '@/components/shared/StatusDot';
import {
  compactDetailRows,
  makeDetailRow,
  type DetailSection,
} from '@/components/shared/DetailSectionTable';
import { InlineDetailTableRow } from '@/components/shared/InlineDetailTableRow';
import { TableCell, TableHead, TableRow } from '@/components/shared/Table';
import { getSimpleStatusIndicator } from '@/utils/status';
import { asTrimmedString } from '@/utils/stringUtils';
import {
  PlatformWindowedRows,
  PLATFORM_HEALTH_FILTER_OPTIONS,
  PlatformResponsiveTableLabel,
  PlatformTableEmptyState,
  PlatformTableToolbar,
  createPlatformTableFilterState,
  formatPlatformTableTextValue,
  getPlatformTableCellClassForKind,
  getPlatformTableHeadClassForKind,
  summarizePlatformTableValues,
  PlatformTableShell,
  withPlatformStatusCounts,
  platformTableBandWidthStyle,
} from '@/features/platformPage/sharedPlatformPage';
import {
  PlatformResourceDetailToggleButton,
  createPlatformResourceDetailState,
  getPlatformResourceDetailRowClass,
} from '@/features/platformPage/PlatformResourceDetailTableRow';
import type { Resource } from '@/types/resource';
import {
  filterKubernetesResources,
  type KubernetesResourceStatusFilter,
  isSingleKubernetesCluster,
} from './kubernetesPageModel';
import {
  KubernetesRecordDetailPanel,
  kubernetesLabelsSection,
  kubernetesObjectSection,
} from './KubernetesRecordDetail';
import { KubernetesScopeText } from './KubernetesScopeText';

// Kubernetes policy resources carry very different API fields. Keep this table
// on the documented NetworkPolicy, PDB, ResourceQuota, and LimitRange shapes
// instead of collapsing them into generic spec/detail text.

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

const policyKind = (resource: Resource): string => {
  if (resource.type === 'k8s-network-policy') return 'NetworkPolicy';
  if (resource.type === 'k8s-pod-disruption-budget') return 'PodDisruptionBudget';
  if (resource.type === 'k8s-resource-quota') return 'ResourceQuota';
  if (resource.type === 'k8s-limit-range') return 'LimitRange';
  return resource.kubernetes?.resourceKind || resource.type;
};

const plural = (count: number, singular: string, pluralLabel = `${singular}s`): string =>
  `${count} ${count === 1 ? singular : pluralLabel}`;

const policyTypes = (resource: Resource): { label: string; title: string } => {
  const explicit = summarizePlatformTableValues(resource.kubernetes?.policyTypes);
  if (explicit.label !== '—') return explicit;

  const inferred = [
    typeof resource.kubernetes?.ingressRuleCount === 'number' ? 'Ingress' : undefined,
    typeof resource.kubernetes?.egressRuleCount === 'number' ? 'Egress' : undefined,
  ];
  return summarizePlatformTableValues(inferred);
};

const quotaKeys = (resource: Resource): string[] => {
  const hard = resource.kubernetes?.hard ?? {};
  const used = resource.kubernetes?.used ?? {};
  return Array.from(new Set([...Object.keys(hard), ...Object.keys(used)])).sort();
};

const quotaUsage = (resource: Resource, visible = 2): { label: string; title: string } => {
  const keys = quotaKeys(resource);
  if (keys.length === 0) return { label: 'No quota values', title: '' };
  const hard = resource.kubernetes?.hard ?? {};
  const used = resource.kubernetes?.used ?? {};
  const values = keys.map((key) => `${key} ${used[key] ?? '0'}/${hard[key] ?? '—'}`);
  return summarizePlatformTableValues(values, { maxVisible: visible });
};

const pdbBudget = (resource: Resource): string => {
  const parts = [
    resource.kubernetes?.minAvailable ? `min ${resource.kubernetes.minAvailable}` : undefined,
    resource.kubernetes?.maxUnavailable
      ? `max unavailable ${resource.kubernetes.maxUnavailable}`
      : undefined,
  ].filter(Boolean);
  return parts.join(', ') || 'Availability budget';
};

const pdbHealth = (resource: Resource): string => {
  const healthy =
    typeof resource.kubernetes?.currentHealthy === 'number' ||
    typeof resource.kubernetes?.desiredHealthy === 'number'
      ? `${resource.kubernetes?.currentHealthy ?? 0}/${resource.kubernetes?.desiredHealthy ?? 0} healthy`
      : undefined;
  const disruptions =
    typeof resource.kubernetes?.disruptionsAllowed === 'number'
      ? `${resource.kubernetes.disruptionsAllowed} disruptions`
      : undefined;
  const expected =
    typeof resource.kubernetes?.expectedPods === 'number'
      ? plural(resource.kubernetes.expectedPods, 'pod')
      : undefined;
  return [healthy, disruptions, expected].filter(Boolean).join(', ') || 'No status reported';
};

const networkPolicyRules = (resource: Resource): string => {
  const rules = [
    typeof resource.kubernetes?.ingressRuleCount === 'number'
      ? `${resource.kubernetes.ingressRuleCount} ingress`
      : undefined,
    typeof resource.kubernetes?.egressRuleCount === 'number'
      ? `${resource.kubernetes.egressRuleCount} egress`
      : undefined,
  ].filter(Boolean);
  return rules.join(', ') || 'No rules reported';
};

const policyShape = (resource: Resource): { label: string; title: string } => {
  if (resource.type === 'k8s-network-policy') {
    const types = policyTypes(resource);
    if (types.label !== '—') {
      return {
        label: `${types.label} policy`,
        title: types.title ? `${types.title} policy` : '',
      };
    }
    return { label: 'Network policy', title: '' };
  }
  if (resource.type === 'k8s-pod-disruption-budget') {
    return { label: 'Availability budget', title: '' };
  }
  if (resource.type === 'k8s-resource-quota') {
    return { label: 'Quota', title: '' };
  }
  if (resource.type === 'k8s-limit-range') {
    return { label: 'Limit range', title: '' };
  }
  return { label: formatPlatformTableTextValue(resource.kubernetes?.resourceKind), title: '' };
};

const policySpec = (resource: Resource): { label: string; title: string } => {
  if (resource.type === 'k8s-network-policy') {
    return { label: networkPolicyRules(resource), title: networkPolicyRules(resource) };
  }
  if (resource.type === 'k8s-pod-disruption-budget') {
    return { label: pdbBudget(resource), title: pdbBudget(resource) };
  }
  if (resource.type === 'k8s-resource-quota') {
    const count = quotaKeys(resource).length;
    return {
      label: count > 0 ? plural(count, 'hard limit') : 'No hard limits',
      title: quotaUsage(resource, Number.MAX_SAFE_INTEGER).title,
    };
  }
  if (resource.type === 'k8s-limit-range') {
    return summarizePlatformTableValues(resource.kubernetes?.limitTypes, { maxVisible: 3 });
  }
  return { label: '—', title: '' };
};

const policyState = (resource: Resource): { label: string; title: string } => {
  if (resource.type === 'k8s-network-policy') {
    return { label: 'Namespace isolation', title: '' };
  }
  if (resource.type === 'k8s-pod-disruption-budget') {
    const health = pdbHealth(resource);
    return { label: health, title: health };
  }
  if (resource.type === 'k8s-resource-quota') {
    return quotaUsage(resource);
  }
  if (resource.type === 'k8s-limit-range') {
    return { label: 'Namespace defaults', title: '' };
  }
  return { label: formatPlatformTableTextValue(resource.status), title: '' };
};

const labelSummary = (resource: Resource): { label: string; title: string } =>
  summarizePlatformTableValues(resource.tags);

// The policy's own fields in full: the table cells summarise them and cap
// long lists, which a phone cannot hover to read.
const policyContentSection = (resource: Resource): DetailSection | null => {
  const k = resource.kubernetes;
  switch (resource.type) {
    case 'k8s-network-policy':
      return {
        label: 'Network policy',
        rows: compactDetailRows([
          makeDetailRow('Applies to', policyTypes(resource).title || policyTypes(resource).label, {
            wrap: true,
          }),
          typeof k?.ingressRuleCount === 'number'
            ? makeDetailRow('Ingress rules', String(k.ingressRuleCount))
            : null,
          typeof k?.egressRuleCount === 'number'
            ? makeDetailRow('Egress rules', String(k.egressRuleCount))
            : null,
        ]),
      };
    case 'k8s-pod-disruption-budget':
      return {
        label: 'Disruption budget',
        rows: compactDetailRows([
          makeDetailRow('Min available', asTrimmedString(k?.minAvailable)),
          makeDetailRow('Max unavailable', asTrimmedString(k?.maxUnavailable)),
          typeof k?.currentHealthy === 'number' || typeof k?.desiredHealthy === 'number'
            ? makeDetailRow(
                'Healthy',
                `${k?.currentHealthy ?? 0} of ${k?.desiredHealthy ?? 0} wanted`,
              )
            : null,
          typeof k?.disruptionsAllowed === 'number'
            ? makeDetailRow('Disruptions allowed', String(k.disruptionsAllowed))
            : null,
          typeof k?.expectedPods === 'number'
            ? makeDetailRow('Expected pods', String(k.expectedPods))
            : null,
        ]),
      };
    case 'k8s-resource-quota': {
      const hard = k?.hard ?? {};
      const used = k?.used ?? {};
      return {
        label: 'Quota (used of hard limit)',
        rows: compactDetailRows(
          quotaKeys(resource).map((key) =>
            makeDetailRow(key, `${used[key] ?? '0'} of ${hard[key] ?? 'no limit'}`, {
              wrap: true,
            }),
          ),
        ),
      };
    }
    case 'k8s-limit-range':
      return {
        label: 'Limit range',
        rows: compactDetailRows([
          makeDetailRow('Limits', (k?.limitTypes ?? []).join(', '), { wrap: true }),
        ]),
      };
    default:
      return null;
  }
};

const policySummary = (resource: Resource): string =>
  [policyShape(resource).label, policyState(resource).label]
    .filter((part) => part && part !== '—')
    .join(' · ');

const buildPolicyDetailSections = (
  resource: Resource,
  now: number,
): Array<DetailSection | null> => [
  kubernetesObjectSection(resource, policyKind(resource), now),
  policyContentSection(resource),
  kubernetesLabelsSection(resource),
];

export const KubernetesPolicyTable: Component<{
  resources: Resource[];
  emptyIcon: JSX.Element;
  emptyTitle: string;
  emptyDescription: string;
  title?: string;
  showToolbar?: boolean;
  externalSearch?: () => string;
  externalStatus?: () => KubernetesResourceStatusFilter;
}> = (props) => {
  const singleCluster = createMemo(() => isSingleKubernetesCluster(props.resources));
  const tableState = createPlatformTableFilterState({
    resources: () => props.resources,
    initialStatus: 'all' as KubernetesResourceStatusFilter,
    filter: filterKubernetesResources,
    externalSearch: props.externalSearch,
    externalStatus: props.externalStatus,
  });
  const drawer = createPlatformResourceDetailState({ idPrefix: 'kubernetes-policy-drawer' });

  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 policy resources"
            searchSuggestions={tableState.searchSuggestions}
            status={tableState.status()}
            onStatusChange={tableState.setStatus}
            statusOptions={withPlatformStatusCounts(
              PLATFORM_HEALTH_FILTER_OPTIONS,
              tableState.countForStatus,
            )}
            visible={tableState.visible()}
            total={tableState.total()}
            rowNoun="policy resources"
          />
        </Show>

        <Show
          when={tableState.filtered().length > 0}
          fallback={
            <PlatformTableEmptyState
              icon={props.emptyIcon}
              title="No policy resources match current filters"
              description="Adjust the search or status filter to see more Kubernetes policy resources."
            />
          }
        >
          <PlatformTableShell
            title={
              props.title ??
              'NetworkPolicies, PodDisruptionBudgets, ResourceQuotas, and LimitRanges'
            }
            tableClass="min-w-full table-fixed text-xs md:min-w-[1180px]"
            header={
              <>
                <TableHead
                  class={`${getPlatformTableHeadClassForKind('name')} platform-table-mobile-w-30 md:w-[22%]`}
                  style={platformTableBandWidthStyle(30)}
                >
                  Resource
                </TableHead>
                <TableHead
                  class={`${getPlatformTableHeadClassForKind('text')} platform-table-mobile-w-15 md:w-[17%]`}
                  style={platformTableBandWidthStyle(23)}
                >
                  Kind
                </TableHead>
                <TableHead
                  class={`${getPlatformTableHeadClassForKind('text')} platform-table-mobile-w-15 md:w-[12%]`}
                  style={platformTableBandWidthStyle(13)}
                >
                  Scope
                </TableHead>
                <TableHead
                  class={`${getPlatformTableHeadClassForKind('text')} platform-table-mobile-w-20 md:w-[15%]`}
                  style={platformTableBandWidthStyle(18)}
                >
                  <PlatformResponsiveTableLabel compact="Policy" full="Policy shape" />
                </TableHead>
                <TableHead
                  class={`${getPlatformTableHeadClassForKind('text')} platform-table-mobile-w-20 md:w-[15%]`}
                  style={platformTableBandWidthStyle(16)}
                >
                  <PlatformResponsiveTableLabel compact="Limits" full="Spec / limits" />
                </TableHead>
                <TableHead
                  class={`${getPlatformTableHeadClassForKind('text')} hidden md:table-cell md:w-[14%]`}
                >
                  Observed state
                </TableHead>
                <TableHead
                  class={`${getPlatformTableHeadClassForKind('text')} hidden md:table-cell md:w-[9%]`}
                >
                  Labels
                </TableHead>
              </>
            }
            body={
              <>
                <PlatformWindowedRows items={tableState.filtered} estimatedRowHeight={32}>
                  {(resource) => {
                    const indicator = () => getSimpleStatusIndicator(resource.status);
                    const name = () => policyName(resource);
                    const shape = () => policyShape(resource);
                    const spec = () => policySpec(resource);
                    const state = () => policyState(resource);
                    const labels = () => labelSummary(resource);
                    const detailRowId = () => drawer.detailRowId(resource);
                    const isExpanded = () => drawer.isExpanded(resource);

                    return (
                      <>
                        <TableRow
                          class={`${getPlatformResourceDetailRowClass(isExpanded())} text-[11px] sm:text-xs`}
                          data-kubernetes-policy-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`}
                          >
                            {policyKind(resource)}
                          </TableCell>
                          <TableCell
                            class={`${getPlatformTableCellClassForKind('text')} text-base-content`}
                          >
                            <KubernetesScopeText
                              resource={resource}
                              singleCluster={singleCluster()}
                              class="block truncate"
                            />
                          </TableCell>
                          <TableCell
                            class={`${getPlatformTableCellClassForKind('text')} text-base-content`}
                          >
                            <span class="block truncate" title={shape().title}>
                              {shape().label}
                            </span>
                          </TableCell>
                          <TableCell
                            class={`${getPlatformTableCellClassForKind('text')} text-base-content`}
                          >
                            <span class="block truncate" title={spec().title}>
                              {spec().label}
                            </span>
                          </TableCell>
                          <TableCell
                            class={`${getPlatformTableCellClassForKind('text')} hidden text-base-content md:table-cell`}
                          >
                            <span class="block truncate" title={state().title}>
                              {state().label}
                            </span>
                          </TableCell>
                          <TableCell
                            class={`${getPlatformTableCellClassForKind('text')} hidden text-base-content md:table-cell`}
                          >
                            <span class="block truncate" title={labels().title}>
                              {labels().label}
                            </span>
                          </TableCell>
                        </TableRow>
                        <Show when={isExpanded()}>
                          <InlineDetailTableRow
                            cellId={detailRowId()}
                            colspan={7}
                            data-inline-kubernetes-policy-detail-for={resource.id}
                          >
                            <KubernetesRecordDetailPanel
                              testId="kubernetes-policy-detail"
                              resource={resource}
                              title={name()}
                              status={indicator()}
                              summary={policySummary(resource)}
                              sections={(now) => buildPolicyDetailSections(resource, now)}
                              onClose={() => drawer.close(resource)}
                            />
                          </InlineDetailTableRow>
                        </Show>
                      </>
                    );
                  }}
                </PlatformWindowedRows>
              </>
            }
          />
        </Show>
      </div>
    </Show>
  );
};

export default KubernetesPolicyTable;