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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
import { getResourceStaleness } from '@/features/platformPage/resourceStaleness';
import {
getPlatformInlineStateClass,
isPlatformAttentionVariant,
} from '@/features/platformPage/platformStatusTone';
import { For, Show, Suspense, createMemo, lazy, type Component, type JSX } from 'solid-js';
import { useSearchParams } from '@solidjs/router';
import { type FilterDef } from '@/components/shared/FilterBar';
import { UpdateButton } from '@/components/shared/ContainerUpdateBadge';
import { getDockerContainerUpdateAction } from './dockerContainerUpdateAction';
import {
getContainerUpdateUncheckableLabel,
isContainerUpdateUncheckable,
} from '@/components/shared/containerUpdateBadgeModel';
import {
GroupedTableModeSegmentedControl,
type GroupedTableMode,
} from '@/components/shared/GroupedTableModeSegmentedControl';
import {
GROUPED_TABLE_ROW_BADGE_CLASS,
getGroupedTableRowCellClass,
getGroupedTableRowClass,
} from '@/components/shared/groupedTableRowPresentation';
import { ResponsiveMetricCell } from '@/components/shared/responsive';
import { StatusDot } from '@/components/shared/StatusDot';
import { ResourceNameWithWebInterfaceLink } from '@/components/shared/WebInterfaceLink';
import { usePersistentSignal } from '@/hooks/usePersistentSignal';
import { getSimpleStatusIndicator } from '@/utils/status';
import { StackedMemoryBar } from '@/components/Workloads/StackedMemoryBar';
import type {
WorkloadWebLinkRow,
WorkloadWebLinksNoun,
} from '@/components/Workloads/workloadWebLinksModel';
import { toDiscoveryConfig } from '@/components/Infrastructure/resourceDetailDiscoveryModel';
import {
getWorkloadTableLayoutMode,
getWorkloadTableLayoutModeForContainer,
} from '@/components/Workloads/guestRowModel';
import { useBreakpoint } from '@/hooks/useBreakpoint';
import { useObservedElementWidth } from '@/hooks/useObservedElementWidth';
import { TableCell, TableRow } from '@/components/shared/Table';
import { asTrimmedString } from '@/utils/stringUtils';
import { buildMetricKeyForUnifiedResource } from '@/utils/metricsKeys';
import { useAlertsActivation } from '@/stores/alertsActivation';
import { dockerContainerOverrideIdCandidates } from '@/features/alerts/alertOverridesModel';
import { DOCKER_QUERY_PARAMS } from '@/routing/resourceLinks';
import {
PLATFORM_HEALTH_FILTER_OPTIONS,
PlatformSortableTableHead,
PlatformResponsiveTableLabel,
PlatformTableMetricFallback,
PlatformTableEmptyState,
PlatformTableToolbar,
createPlatformTableFilterState,
createPlatformTableSortState,
formatPlatformTableUptimeValue,
getPlatformTableFiniteMetric,
getPlatformTableCellClassForKind,
PlatformTableShell,
PlatformWindowedRows,
type PlatformTableSortValue,
withPlatformStatusCounts,
} from '@/features/platformPage/sharedPlatformPage';
import {
PlatformResourceDetailToggleButton,
PlatformResourceDetailTableRow,
createPlatformResourceDetailState,
createPlatformResourceLabelResolver,
getPlatformResourceDetailRowClass,
} from '@/features/platformPage/PlatformResourceDetailTableRow';
import {
DockerResourceNameCell,
dockerHostName,
dockerJoinValues,
dockerResourceName,
dockerStateTextToneClass,
dockerTextValue,
type DockerNativeTableProps,
} from './DockerNativeTableShared';
import {
compareDockerContainers,
dockerContainerPortsCompactSummary,
dockerContainerPortsSummary,
dockerContainerRestartAttentionLabel,
dockerContainerRestartCountTitle,
filterDockerResources,
mapDockerContainerStatus,
type DockerResourceStatusFilter,
} from './dockerPageModel';
import {
DOCKER_CONTAINER_SORTABLE_COLUMN_IDS,
getDockerContainerColumnWidthStyle,
getDockerContainerSortKey,
getDockerContainerTableMinWidthClass,
getDockerContainerVisibleColumnsForLayout,
isDockerContainerColumnInLayout,
isDockerContainerStateUnderName,
type DockerContainerSortKey,
type DockerContainerTableColumn,
} from './dockerContainerTableModel';
import type { Resource } from '@/types/resource';
import { DockerContainerLifecycleControls } from './DockerContainerLifecycleControls';
import { CONTAINER_CPU_CAPACITY_DESCRIPTION } from './dockerCpuPresentation';
import { DockerImageReferenceText } from './DockerImageReferenceText';
import {
getDockerContainerStatePresentation,
getDockerContainerUptimeSeconds,
} from './dockerContainerStatePresentation';
type DockerNetwork = NonNullable<NonNullable<Resource['docker']>['networks']>[number];
type DockerMount = NonNullable<NonNullable<Resource['docker']>['mounts']>[number];
type DockerContainersTableProps = DockerNativeTableProps & {
onLifecycleActionSettled?: () => void | Promise<void>;
// Host resources backing the group headers in grouped mode: they carry the
// host's status and custom web-interface URL, which container rows do not.
hosts?: Resource[];
};
type DockerContainerHostGroup = {
host: string;
hostResource?: Resource;
rows: Resource[];
};
type DockerContainerRenderItem =
| { kind: 'group'; key: string; group: DockerContainerHostGroup }
| { kind: 'resource'; key: string; resource: Resource };
const networkLabel = (network: DockerNetwork): string => {
const name = asTrimmedString(network.name);
const address = asTrimmedString(network.ipv4) || asTrimmedString(network.ipv6);
if (name && address) return `${name} ${address}`;
return name || address || '';
};
const networksSummary = (resource: Resource): string =>
dockerJoinValues(resource.docker?.networks?.map((network) => networkLabel(network)));
const mountLabel = (mount: DockerMount): string => {
const type = asTrimmedString(mount.type);
const destination = asTrimmedString(mount.destination);
const source = asTrimmedString(mount.source);
const mode = asTrimmedString(mount.mode) || (mount.rw === false ? 'ro' : '');
const endpoint = destination || source;
if (!endpoint) return type || '';
const prefix = type ? `${type}:` : '';
const suffix = mode ? ` (${mode})` : '';
return `${prefix}${endpoint}${suffix}`;
};
const mountsSummary = (resource: Resource): string =>
dockerJoinValues(resource.docker?.mounts?.map((mount) => mountLabel(mount)));
const runtimeSummary = (resource: Resource): string => {
const runtime = asTrimmedString(resource.docker?.runtime);
const version = asTrimmedString(
resource.docker?.runtimeVersion || resource.docker?.dockerVersion,
);
if (runtime && version) return `${runtime} ${version}`;
return runtime || version || '—';
};
// Lazy so the trigger keeps its own chunk instead of joining (and renaming)
// the chunk the Docker and workloads pages already share.
const WorkloadWebLinksAction = lazy(() => import('@/components/Workloads/WorkloadWebLinksAction'));
const CONTAINER_WEB_LINKS_NOUN: WorkloadWebLinksNoun = { one: 'container', many: 'containers' };
// Keyed by the identity the container drawer saves its web link under, so the
// bulk editor and the drawer field read and write the same record.
const toContainerWebLinkRows = (resource: Resource): WorkloadWebLinkRow[] => {
const target = toDiscoveryConfig(resource);
if (target?.metadataKind !== 'guest' || !target.metadataId) return [];
return [
{
metadataId: target.metadataId,
name: dockerResourceName(resource),
detail: [dockerHostName(resource), dockerTextValue(resource.docker?.image)]
.filter((part) => part && part !== '—')
.join(' · '),
status: asTrimmedString(resource.docker?.containerState || resource.status) ?? '',
addressHint: '',
savedUrl: resource.customUrl ?? '',
},
];
};
const isContainerRunning = (resource: Resource): boolean =>
(asTrimmedString(resource.docker?.containerState || resource.status) ?? '').toLowerCase() ===
'running';
const updateStatusLabel = (resource: Resource): string => {
const update = resource.docker?.updateStatus;
if (!update) return '—';
if (isContainerUpdateUncheckable(update)) return getContainerUpdateUncheckableLabel(update);
if (asTrimmedString(update.error)) return 'Error';
return update.updateAvailable ? 'Available' : 'Current';
};
const updateStatusTitle = (resource: Resource): string => {
const update = resource.docker?.updateStatus;
if (!update) return 'No image update check reported';
return dockerJoinValues(
[
updateStatusLabel(resource),
update.error,
update.currentDigest ? `current ${update.currentDigest}` : undefined,
update.latestDigest ? `latest ${update.latestDigest}` : undefined,
update.lastChecked ? `checked ${update.lastChecked}` : undefined,
],
updateStatusLabel(resource),
);
};
// Scalar per column that user-controlled sorting orders on. '—' style empty
// renders map to null so rows without the datum sink to the bottom.
const getDockerContainerSortValue = (
resource: Resource,
key: DockerContainerSortKey,
): PlatformTableSortValue => {
switch (key) {
case 'container':
return dockerResourceName(resource);
case 'host': {
const host = dockerHostName(resource);
return host === '—' ? null : host;
}
case 'runtime': {
const runtime = runtimeSummary(resource);
return runtime === '—' ? null : runtime;
}
case 'image':
return asTrimmedString(resource.docker?.image) || null;
case 'state':
return getDockerContainerStatePresentation(resource).label;
case 'uptime':
return getDockerContainerUptimeSeconds(resource) ?? null;
case 'cpu':
return getPlatformTableFiniteMetric(resource.cpu?.current) ?? null;
case 'memory': {
const total = getPlatformTableFiniteMetric(resource.memory?.total) ?? 0;
if (total > 0) {
return ((getPlatformTableFiniteMetric(resource.memory?.used) ?? 0) / total) * 100;
}
return getPlatformTableFiniteMetric(resource.memory?.current) ?? null;
}
case 'restarts':
return typeof resource.docker?.restartCount === 'number'
? resource.docker.restartCount
: null;
case 'updates': {
const label = updateStatusLabel(resource);
return label === '—' ? null : label;
}
default:
key satisfies never;
return null;
}
};
const DOCKER_CONTAINER_SEARCH_TIPS = {
popoverId: 'docker-containers-search-help',
intro: 'Filter containers by name, image, compose stack, or label.',
tips: [
{ code: 'nginx', description: 'Match container names, images, and labels' },
{ code: '-watchtower', description: 'Hide containers matching a term' },
],
footerHighlight: 'Tip',
footerText: 'Combine exclusions and save them as a default view to keep noisy containers hidden.',
};
export const DockerContainersTable: Component<DockerContainersTableProps> = (props) => {
const alertsActivation = useAlertsActivation();
const breakpoint = useBreakpoint();
const observedWidth = useObservedElementWidth();
const layoutMode = createMemo(() => {
const measuredWidth = observedWidth.width();
return measuredWidth === null
? getWorkloadTableLayoutMode(breakpoint.width())
: getWorkloadTableLayoutModeForContainer(measuredWidth);
});
// Search and status live in the URL, like the host scope below, so the
// whole filter state is shareable and bookmarkable. That is what makes
// exclusions portable: search `-name`, bookmark the resulting URL, and the
// containers stay hidden every time you open it. URL writes replace the
// history entry so typing does not pile up back-button states.
const [searchParams, setSearchParams] = useSearchParams();
const searchFilter = () => {
const value = searchParams[DOCKER_QUERY_PARAMS.query];
return typeof value === 'string' ? value : '';
};
const setSearchFilter = (value: string) =>
setSearchParams({ [DOCKER_QUERY_PARAMS.query]: value || null }, { replace: true });
const statusFilter = (): DockerResourceStatusFilter => {
const value = searchParams[DOCKER_QUERY_PARAMS.status];
return value === 'online' || value === 'degraded' || value === 'offline' ? value : 'all';
};
const setStatusFilter = (value: DockerResourceStatusFilter) =>
setSearchParams(
{ [DOCKER_QUERY_PARAMS.status]: value === 'all' ? null : value },
{ replace: true },
);
const tableState = createPlatformTableFilterState({
resources: () => props.resources,
initialStatus: 'all' as DockerResourceStatusFilter,
filter: filterDockerResources,
externalSearch: searchFilter,
onExternalSearchChange: setSearchFilter,
externalStatus: statusFilter,
onExternalStatusChange: setStatusFilter,
});
// Host scope filter, URL-backed so it is shareable and captured by saved
// views. Distinct hosts are derived from the current resource set; the facet
// only appears once more than one host is present (a single-host fleet has
// nothing to scope by).
const hostFilter = () => {
const host = searchParams[DOCKER_QUERY_PARAMS.host];
return typeof host === 'string' ? host : '';
};
const setHostFilter = (value: string) =>
setSearchParams({ [DOCKER_QUERY_PARAMS.host]: value || null });
const hostOptions = createMemo(() => {
const seen = new Set<string>();
for (const resource of props.resources) {
const host = dockerHostName(resource);
if (host && host !== '—') seen.add(host);
}
return [...seen].sort((a, b) => a.localeCompare(b));
});
const scopeFilters = createMemo<FilterDef[]>(() => {
if (hostOptions().length <= 1) return [];
return [
{
id: 'host',
label: 'Host',
group: 'scope',
options: () => [
{ value: '', label: 'All hosts' },
...hostOptions().map((host) => ({ value: host, label: host })),
],
value: hostFilter,
setValue: setHostFilter,
defaultValue: '',
},
];
});
const applyHostScope = (rows: Resource[]) => {
const host = hostFilter();
return host ? rows.filter((resource) => dockerHostName(resource) === host) : rows;
};
const scopedRows = createMemo(() => applyHostScope(tableState.filtered()));
// The host facet narrows rows after the shared filter state, so chip counts
// must apply it too or a scoped view would count other hosts' containers.
const countForStatus = (value: DockerResourceStatusFilter): number =>
applyHostScope(filterDockerResources(props.resources, tableState.search(), value)).length;
const hasActiveFilters = () => tableState.hasActiveFilters() || hostFilter() !== '';
// Reset must clear every URL param in ONE navigation. Consecutive
// setSearchParams calls each merge against the pre-navigation URL (the
// router commits inside an async transition), so clearing search, status,
// and host as three writes would leave the first two params resurrected.
const resetFilters = () =>
setSearchParams(
{
[DOCKER_QUERY_PARAMS.query]: null,
[DOCKER_QUERY_PARAMS.status]: null,
[DOCKER_QUERY_PARAMS.host]: null,
},
{ replace: true },
);
// User-controlled sorting layered over the attention-first default: rows
// are pre-sorted by the status compare, so a user sort keeps that order for
// ties and the table falls straight back to it when the sort is cleared.
// Where the layout has no Restarts column, a crash-looping container says
// so in its State cell instead.
const flagRestartsInState = createMemo(
() => !isDockerContainerColumnInLayout('restarts', layoutMode()),
);
const stateUnderName = createMemo(() => isDockerContainerStateUnderName(layoutMode()));
const stateFor = (resource: Resource) =>
getDockerContainerStatePresentation(resource, { flagRestarts: flagRestartsInState() });
// Sorting reorders rows only; grouped mode re-buckets the sorted rows, so
// the sort applies within each host group and stays orthogonal to grouping.
const sort = createPlatformTableSortState({
storageKey: 'dockerContainers',
sortKeys: DOCKER_CONTAINER_SORTABLE_COLUMN_IDS,
descendingFirst: ['cpu', 'memory', 'restarts', 'uptime'],
});
const sortedRows = createMemo(() =>
sort.sortRows([...scopedRows()].sort(compareDockerContainers), (resource, key) =>
// State sorts by the words the row shows, restart warning included.
key === 'state' ? stateFor(resource).label : getDockerContainerSortValue(resource, key),
),
);
// Grouped-by-host view, mirroring the workloads table: preference persists
// locally (not in the URL) and only applies once the fleet spans more than
// one host; a single-host list gains nothing from a group header.
const [groupingModePreference, setGroupingModePreference] = usePersistentSignal<GroupedTableMode>(
'dockerContainersGroupingMode',
'grouped',
{
deserialize: (raw) => (raw === 'grouped' || raw === 'flat' ? raw : 'grouped'),
},
);
const isGroupable = createMemo(() => hostOptions().length > 1);
const groupingMode = createMemo<GroupedTableMode>(() =>
isGroupable() ? groupingModePreference() : 'flat',
);
// Runtime is host-level data repeated on every container row; it only
// informs when the fleet actually mixes runtimes (docker vs podman).
const showRuntimeColumn = createMemo(() => {
const kinds = new Set<string>();
for (const resource of props.resources) {
const kind = (asTrimmedString(resource.docker?.runtime) ?? '').toLowerCase();
if (kind) kinds.add(kind);
}
return kinds.size > 1;
});
const showRestartColumn = createMemo(() =>
scopedRows().some(
(resource) =>
typeof resource.docker?.restartCount === 'number' && resource.docker.restartCount > 0,
),
);
// A running container with a failing or starting health check needs the
// State column as much as a stopped one does.
const showStateColumn = createMemo(() =>
scopedRows().some((resource) => stateFor(resource).tone !== null),
);
const showUptimeColumn = createMemo(() =>
scopedRows().some((resource) => getDockerContainerUptimeSeconds(resource) !== undefined),
);
const visibleColumns = createMemo(() =>
getDockerContainerVisibleColumnsForLayout(
layoutMode(),
showRuntimeColumn(),
showRestartColumn(),
showStateColumn(),
{
groupedByHost: isGroupable() && groupingMode() === 'grouped',
singleHost: hostOptions().length <= 1,
includeUptime: showUptimeColumn(),
},
),
);
const visibleColumnIds = createMemo(() => visibleColumns().map((column) => column.id));
// A sort applies only while its column shows. A saved sort on a column this
// layout hides (Host or Engine while grouped, State under a phone row's
// name, Uptime on a phone) would reorder rows with no visible indicator, so
// those rows fall back to the attention-first order; the preference stays
// saved for the layouts that show its column.
const displayRows = createMemo(() => {
const sortKey = sort.sortKey();
return sortKey && !visibleColumnIds().includes(sortKey)
? [...scopedRows()].sort(compareDockerContainers)
: sortedRows();
});
const hostResourceById = createMemo(() => {
const map = new Map<string, Resource>();
for (const hostResource of props.hosts ?? []) map.set(hostResource.id, hostResource);
return map;
});
const hostResourceByName = createMemo(() => {
const map = new Map<string, Resource>();
for (const hostResource of props.hosts ?? []) {
const keys = [
dockerHostName(hostResource),
asTrimmedString(hostResource.name) ?? '',
asTrimmedString(hostResource.displayName) ?? '',
];
for (const key of keys) {
if (key && key !== '—' && !map.has(key)) map.set(key, hostResource);
}
}
return map;
});
const groupedRows = createMemo<DockerContainerHostGroup[]>(() => {
const groups = new Map<string, Resource[]>();
for (const resource of displayRows()) {
const host = dockerHostName(resource);
const rows = groups.get(host);
if (rows) rows.push(resource);
else groups.set(host, [resource]);
}
return [...groups.entries()]
.sort(([a], [b]) => a.localeCompare(b))
.map(([host, rows]) => ({ host, hostResource: hostResourceByName().get(host), rows }));
});
const groupedRenderItems = createMemo<DockerContainerRenderItem[]>(() => {
const items: DockerContainerRenderItem[] = [];
for (const group of groupedRows()) {
items.push({ kind: 'group', key: `group:${group.host}`, group });
for (const resource of group.rows) {
items.push({ kind: 'resource', key: `resource:${resource.id}`, resource });
}
}
return items;
});
const drawerColSpan = createMemo(() => visibleColumns().length);
const drawer = createPlatformResourceDetailState({ idPrefix: 'docker-container-drawer' });
const resolveResourceLabel = createPlatformResourceLabelResolver(() => props.resources);
const renderContainerRow = (resource: Resource): JSX.Element => {
// REST reconciliation keeps this resource object and row alive. Read
// its current health verdict rather than retaining the first green dot.
const indicator = () => mapDockerContainerStatus(resource);
const image = () => dockerTextValue(resource.docker?.image);
const state = () => stateFor(resource);
const stateWords = () => (
<span
class={`block max-w-full truncate ${dockerStateTextToneClass(state().tone)}`}
title={state().title}
data-docker-container-state={state().tone ?? 'ok'}
>
{state().label}
</span>
);
// Without a State column the words join the name only when the state
// needs attention; a running or stopped container reads in its dot.
// Keep bounded failure words readable on phones: the neighbouring name
// can truncate first without turning the row back into two lines.
const stateBesideName = () => (
<span
class={`${getPlatformInlineStateClass(isPlatformAttentionVariant(state().tone))} ${isPlatformAttentionVariant(state().tone) ? 'shrink-0' : ''} ${dockerStateTextToneClass(state().tone)}`}
title={state().title}
data-docker-container-state={state().tone ?? 'ok'}
>
{state().label}
</span>
);
const runtime = () => runtimeSummary(resource);
const host = () => dockerHostName(resource);
const running = () => isContainerRunning(resource);
const metricsKey = () => buildMetricKeyForUnifiedResource(resource);
// Overrides key on docker:<hostId>/<containerName> with legacy ID forms
// as fallbacks; without the backing host resource only the docker-scope
// defaults can apply.
const alertResourceIds = () => {
const hostResource = hostResourceByName().get(host());
if (!hostResource) return [];
return dockerContainerOverrideIdCandidates(hostResource, resource);
};
const cpuThresholds = () =>
alertsActivation.getMetricThresholds('docker', 'cpu', alertResourceIds());
const memoryThresholds = () =>
alertsActivation.getMetricThresholds('docker', 'memory', alertResourceIds());
const cpuPercent = () => getPlatformTableFiniteMetric(resource.cpu?.current);
const memoryUsed = () => getPlatformTableFiniteMetric(resource.memory?.used) ?? 0;
const memoryTotal = () => getPlatformTableFiniteMetric(resource.memory?.total) ?? 0;
const memoryPercentOnly = () =>
memoryTotal() > 0 ? undefined : getPlatformTableFiniteMetric(resource.memory?.current);
const hasMemoryMetric = () => memoryTotal() > 0 || memoryPercentOnly() !== undefined;
const ports = () => dockerContainerPortsSummary(resource);
const portsCompact = () => dockerContainerPortsCompactSummary(resource);
const networks = () => networksSummary(resource);
const mounts = () => mountsSummary(resource);
const updates = () => updateStatusLabel(resource);
const updateTitle = () => updateStatusTitle(resource);
// An accessor, not a value: action readiness can arrive after the row
// mounts (the REST revalidation follows a websocket paint), and a value
// captured at mount kept offering an update the server had refused.
const action = () =>
getDockerContainerUpdateAction(resource, hostResourceById().get(resource.parentId ?? ''));
const detailRowId = () => drawer.detailRowId(resource);
const isExpanded = () => drawer.isExpanded(resource);
const renderColumnCell = (column: DockerContainerTableColumn): JSX.Element => {
switch (column.id) {
case 'container':
return (
<DockerResourceNameCell
resource={resource}
indicator={indicator()}
detail={stateUnderName() ? stateBesideName() : undefined}
detailToggle={
<PlatformResourceDetailToggleButton
expanded={isExpanded()}
resourceLabel={dockerResourceName(resource)}
controlsId={detailRowId()}
onToggle={() => drawer.toggle(resource)}
/>
}
/>
);
case 'host':
return (
<TableCell class={`${getPlatformTableCellClassForKind(column.kind)} text-base-content`}>
<span class="block max-w-full truncate" title={host()}>
{host()}
</span>
</TableCell>
);
case 'runtime':
return (
<TableCell class={`${getPlatformTableCellClassForKind(column.kind)} text-base-content`}>
<span class="block max-w-full truncate" title={runtime()}>
{runtime()}
</span>
</TableCell>
);
case 'image':
return (
<TableCell class={`${getPlatformTableCellClassForKind(column.kind)} text-base-content`}>
<DockerImageReferenceText reference={image()} class="max-w-full" />
</TableCell>
);
case 'state':
return (
<TableCell class={`${getPlatformTableCellClassForKind(column.kind)} text-base-content`}>
{stateWords()}
</TableCell>
);
case 'cpu':
return (
<TableCell class={getPlatformTableCellClassForKind(column.kind)}>
<ResponsiveMetricCell
class="w-full"
value={cpuPercent() ?? 0}
type="cpu"
resourceId={metricsKey()}
isRunning={running() && cpuPercent() !== undefined}
showMobile={false}
thresholds={cpuThresholds()}
/>
</TableCell>
);
case 'memory':
return (
<TableCell class={getPlatformTableCellClassForKind(column.kind)}>
<Show
when={running() && hasMemoryMetric()}
fallback={<PlatformTableMetricFallback />}
>
<StackedMemoryBar
used={memoryUsed()}
total={memoryTotal()}
percentOnly={memoryPercentOnly()}
thresholds={memoryThresholds()}
/>
</Show>
</TableCell>
);
case 'restarts':
return (
<TableCell class={`${getPlatformTableCellClassForKind(column.kind)} text-base-content`}>
<Show
when={typeof resource.docker?.restartCount === 'number'}
fallback={<span>—</span>}
>
<span
class={`tabular-nums ${
dockerContainerRestartAttentionLabel(resource)
? dockerStateTextToneClass('warning')
: ''
}`}
title={dockerContainerRestartCountTitle(resource.docker?.restartCount ?? 0)}
>
{resource.docker?.restartCount}
</span>
</Show>
</TableCell>
);
case 'uptime':
return (
<TableCell
class={`${getPlatformTableCellClassForKind(column.kind)} text-base-content tabular-nums`}
>
{formatPlatformTableUptimeValue(getDockerContainerUptimeSeconds(resource))}
</TableCell>
);
case 'ports':
return (
<TableCell class={`${getPlatformTableCellClassForKind(column.kind)} text-base-content`}>
<span class="block max-w-full truncate font-mono text-[11px]" title={ports()}>
{portsCompact()}
</span>
</TableCell>
);
case 'networks':
return (
<TableCell class={`${getPlatformTableCellClassForKind(column.kind)} text-base-content`}>
<span class="block max-w-full truncate" title={networks()}>
{networks()}
</span>
</TableCell>
);
case 'mounts':
return (
<TableCell class={`${getPlatformTableCellClassForKind(column.kind)} text-base-content`}>
<span class="block max-w-full truncate" title={mounts()}>
{mounts()}
</span>
</TableCell>
);
case 'updates':
return (
<TableCell
class={`${getPlatformTableCellClassForKind(column.kind)} text-base-content docker-container-update-cell`}
>
<Show
when={action()}
fallback={
<span class="block max-w-full truncate" title={updateTitle()}>
{updates()}
</span>
}
>
{(updateAction) => (
<UpdateButton
agentId={updateAction().agentId}
containerId={updateAction().containerId}
containerName={updateAction().containerName}
updateStatus={updateAction().updateStatus}
resourceId={updateAction().resourceId}
actionReadiness={updateAction().actionReadiness}
updateNotOfferedReason={updateAction().updateNotOfferedReason}
hostName={updateAction().hostName}
hostCommandsEnabled={updateAction().hostCommandsEnabled}
/>
)}
</Show>
</TableCell>
);
case 'actions':
return (
<TableCell class={getPlatformTableCellClassForKind(column.kind)}>
<DockerContainerLifecycleControls
resource={resource}
collapsed={layoutMode() !== 'wide'}
onActionSettled={props.onLifecycleActionSettled}
/>
</TableCell>
);
default:
column.id satisfies never;
return <></>;
}
};
return (
<>
<TableRow
class={`${getPlatformResourceDetailRowClass(isExpanded())} text-[11px] sm:text-xs`}
data-docker-container-row={resource.id}
onClick={() => drawer.toggle(resource)}
>
<For each={visibleColumns()}>{(column) => renderColumnCell(column)}</For>
</TableRow>
<PlatformResourceDetailTableRow
resource={resource}
open={isExpanded()}
detailRowId={detailRowId()}
colSpan={drawerColSpan()}
resolveResourceLabel={resolveResourceLabel}
onClose={() => drawer.close(resource)}
onResourceActionSettled={props.onLifecycleActionSettled}
/>
</>
);
};
const renderHostGroupHeader = (group: DockerContainerHostGroup): JSX.Element => {
const indicator = group.hostResource
? getSimpleStatusIndicator(group.hostResource.status)
: undefined;
// The host's own engine metadata is authoritative; without it, name every
// distinct engine its containers report rather than just the first row's.
const engine = () => {
const host = group.hostResource;
if (host) {
const hostSummary = runtimeSummary(host);
if (hostSummary !== '—') return hostSummary;
}
const summaries = [...new Set(group.rows.map((row) => runtimeSummary(row)))]
.filter((summary) => summary !== '—')
.sort((a, b) => a.localeCompare(b));
return summaries.length > 0 ? summaries.join(', ') : null;
};
const staleness = () => getResourceStaleness(group.hostResource);
return (
<TableRow class={getGroupedTableRowClass()} data-docker-host-group={group.host}>
<TableCell class={getGroupedTableRowCellClass()} colspan={visibleColumns().length}>
<div class="flex min-w-0 items-center gap-2">
<Show when={indicator}>
{(hostIndicator) => (
<StatusDot
size="sm"
variant={hostIndicator().variant}
title={hostIndicator().label}
ariaHidden
/>
)}
</Show>
<ResourceNameWithWebInterfaceLink
name={group.host}
url={group.hostResource?.customUrl}
class="min-w-0"
nameClass="truncate"
/>
<span class={GROUPED_TABLE_ROW_BADGE_CLASS}>
{group.rows.length} {group.rows.length === 1 ? 'container' : 'containers'}
</span>
<Show when={engine()}>
{(label) => <span class="shrink-0 text-[10px] text-muted">{label()}</span>}
</Show>
<Show when={staleness()}>
{(stale) => (
<span
class="shrink-0 text-[10px] font-medium text-amber-700 dark:text-amber-300"
title={`${stale().label}. Container states and metrics are the last values received.`}
data-docker-host-group-stale
>
{stale().label}
</span>
)}
</Show>
</div>
</TableCell>
</TableRow>
);
};
return (
<Show
when={props.resources.length > 0}
fallback={
<PlatformTableEmptyState
icon={props.emptyIcon}
title={props.emptyTitle}
description={props.emptyDescription}
/>
}
>
<div ref={observedWidth.setElement} class="space-y-3">
<Show when={props.showToolbar !== false}>
<PlatformTableToolbar
search={tableState.search}
onSearchChange={tableState.setSearch}
searchPlaceholder="Search containers"
searchSuggestions={tableState.searchSuggestions}
searchTips={DOCKER_CONTAINER_SEARCH_TIPS}
status={tableState.status()}
onStatusChange={tableState.setStatus}
statusOptions={withPlatformStatusCounts(PLATFORM_HEALTH_FILTER_OPTIONS, countForStatus)}
filters={scopeFilters()}
visible={scopedRows().length}
total={tableState.total()}
rowNoun="containers"
hasActiveFilters={hasActiveFilters()}
onResetFilters={resetFilters}
viewOptions={
isGroupable() ? (
<div>
<div class="mb-1.5 text-[10px] font-semibold uppercase tracking-wide text-muted">
Layout
</div>
<GroupedTableModeSegmentedControl
value={groupingMode()}
onChange={setGroupingModePreference}
/>
</div>
) : undefined
}
/>
</Show>
<Show
when={scopedRows().length > 0}
fallback={
<PlatformTableEmptyState
icon={props.emptyIcon}
title="No containers match current filters"
description="Adjust the search, status, or host filter to see more Docker containers."
/>
}
>
<PlatformTableShell
title={props.title ?? 'Containers'}
actions={
<Suspense fallback={null}>
<WorkloadWebLinksAction
source={{
kind: 'rows',
noun: CONTAINER_WEB_LINKS_NOUN,
rows: () => scopedRows().flatMap(toContainerWebLinkRows),
}}
/>
</Suspense>
}
footer={
<p
class="px-3 py-2 text-xs leading-relaxed text-muted"
data-testid="container-table-cpu-scale"
>
{CONTAINER_CPU_CAPACITY_DESCRIPTION}
</p>
}
tableClass={`${getDockerContainerTableMinWidthClass()} table-fixed text-xs`}
colgroup={
<colgroup>
<For each={visibleColumns()}>
{(column) => (
<col
style={getDockerContainerColumnWidthStyle(
column.id,
layoutMode(),
visibleColumnIds(),
)}
/>
)}
</For>
</colgroup>
}
header={
<>
<For each={visibleColumns()}>
{(column) => (
<PlatformSortableTableHead
kind={column.kind}
sort={sort}
sortKey={getDockerContainerSortKey(column.id)}
>
<Show
when={column.id !== 'actions'}
fallback={<span class="sr-only">{column.label}</span>}
>
<Show
when={column.compactLabel}
fallback={
<Show when={column.id === 'memory'} fallback={<>{column.label}</>}>
<PlatformResponsiveTableLabel compact="Mem" full="Memory" />
</Show>
}
>
{(compactLabel) => (
<PlatformResponsiveTableLabel
compact={compactLabel()}
full={column.label}
/>
)}
</Show>
</Show>
</PlatformSortableTableHead>
)}
</For>
</>
}
body={
<Show
when={groupingMode() === 'grouped'}
fallback={
<PlatformWindowedRows items={displayRows} estimatedRowHeight={32}>
{(resource) => renderContainerRow(resource)}
</PlatformWindowedRows>
}
>
<PlatformWindowedRows
items={groupedRenderItems}
keyExtractor={(item) => item.key}
estimatedRowHeight={32}
>
{(item) =>
item.kind === 'group'
? renderHostGroupHeader(item.group)
: renderContainerRow(item.resource)
}
</PlatformWindowedRows>
</Show>
}
/>
</Show>
</div>
</Show>
);
};
export default DockerContainersTable;