@myrialabs/clopen 0.4.34 → 0.4.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/backend/auth/permissions.ts +7 -0
- package/backend/containers/actions.ts +316 -0
- package/backend/containers/disk-usage.test.ts +68 -0
- package/backend/containers/disk-usage.ts +170 -0
- package/backend/containers/logs.ts +335 -0
- package/backend/containers/monitor.ts +410 -0
- package/backend/containers/parse.test.ts +599 -0
- package/backend/containers/parse.ts +905 -0
- package/backend/containers/port-index.test.ts +91 -0
- package/backend/containers/port-index.ts +198 -0
- package/backend/containers/prune-job.test.ts +148 -0
- package/backend/containers/prune-job.ts +129 -0
- package/backend/containers/pty-backend.ts +337 -0
- package/backend/containers/pty.ts +114 -0
- package/backend/containers/runtime.ts +218 -0
- package/backend/containers/scan.ts +293 -0
- package/backend/files/file-watcher.test.ts +105 -0
- package/backend/files/file-watcher.ts +45 -1
- package/backend/git/git-service.test.ts +33 -0
- package/backend/git/git-service.ts +7 -3
- package/backend/git/nested-repos.test.ts +292 -1
- package/backend/git/nested-repos.ts +330 -17
- package/backend/{ports → host}/runner.ts +19 -10
- package/backend/index.ts +11 -2
- package/backend/ports/attribute.ts +1 -1
- package/backend/ports/kill.ts +1 -1
- package/backend/ports/monitor.ts +1 -1
- package/backend/ports/processes.ts +1 -1
- package/backend/ports/scan-host.ts +77 -8
- package/backend/ports/scan.test.ts +1 -1
- package/backend/ports/scan.ts +1 -1
- package/backend/ports/ssh-lineage.ts +1 -1
- package/backend/preview/browser/browser-video-capture.ts +84 -31
- package/backend/ws/containers/actions.ts +156 -0
- package/backend/ws/containers/index.ts +43 -0
- package/backend/ws/containers/list.ts +146 -0
- package/backend/ws/containers/logs.ts +43 -0
- package/backend/ws/containers/tunnel.ts +101 -0
- package/backend/ws/git/log.ts +3 -1
- package/backend/ws/git/status.ts +37 -27
- package/backend/ws/index.ts +2 -0
- package/backend/ws/message-rate-limiter.test.ts +45 -0
- package/backend/ws/message-rate-limiter.ts +34 -3
- package/backend/ws/ssh/connections.ts +8 -0
- package/backend/ws/system/device-info.ts +99 -43
- package/dist/assets/{index-vW2RpdHu.js → index-B0iIhSO9.js} +1 -1
- package/dist/assets/{index-gGTMFUa8.js → index-BRJqss6F.js} +1 -1
- package/dist/assets/main-Buko4D0t.css +1 -0
- package/dist/assets/{main-ZCojSzvW.js → main-C_iGUZyL.js} +467 -449
- package/dist/index.html +2 -2
- package/dist/manifest.json +9 -2
- package/package.json +1 -1
- package/shared/types/containers/container.ts +366 -0
- package/shared/types/containers/index.ts +5 -0
- package/shared/types/host/index.ts +18 -0
- package/shared/types/ports/port.ts +47 -9
- package/shared/utils/logger.ts +2 -0
- package/shared/utils/ws-client.ts +67 -12
- package/shared/utils/ws-server.ts +64 -13
- package/dist/assets/main-CYCMEbXB.css +0 -1
|
@@ -0,0 +1,905 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Containers — turning two runtimes' output into one model.
|
|
3
|
+
*
|
|
4
|
+
* Docker and Podman answer the same questions in different words. Docker's CLI
|
|
5
|
+
* speaks Go templates and prints one JSON object per line; Podman prints a JSON
|
|
6
|
+
* array with its own field names, its own timestamps (sometimes an epoch,
|
|
7
|
+
* sometimes RFC 3339) and structured ports where Docker has a string. Every one
|
|
8
|
+
* of those differences is resolved here, so nothing downstream — not the
|
|
9
|
+
* scanner, not the WebSocket layer, not the UI — ever asks which runtime it is
|
|
10
|
+
* looking at.
|
|
11
|
+
*
|
|
12
|
+
* Everything in this file is a pure function over command output, which is what
|
|
13
|
+
* makes the awkward parts (a locale-formatted date, a port range, a compose
|
|
14
|
+
* label) testable without a container runtime anywhere near the test.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import type {
|
|
18
|
+
ContainerDetail,
|
|
19
|
+
ContainerDiskUsage,
|
|
20
|
+
ContainerDiskUsageRow,
|
|
21
|
+
ContainerEntry,
|
|
22
|
+
ContainerHealth,
|
|
23
|
+
ContainerImageEntry,
|
|
24
|
+
ContainerNetworkEntry,
|
|
25
|
+
ContainerPortBinding,
|
|
26
|
+
ContainerState,
|
|
27
|
+
ContainerStats,
|
|
28
|
+
ContainerVolumeEntry
|
|
29
|
+
} from '$shared/types/containers';
|
|
30
|
+
|
|
31
|
+
/** Parse NDJSON, skipping anything that is not an object — warnings, banners. */
|
|
32
|
+
function readJsonLines(stdout: string): Record<string, unknown>[] {
|
|
33
|
+
const rows: Record<string, unknown>[] = [];
|
|
34
|
+
for (const line of stdout.split('\n')) {
|
|
35
|
+
const trimmed = line.trim();
|
|
36
|
+
if (!trimmed.startsWith('{')) continue;
|
|
37
|
+
try {
|
|
38
|
+
const value = JSON.parse(trimmed);
|
|
39
|
+
if (value && typeof value === 'object') rows.push(value as Record<string, unknown>);
|
|
40
|
+
} catch {
|
|
41
|
+
// A truncated line is one row lost, not a failed scan.
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return rows;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Parse a JSON array, tolerating the empty output an idle host produces. */
|
|
48
|
+
function readJsonArray(stdout: string): Record<string, unknown>[] {
|
|
49
|
+
const trimmed = stdout.trim();
|
|
50
|
+
if (!trimmed) return [];
|
|
51
|
+
try {
|
|
52
|
+
const value = JSON.parse(trimmed);
|
|
53
|
+
if (Array.isArray(value)) return value.filter((row) => row && typeof row === 'object');
|
|
54
|
+
if (value && typeof value === 'object') return [value as Record<string, unknown>];
|
|
55
|
+
} catch {
|
|
56
|
+
// Podman prints an array; if it printed something else, say nothing.
|
|
57
|
+
}
|
|
58
|
+
return [];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function str(value: unknown): string | null {
|
|
62
|
+
if (typeof value === 'string') return value.trim() || null;
|
|
63
|
+
if (typeof value === 'number' && Number.isFinite(value)) return String(value);
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function num(value: unknown): number | null {
|
|
68
|
+
if (typeof value === 'number' && Number.isFinite(value)) return value;
|
|
69
|
+
if (typeof value === 'string' && value.trim()) {
|
|
70
|
+
const parsed = Number(value);
|
|
71
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
72
|
+
}
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* A timestamp from either runtime, as an ISO string or null.
|
|
78
|
+
*
|
|
79
|
+
* Docker prints `2026-08-25 09:02:11 +0700 WIB` — a Go time layout whose
|
|
80
|
+
* trailing zone abbreviation no `Date` can parse, and whose abbreviation is
|
|
81
|
+
* locale-dependent besides. The offset that precedes it is unambiguous, so the
|
|
82
|
+
* date is rebuilt from the parts and the abbreviation dropped. Podman prints
|
|
83
|
+
* RFC 3339, or a Unix epoch in older versions. Anything else reports null
|
|
84
|
+
* rather than a date that would be quietly wrong.
|
|
85
|
+
*/
|
|
86
|
+
export function parseTimestamp(value: unknown): string | null {
|
|
87
|
+
if (value === null || value === undefined) return null;
|
|
88
|
+
|
|
89
|
+
if (typeof value === 'number') {
|
|
90
|
+
if (!Number.isFinite(value) || value <= 0) return null;
|
|
91
|
+
// Seconds below ~year 33658, milliseconds above it.
|
|
92
|
+
const date = new Date(value > 1e12 ? value : value * 1000);
|
|
93
|
+
return Number.isNaN(date.getTime()) ? null : date.toISOString();
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (typeof value !== 'string') return null;
|
|
97
|
+
const text = value.trim();
|
|
98
|
+
if (!text) return null;
|
|
99
|
+
// Go's zero time: what both runtimes print for a container that never ran.
|
|
100
|
+
if (text.startsWith('0001-01-01')) return null;
|
|
101
|
+
|
|
102
|
+
if (/^\d+$/.test(text)) return parseTimestamp(Number(text));
|
|
103
|
+
|
|
104
|
+
// Deliberately the only accepted shape. `new Date` as a fallback looks
|
|
105
|
+
// harmless and is not: handed a French `mar. août 25 09:02:11 2026` it
|
|
106
|
+
// returns 25 March without complaint, which is how a wrong date reaches a
|
|
107
|
+
// user's screen looking exactly like a right one.
|
|
108
|
+
const match = text.match(
|
|
109
|
+
/^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2})(\.\d+)?\s*(Z|[+-]\d{2}:?\d{2})?/
|
|
110
|
+
);
|
|
111
|
+
if (!match) return null;
|
|
112
|
+
|
|
113
|
+
const [, day, time, fraction, zone] = match;
|
|
114
|
+
// A zone with no colon (`+0700`) is Go's spelling; ISO wants `+07:00`.
|
|
115
|
+
const offset = zone && zone !== 'Z' && !zone.includes(':')
|
|
116
|
+
? `${zone.slice(0, 3)}:${zone.slice(3)}`
|
|
117
|
+
: (zone ?? '');
|
|
118
|
+
const date = new Date(`${day}T${time}${fraction ?? ''}${offset}`);
|
|
119
|
+
return Number.isNaN(date.getTime()) ? null : date.toISOString();
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* The lifecycle state, from whichever field the runtime filled in.
|
|
124
|
+
*
|
|
125
|
+
* Docker before 20.10 has no `State` column at all, so the status text is the
|
|
126
|
+
* fallback: `Up 3 hours` and `Exited (0) 2 days ago` are the same sentence the
|
|
127
|
+
* daemon would have put in `State`.
|
|
128
|
+
*/
|
|
129
|
+
export function normaliseState(state: string | null, statusText: string | null): ContainerState {
|
|
130
|
+
const value = (state ?? '').trim().toLowerCase();
|
|
131
|
+
switch (value) {
|
|
132
|
+
case 'running':
|
|
133
|
+
case 'paused':
|
|
134
|
+
case 'restarting':
|
|
135
|
+
case 'created':
|
|
136
|
+
case 'exited':
|
|
137
|
+
case 'dead':
|
|
138
|
+
case 'removing':
|
|
139
|
+
return value;
|
|
140
|
+
case 'stopped':
|
|
141
|
+
// Podman's word for what Docker calls `exited`.
|
|
142
|
+
return 'exited';
|
|
143
|
+
case 'configured':
|
|
144
|
+
// Podman's word for a container that has never run.
|
|
145
|
+
return 'created';
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const status = (statusText ?? '').trim().toLowerCase();
|
|
149
|
+
if (status.startsWith('up')) return status.includes('(paused)') ? 'paused' : 'running';
|
|
150
|
+
if (status.startsWith('exited')) return 'exited';
|
|
151
|
+
if (status.startsWith('created')) return 'created';
|
|
152
|
+
if (status.startsWith('restarting')) return 'restarting';
|
|
153
|
+
if (status.startsWith('removal') || status.startsWith('removing')) return 'removing';
|
|
154
|
+
if (status.startsWith('dead')) return 'dead';
|
|
155
|
+
return 'unknown';
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** The healthcheck verdict, which both runtimes report inside the status text. */
|
|
159
|
+
export function healthFrom(statusText: string | null, explicit?: unknown): ContainerHealth {
|
|
160
|
+
const direct = (str(explicit) ?? '').toLowerCase();
|
|
161
|
+
if (direct === 'healthy' || direct === 'unhealthy' || direct === 'starting') return direct;
|
|
162
|
+
|
|
163
|
+
const status = (statusText ?? '').toLowerCase();
|
|
164
|
+
if (status.includes('(healthy)')) return 'healthy';
|
|
165
|
+
if (status.includes('(unhealthy)')) return 'unhealthy';
|
|
166
|
+
if (status.includes('health: starting')) return 'starting';
|
|
167
|
+
return 'none';
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Docker's `Ports` column: a comma-separated list mixing published mappings
|
|
172
|
+
* (`0.0.0.0:8080->80/tcp`), the IPv6 mapping that shadows them (`:::8080->…`)
|
|
173
|
+
* and bare exposed ports (`9000/tcp`). Ranges appear collapsed
|
|
174
|
+
* (`0.0.0.0:8000-8002->8000-8002/tcp`) and are expanded, because a row that
|
|
175
|
+
* says "8000" when the host also holds 8001 is the kind of half-truth this
|
|
176
|
+
* feature exists to remove.
|
|
177
|
+
*/
|
|
178
|
+
export function parseDockerPortsField(value: string | null): ContainerPortBinding[] {
|
|
179
|
+
if (!value) return [];
|
|
180
|
+
const bindings: ContainerPortBinding[] = [];
|
|
181
|
+
|
|
182
|
+
for (const part of value.split(',')) {
|
|
183
|
+
const text = part.trim();
|
|
184
|
+
if (!text) continue;
|
|
185
|
+
|
|
186
|
+
const mapped = text.match(/^(.*):(\d+)(?:-(\d+))?->(\d+)(?:-(\d+))?\/(tcp|udp)$/i);
|
|
187
|
+
if (mapped) {
|
|
188
|
+
const [, address, hostStart, hostEnd, containerStart, containerEnd, protocol] = mapped;
|
|
189
|
+
const spanHost = Number(hostEnd ?? hostStart) - Number(hostStart);
|
|
190
|
+
const spanContainer = Number(containerEnd ?? containerStart) - Number(containerStart);
|
|
191
|
+
const span = Math.min(Math.max(spanHost, spanContainer), MAX_PORT_RANGE);
|
|
192
|
+
for (let offset = 0; offset <= span; offset++) {
|
|
193
|
+
bindings.push({
|
|
194
|
+
hostAddress: address || null,
|
|
195
|
+
hostPort: Number(hostStart) + offset,
|
|
196
|
+
containerPort: Number(containerStart) + offset,
|
|
197
|
+
protocol: protocol.toLowerCase() as 'tcp' | 'udp'
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const exposed = text.match(/^(\d+)(?:-(\d+))?\/(tcp|udp)$/i);
|
|
204
|
+
if (exposed) {
|
|
205
|
+
const [, start, end, protocol] = exposed;
|
|
206
|
+
const span = Math.min(Number(end ?? start) - Number(start), MAX_PORT_RANGE);
|
|
207
|
+
for (let offset = 0; offset <= span; offset++) {
|
|
208
|
+
bindings.push({
|
|
209
|
+
hostAddress: null,
|
|
210
|
+
hostPort: null,
|
|
211
|
+
containerPort: Number(start) + offset,
|
|
212
|
+
protocol: protocol.toLowerCase() as 'tcp' | 'udp'
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
return dedupeBindings(bindings);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** A published range is expanded, but not without bound. */
|
|
222
|
+
const MAX_PORT_RANGE = 64;
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Docker publishes on IPv4 and IPv6 separately, so the same mapping arrives
|
|
226
|
+
* twice under two addresses. The pair is one binding to a reader, so the second
|
|
227
|
+
* address is folded into the first rather than repeated.
|
|
228
|
+
*/
|
|
229
|
+
function dedupeBindings(bindings: ContainerPortBinding[]): ContainerPortBinding[] {
|
|
230
|
+
const seen = new Map<string, ContainerPortBinding>();
|
|
231
|
+
for (const binding of bindings) {
|
|
232
|
+
const key = `${binding.protocol}:${binding.hostPort ?? 'none'}:${binding.containerPort}`;
|
|
233
|
+
const existing = seen.get(key);
|
|
234
|
+
if (!existing) {
|
|
235
|
+
seen.set(key, binding);
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
// Prefer the address that says something: `0.0.0.0` over `::`.
|
|
239
|
+
if (existing.hostAddress === '::' && binding.hostAddress && binding.hostAddress !== '::') {
|
|
240
|
+
seen.set(key, binding);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
// Published ports first, in port order; the merely exposed ones after, since
|
|
244
|
+
// they are the ones nobody can reach from outside the host.
|
|
245
|
+
return [...seen.values()].sort(
|
|
246
|
+
(a, b) =>
|
|
247
|
+
Number(a.hostPort === null) - Number(b.hostPort === null) ||
|
|
248
|
+
(a.hostPort ?? 0) - (b.hostPort ?? 0) ||
|
|
249
|
+
a.containerPort - b.containerPort
|
|
250
|
+
);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Podman's structured ports, including its `range` shorthand. */
|
|
254
|
+
function parsePodmanPorts(value: unknown): ContainerPortBinding[] {
|
|
255
|
+
if (!Array.isArray(value)) return [];
|
|
256
|
+
const bindings: ContainerPortBinding[] = [];
|
|
257
|
+
|
|
258
|
+
for (const raw of value) {
|
|
259
|
+
if (!raw || typeof raw !== 'object') continue;
|
|
260
|
+
const row = raw as Record<string, unknown>;
|
|
261
|
+
const containerPort = num(row.container_port ?? row.containerPort);
|
|
262
|
+
if (containerPort === null) continue;
|
|
263
|
+
const hostPort = num(row.host_port ?? row.hostPort);
|
|
264
|
+
const protocol = (str(row.protocol) ?? 'tcp').toLowerCase() === 'udp' ? 'udp' : 'tcp';
|
|
265
|
+
const span = Math.min(Math.max((num(row.range) ?? 1) - 1, 0), MAX_PORT_RANGE);
|
|
266
|
+
|
|
267
|
+
for (let offset = 0; offset <= span; offset++) {
|
|
268
|
+
bindings.push({
|
|
269
|
+
hostAddress: str(row.host_ip ?? row.hostIP) ?? null,
|
|
270
|
+
hostPort: hostPort === null || hostPort === 0 ? null : hostPort + offset,
|
|
271
|
+
containerPort: containerPort + offset,
|
|
272
|
+
protocol
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
return dedupeBindings(bindings);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Docker's `Labels` column: `k=v,k=v`. Podman hands over an object already. */
|
|
281
|
+
function parseLabels(value: unknown): Map<string, string> {
|
|
282
|
+
const labels = new Map<string, string>();
|
|
283
|
+
|
|
284
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
285
|
+
for (const [key, raw] of Object.entries(value as Record<string, unknown>)) {
|
|
286
|
+
const text = str(raw);
|
|
287
|
+
if (text !== null) labels.set(key, text);
|
|
288
|
+
}
|
|
289
|
+
return labels;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const text = str(value);
|
|
293
|
+
if (!text) return labels;
|
|
294
|
+
for (const pair of text.split(',')) {
|
|
295
|
+
const index = pair.indexOf('=');
|
|
296
|
+
if (index <= 0) continue;
|
|
297
|
+
labels.set(pair.slice(0, index).trim(), pair.slice(index + 1).trim());
|
|
298
|
+
}
|
|
299
|
+
return labels;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
const COMPOSE_PROJECT_LABELS = ['com.docker.compose.project', 'io.podman.compose.project'];
|
|
303
|
+
const COMPOSE_SERVICE_LABELS = ['com.docker.compose.service', 'io.podman.compose.service'];
|
|
304
|
+
|
|
305
|
+
function firstLabel(labels: Map<string, string>, keys: string[]): string | null {
|
|
306
|
+
for (const key of keys) {
|
|
307
|
+
const value = labels.get(key);
|
|
308
|
+
if (value) return value;
|
|
309
|
+
}
|
|
310
|
+
return null;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function shortId(id: string): string {
|
|
314
|
+
return id.length > 12 ? id.slice(0, 12) : id;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* A status line for a runtime that did not write one.
|
|
319
|
+
*
|
|
320
|
+
* Podman's JSON leaves `Status` empty in some versions, and an empty cell in
|
|
321
|
+
* the column a user reads first is worse than a sentence assembled from the
|
|
322
|
+
* state and the start time — which is exactly how Docker builds its own.
|
|
323
|
+
*/
|
|
324
|
+
function synthesiseStatus(state: ContainerState, startedAt: string | null, exitCode: number | null): string {
|
|
325
|
+
if (state === 'running' || state === 'paused') {
|
|
326
|
+
const suffix = state === 'paused' ? ' (Paused)' : '';
|
|
327
|
+
if (!startedAt) return `Up${suffix}`;
|
|
328
|
+
return `Up ${describeSpan(Date.parse(startedAt))}${suffix}`;
|
|
329
|
+
}
|
|
330
|
+
if (state === 'exited') return exitCode === null ? 'Exited' : `Exited (${exitCode})`;
|
|
331
|
+
return state.charAt(0).toUpperCase() + state.slice(1);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** `3 hours`, `2 days` — the coarse span both runtimes print. */
|
|
335
|
+
function describeSpan(since: number, now = Date.now()): string {
|
|
336
|
+
const seconds = Math.max(1, Math.round((now - since) / 1000));
|
|
337
|
+
if (seconds < 60) return `${seconds} seconds`;
|
|
338
|
+
const minutes = Math.round(seconds / 60);
|
|
339
|
+
if (minutes < 60) return `${minutes} minute${minutes === 1 ? '' : 's'}`;
|
|
340
|
+
const hours = Math.round(minutes / 60);
|
|
341
|
+
if (hours < 48) return `${hours} hour${hours === 1 ? '' : 's'}`;
|
|
342
|
+
const days = Math.round(hours / 24);
|
|
343
|
+
return `${days} day${days === 1 ? '' : 's'}`;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** `docker ps --all --no-trunc --format {{json .}}`. */
|
|
347
|
+
export function parseDockerPs(stdout: string, hostId: string): ContainerEntry[] {
|
|
348
|
+
return readJsonLines(stdout)
|
|
349
|
+
.map((row): ContainerEntry | null => {
|
|
350
|
+
const id = str(row.ID ?? row.Id);
|
|
351
|
+
if (!id) return null;
|
|
352
|
+
|
|
353
|
+
const statusText = str(row.Status) ?? '';
|
|
354
|
+
const state = normaliseState(str(row.State), statusText);
|
|
355
|
+
const labels = parseLabels(row.Labels);
|
|
356
|
+
// `Names` carries every name a container answers to; the first is the
|
|
357
|
+
// one the runtime itself prints.
|
|
358
|
+
const name = (str(row.Names) ?? '').split(',')[0].trim() || shortId(id);
|
|
359
|
+
|
|
360
|
+
return {
|
|
361
|
+
key: `${hostId}:${id}`,
|
|
362
|
+
id,
|
|
363
|
+
shortId: shortId(id),
|
|
364
|
+
name,
|
|
365
|
+
image: str(row.Image) ?? 'unknown',
|
|
366
|
+
state,
|
|
367
|
+
statusText: statusText || synthesiseStatus(state, null, null),
|
|
368
|
+
health: healthFrom(statusText),
|
|
369
|
+
createdAt: parseTimestamp(row.CreatedAt),
|
|
370
|
+
startedAt: null,
|
|
371
|
+
ports: parseDockerPortsField(str(row.Ports)),
|
|
372
|
+
composeProject: firstLabel(labels, COMPOSE_PROJECT_LABELS),
|
|
373
|
+
composeService: firstLabel(labels, COMPOSE_SERVICE_LABELS),
|
|
374
|
+
command: str(row.Command),
|
|
375
|
+
canManage: state !== 'removing'
|
|
376
|
+
};
|
|
377
|
+
})
|
|
378
|
+
.filter((entry): entry is ContainerEntry => entry !== null);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** `podman ps --all --no-trunc --format json`. */
|
|
382
|
+
export function parsePodmanPs(stdout: string, hostId: string): ContainerEntry[] {
|
|
383
|
+
return readJsonArray(stdout)
|
|
384
|
+
.filter((row) => row.IsInfra !== true)
|
|
385
|
+
.map((row): ContainerEntry | null => {
|
|
386
|
+
const id = str(row.Id ?? row.ID);
|
|
387
|
+
if (!id) return null;
|
|
388
|
+
|
|
389
|
+
const names = Array.isArray(row.Names) ? row.Names.map(str).filter(Boolean) : [str(row.Names)];
|
|
390
|
+
const startedAt = parseTimestamp(row.StartedAt);
|
|
391
|
+
const state = normaliseState(str(row.State), str(row.Status));
|
|
392
|
+
const labels = parseLabels(row.Labels);
|
|
393
|
+
const command = Array.isArray(row.Command)
|
|
394
|
+
? row.Command.map((part) => str(part) ?? '').join(' ').trim() || null
|
|
395
|
+
: str(row.Command);
|
|
396
|
+
|
|
397
|
+
return {
|
|
398
|
+
key: `${hostId}:${id}`,
|
|
399
|
+
id,
|
|
400
|
+
shortId: shortId(id),
|
|
401
|
+
name: (names[0] as string | null) ?? shortId(id),
|
|
402
|
+
image: str(row.Image) ?? 'unknown',
|
|
403
|
+
state,
|
|
404
|
+
statusText: str(row.Status) ?? synthesiseStatus(state, startedAt, num(row.ExitCode)),
|
|
405
|
+
health: healthFrom(str(row.Status), row.Health ?? row.HealthStatus),
|
|
406
|
+
createdAt: parseTimestamp(row.Created ?? row.CreatedAt),
|
|
407
|
+
startedAt: state === 'running' || state === 'paused' ? startedAt : null,
|
|
408
|
+
ports: parsePodmanPorts(row.Ports),
|
|
409
|
+
composeProject: firstLabel(labels, COMPOSE_PROJECT_LABELS),
|
|
410
|
+
composeService: firstLabel(labels, COMPOSE_SERVICE_LABELS),
|
|
411
|
+
command,
|
|
412
|
+
canManage: state !== 'removing'
|
|
413
|
+
};
|
|
414
|
+
})
|
|
415
|
+
.filter((entry): entry is ContainerEntry => entry !== null);
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/** Bytes as the runtimes print them, for a Podman size that arrives as a number. */
|
|
419
|
+
function humanSize(bytes: number | null): string {
|
|
420
|
+
if (bytes === null) return 'unknown';
|
|
421
|
+
const units = ['B', 'kB', 'MB', 'GB', 'TB'];
|
|
422
|
+
let value = bytes;
|
|
423
|
+
let unit = 0;
|
|
424
|
+
while (value >= 1000 && unit < units.length - 1) {
|
|
425
|
+
value /= 1000;
|
|
426
|
+
unit++;
|
|
427
|
+
}
|
|
428
|
+
return `${value >= 10 || unit === 0 ? Math.round(value) : value.toFixed(1)}${units[unit]}`;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/** `docker images --format {{json .}}`. */
|
|
432
|
+
export function parseDockerImages(stdout: string): ContainerImageEntry[] {
|
|
433
|
+
return readJsonLines(stdout)
|
|
434
|
+
.map((row): ContainerImageEntry | null => {
|
|
435
|
+
const id = str(row.ID ?? row.Id);
|
|
436
|
+
if (!id) return null;
|
|
437
|
+
const repository = str(row.Repository) ?? '<none>';
|
|
438
|
+
const tag = str(row.Tag) ?? '<none>';
|
|
439
|
+
return {
|
|
440
|
+
key: `${id}:${repository}:${tag}`,
|
|
441
|
+
id,
|
|
442
|
+
repository,
|
|
443
|
+
tag,
|
|
444
|
+
size: str(row.Size) ?? 'unknown',
|
|
445
|
+
createdAt: parseTimestamp(row.CreatedAt),
|
|
446
|
+
dangling: repository === '<none>' && tag === '<none>',
|
|
447
|
+
usedBy: []
|
|
448
|
+
};
|
|
449
|
+
})
|
|
450
|
+
.filter((entry): entry is ContainerImageEntry => entry !== null);
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/** `podman images --format json`. One row per repo:tag, like Docker's table. */
|
|
454
|
+
export function parsePodmanImages(stdout: string): ContainerImageEntry[] {
|
|
455
|
+
const images: ContainerImageEntry[] = [];
|
|
456
|
+
|
|
457
|
+
for (const row of readJsonArray(stdout)) {
|
|
458
|
+
const id = str(row.Id ?? row.ID);
|
|
459
|
+
if (!id) continue;
|
|
460
|
+
const size = humanSize(num(row.Size));
|
|
461
|
+
const createdAt = parseTimestamp(row.Created ?? row.CreatedAt);
|
|
462
|
+
const tags = Array.isArray(row.Names)
|
|
463
|
+
? row.Names.map(str).filter((tag): tag is string => tag !== null)
|
|
464
|
+
: Array.isArray(row.RepoTags)
|
|
465
|
+
? row.RepoTags.map(str).filter((tag): tag is string => tag !== null)
|
|
466
|
+
: [];
|
|
467
|
+
|
|
468
|
+
if (tags.length === 0) {
|
|
469
|
+
images.push({
|
|
470
|
+
key: `${id}:<none>:<none>`,
|
|
471
|
+
id,
|
|
472
|
+
repository: '<none>',
|
|
473
|
+
tag: '<none>',
|
|
474
|
+
size,
|
|
475
|
+
createdAt,
|
|
476
|
+
dangling: true,
|
|
477
|
+
usedBy: []
|
|
478
|
+
});
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
for (const tag of tags) {
|
|
483
|
+
const at = tag.lastIndexOf(':');
|
|
484
|
+
// A registry port (`localhost:5000/app`) also contains a colon, so the
|
|
485
|
+
// split only counts when nothing after it looks like a path.
|
|
486
|
+
const hasTag = at > 0 && !tag.slice(at + 1).includes('/');
|
|
487
|
+
images.push({
|
|
488
|
+
key: `${id}:${tag}`,
|
|
489
|
+
id,
|
|
490
|
+
repository: hasTag ? tag.slice(0, at) : tag,
|
|
491
|
+
tag: hasTag ? tag.slice(at + 1) : 'latest',
|
|
492
|
+
size,
|
|
493
|
+
createdAt,
|
|
494
|
+
dangling: false,
|
|
495
|
+
usedBy: []
|
|
496
|
+
});
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
return images;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/** `docker volume ls --format {{json .}}`. Docker reports no creation time. */
|
|
504
|
+
export function parseDockerVolumes(stdout: string): ContainerVolumeEntry[] {
|
|
505
|
+
return readJsonLines(stdout)
|
|
506
|
+
.map((row): ContainerVolumeEntry | null => {
|
|
507
|
+
const name = str(row.Name);
|
|
508
|
+
if (!name) return null;
|
|
509
|
+
return {
|
|
510
|
+
key: name,
|
|
511
|
+
name,
|
|
512
|
+
driver: str(row.Driver) ?? 'local',
|
|
513
|
+
mountpoint: str(row.Mountpoint),
|
|
514
|
+
createdAt: parseTimestamp(row.CreatedAt),
|
|
515
|
+
usedBy: []
|
|
516
|
+
};
|
|
517
|
+
})
|
|
518
|
+
.filter((entry): entry is ContainerVolumeEntry => entry !== null);
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/** `podman volume ls --format json`. */
|
|
522
|
+
export function parsePodmanVolumes(stdout: string): ContainerVolumeEntry[] {
|
|
523
|
+
return readJsonArray(stdout)
|
|
524
|
+
.map((row): ContainerVolumeEntry | null => {
|
|
525
|
+
const name = str(row.Name);
|
|
526
|
+
if (!name) return null;
|
|
527
|
+
return {
|
|
528
|
+
key: name,
|
|
529
|
+
name,
|
|
530
|
+
driver: str(row.Driver) ?? 'local',
|
|
531
|
+
mountpoint: str(row.Mountpoint),
|
|
532
|
+
createdAt: parseTimestamp(row.CreatedAt),
|
|
533
|
+
usedBy: []
|
|
534
|
+
};
|
|
535
|
+
})
|
|
536
|
+
.filter((entry): entry is ContainerVolumeEntry => entry !== null);
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* The networks the runtime creates and owns.
|
|
541
|
+
*
|
|
542
|
+
* Listed so they can be shown, and named so they are never offered as
|
|
543
|
+
* something to delete: a `network rm bridge` fails on every host, and an action
|
|
544
|
+
* that can only fail should not be on screen.
|
|
545
|
+
*/
|
|
546
|
+
const PREDEFINED_NETWORKS = new Set(['bridge', 'host', 'none', 'podman', 'ingress', 'docker_gwbridge']);
|
|
547
|
+
|
|
548
|
+
/** `docker network ls --no-trunc --format {{json .}}`. */
|
|
549
|
+
export function parseDockerNetworks(stdout: string): ContainerNetworkEntry[] {
|
|
550
|
+
return readJsonLines(stdout)
|
|
551
|
+
.map((row): ContainerNetworkEntry | null => {
|
|
552
|
+
const id = str(row.ID ?? row.Id);
|
|
553
|
+
const name = str(row.Name);
|
|
554
|
+
if (!id || !name) return null;
|
|
555
|
+
return {
|
|
556
|
+
key: id,
|
|
557
|
+
id,
|
|
558
|
+
name,
|
|
559
|
+
driver: str(row.Driver) ?? 'bridge',
|
|
560
|
+
scope: str(row.Scope) ?? 'local',
|
|
561
|
+
internal: row.Internal === true || str(row.Internal) === 'true',
|
|
562
|
+
createdAt: parseTimestamp(row.CreatedAt),
|
|
563
|
+
usedBy: [],
|
|
564
|
+
predefined: PREDEFINED_NETWORKS.has(name)
|
|
565
|
+
};
|
|
566
|
+
})
|
|
567
|
+
.filter((entry): entry is ContainerNetworkEntry => entry !== null);
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
/**
|
|
571
|
+
* `podman network ls --format json`. Podman spells its network fields in
|
|
572
|
+
* lower case where Docker capitalises them, so both spellings are read.
|
|
573
|
+
*/
|
|
574
|
+
export function parsePodmanNetworks(stdout: string): ContainerNetworkEntry[] {
|
|
575
|
+
return readJsonArray(stdout)
|
|
576
|
+
.map((row): ContainerNetworkEntry | null => {
|
|
577
|
+
const id = str(row.id ?? row.ID ?? row.Id);
|
|
578
|
+
const name = str(row.name ?? row.Name);
|
|
579
|
+
if (!name) return null;
|
|
580
|
+
return {
|
|
581
|
+
// Podman's rootless networks have no id in some versions; the name is
|
|
582
|
+
// unique either way and is what `network rm` takes.
|
|
583
|
+
key: id ?? name,
|
|
584
|
+
id: id ?? name,
|
|
585
|
+
name,
|
|
586
|
+
driver: str(row.driver ?? row.Driver) ?? 'bridge',
|
|
587
|
+
scope: str(row.scope ?? row.Scope) ?? 'local',
|
|
588
|
+
internal: row.internal === true || row.Internal === true,
|
|
589
|
+
createdAt: parseTimestamp(row.created ?? row.Created ?? row.CreatedAt),
|
|
590
|
+
usedBy: [],
|
|
591
|
+
predefined: PREDEFINED_NETWORKS.has(name)
|
|
592
|
+
};
|
|
593
|
+
})
|
|
594
|
+
.filter((entry): entry is ContainerNetworkEntry => entry !== null);
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/**
|
|
598
|
+
* Which containers use each image and volume.
|
|
599
|
+
*
|
|
600
|
+
* Computed from the container list already in hand rather than asked of the
|
|
601
|
+
* runtime: a second round trip per image would cost more than the answer is
|
|
602
|
+
* worth, and the answer is exact either way.
|
|
603
|
+
*/
|
|
604
|
+
export function linkUsage(
|
|
605
|
+
entries: ContainerEntry[],
|
|
606
|
+
images: ContainerImageEntry[],
|
|
607
|
+
volumes: ContainerVolumeEntry[],
|
|
608
|
+
mountsByContainer: Map<string, string[]>,
|
|
609
|
+
networks: ContainerNetworkEntry[] = [],
|
|
610
|
+
networksByContainer: Map<string, string[]> = new Map()
|
|
611
|
+
): void {
|
|
612
|
+
for (const image of images) {
|
|
613
|
+
const tagged = `${image.repository}:${image.tag}`;
|
|
614
|
+
image.usedBy = entries
|
|
615
|
+
.filter((entry) => {
|
|
616
|
+
const used = entry.image;
|
|
617
|
+
if (used === tagged || used === image.repository) return true;
|
|
618
|
+
// Podman prints fully qualified names; Docker's short form is a suffix.
|
|
619
|
+
if (used.endsWith(`/${tagged}`)) return true;
|
|
620
|
+
return used.startsWith(image.id) || image.id.startsWith(used);
|
|
621
|
+
})
|
|
622
|
+
.map((entry) => entry.name);
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
for (const volume of volumes) {
|
|
626
|
+
volume.usedBy = entries
|
|
627
|
+
.filter((entry) => (mountsByContainer.get(entry.id) ?? []).includes(volume.name))
|
|
628
|
+
.map((entry) => entry.name);
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
for (const network of networks) {
|
|
632
|
+
network.usedBy = entries
|
|
633
|
+
.filter((entry) => (networksByContainer.get(entry.id) ?? []).includes(network.name))
|
|
634
|
+
.map((entry) => entry.name);
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
/** The networks each container is attached to, from either runtime's `ps`. */
|
|
639
|
+
export function parseNetworkMembership(
|
|
640
|
+
stdout: string,
|
|
641
|
+
runtime: 'docker' | 'podman'
|
|
642
|
+
): Map<string, string[]> {
|
|
643
|
+
const membership = new Map<string, string[]>();
|
|
644
|
+
const rows = runtime === 'docker' ? readJsonLines(stdout) : readJsonArray(stdout);
|
|
645
|
+
|
|
646
|
+
for (const row of rows) {
|
|
647
|
+
const id = str(row.ID ?? row.Id);
|
|
648
|
+
if (!id) continue;
|
|
649
|
+
const raw = row.Networks;
|
|
650
|
+
const names = Array.isArray(raw)
|
|
651
|
+
? raw.map((name) => str(name)).filter((name): name is string => name !== null)
|
|
652
|
+
: (str(raw) ?? '')
|
|
653
|
+
.split(',')
|
|
654
|
+
.map((name) => name.trim())
|
|
655
|
+
.filter(Boolean);
|
|
656
|
+
membership.set(id, names);
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
return membership;
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
/** The volume names each container mounts, from either runtime's `ps` output. */
|
|
663
|
+
export function parseMounts(stdout: string, runtime: 'docker' | 'podman'): Map<string, string[]> {
|
|
664
|
+
const mounts = new Map<string, string[]>();
|
|
665
|
+
const rows = runtime === 'docker' ? readJsonLines(stdout) : readJsonArray(stdout);
|
|
666
|
+
|
|
667
|
+
for (const row of rows) {
|
|
668
|
+
const id = str(row.ID ?? row.Id);
|
|
669
|
+
if (!id) continue;
|
|
670
|
+
const raw = row.Mounts;
|
|
671
|
+
const names = Array.isArray(raw)
|
|
672
|
+
? raw
|
|
673
|
+
.map((mount) =>
|
|
674
|
+
typeof mount === 'string' ? mount : str((mount as Record<string, unknown>)?.Name)
|
|
675
|
+
)
|
|
676
|
+
.filter((name): name is string => name !== null)
|
|
677
|
+
: (str(raw) ?? '')
|
|
678
|
+
.split(',')
|
|
679
|
+
.map((name) => name.trim())
|
|
680
|
+
.filter(Boolean);
|
|
681
|
+
mounts.set(id, names);
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
return mounts;
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
/**
|
|
688
|
+
* `inspect --format {{json .}}` from either runtime.
|
|
689
|
+
*
|
|
690
|
+
* Podman deliberately mirrors Docker's inspect schema, so one reader serves
|
|
691
|
+
* both. Fields either runtime may omit are reported as null rather than
|
|
692
|
+
* defaulted, because "this host did not say" and "zero" are different answers.
|
|
693
|
+
*/
|
|
694
|
+
export function parseInspect(stdout: string): ContainerDetail | null {
|
|
695
|
+
const rows = stdout.trim().startsWith('[') ? readJsonArray(stdout) : readJsonLines(stdout);
|
|
696
|
+
const row = rows[0];
|
|
697
|
+
if (!row) return null;
|
|
698
|
+
|
|
699
|
+
const id = str(row.Id ?? row.ID);
|
|
700
|
+
if (!id) return null;
|
|
701
|
+
|
|
702
|
+
const state = (row.State ?? {}) as Record<string, unknown>;
|
|
703
|
+
const config = (row.Config ?? {}) as Record<string, unknown>;
|
|
704
|
+
const hostConfig = (row.HostConfig ?? {}) as Record<string, unknown>;
|
|
705
|
+
const networkSettings = (row.NetworkSettings ?? {}) as Record<string, unknown>;
|
|
706
|
+
const health = (state.Health ?? {}) as Record<string, unknown>;
|
|
707
|
+
|
|
708
|
+
const statusText = str(state.Status);
|
|
709
|
+
const command = Array.isArray(config.Cmd)
|
|
710
|
+
? config.Cmd.map((part) => str(part) ?? '').join(' ').trim() || null
|
|
711
|
+
: str(row.Path);
|
|
712
|
+
|
|
713
|
+
const networks: ContainerDetail['networks'] = [];
|
|
714
|
+
const rawNetworks = (networkSettings.Networks ?? {}) as Record<string, unknown>;
|
|
715
|
+
for (const [name, raw] of Object.entries(rawNetworks)) {
|
|
716
|
+
const value = (raw ?? {}) as Record<string, unknown>;
|
|
717
|
+
networks.push({ name, ipAddress: str(value.IPAddress) });
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
const mounts: ContainerDetail['mounts'] = [];
|
|
721
|
+
if (Array.isArray(row.Mounts)) {
|
|
722
|
+
for (const raw of row.Mounts) {
|
|
723
|
+
const mount = (raw ?? {}) as Record<string, unknown>;
|
|
724
|
+
const destination = str(mount.Destination);
|
|
725
|
+
if (!destination) continue;
|
|
726
|
+
mounts.push({
|
|
727
|
+
source: str(mount.Source) ?? str(mount.Name) ?? '',
|
|
728
|
+
destination,
|
|
729
|
+
readOnly: mount.RW === false || mount.ReadOnly === true,
|
|
730
|
+
kind: str(mount.Type) ?? 'bind'
|
|
731
|
+
});
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
const ports: ContainerPortBinding[] = [];
|
|
736
|
+
const rawPorts = (networkSettings.Ports ?? {}) as Record<string, unknown>;
|
|
737
|
+
for (const [spec, raw] of Object.entries(rawPorts)) {
|
|
738
|
+
const match = spec.match(/^(\d+)\/(tcp|udp)$/i);
|
|
739
|
+
if (!match) continue;
|
|
740
|
+
const containerPort = Number(match[1]);
|
|
741
|
+
const protocol = match[2].toLowerCase() as 'tcp' | 'udp';
|
|
742
|
+
if (!Array.isArray(raw) || raw.length === 0) {
|
|
743
|
+
ports.push({ hostAddress: null, hostPort: null, containerPort, protocol });
|
|
744
|
+
continue;
|
|
745
|
+
}
|
|
746
|
+
for (const binding of raw) {
|
|
747
|
+
const value = (binding ?? {}) as Record<string, unknown>;
|
|
748
|
+
ports.push({
|
|
749
|
+
hostAddress: str(value.HostIp) ?? null,
|
|
750
|
+
hostPort: num(value.HostPort),
|
|
751
|
+
containerPort,
|
|
752
|
+
protocol
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
const labels: ContainerDetail['labels'] = [];
|
|
758
|
+
for (const [key, value] of parseLabels(config.Labels)) labels.push({ key, value });
|
|
759
|
+
labels.sort((a, b) => a.key.localeCompare(b.key));
|
|
760
|
+
|
|
761
|
+
const restartPolicy = (hostConfig.RestartPolicy ?? {}) as Record<string, unknown>;
|
|
762
|
+
|
|
763
|
+
return {
|
|
764
|
+
id,
|
|
765
|
+
// Docker prefixes the name with a slash; nobody reads it that way.
|
|
766
|
+
name: (str(row.Name) ?? shortId(id)).replace(/^\//, ''),
|
|
767
|
+
image: str(config.Image) ?? str((row.Image as unknown) ?? null) ?? 'unknown',
|
|
768
|
+
imageId: str(row.Image),
|
|
769
|
+
command,
|
|
770
|
+
createdAt: parseTimestamp(row.Created),
|
|
771
|
+
startedAt: parseTimestamp(state.StartedAt),
|
|
772
|
+
finishedAt: parseTimestamp(state.FinishedAt),
|
|
773
|
+
state: normaliseState(statusText, statusText),
|
|
774
|
+
health: healthFrom(null, health.Status),
|
|
775
|
+
exitCode: num(state.ExitCode),
|
|
776
|
+
restartCount: num(row.RestartCount),
|
|
777
|
+
restartPolicy: str(restartPolicy.Name),
|
|
778
|
+
pid: num(state.Pid),
|
|
779
|
+
workingDir: str(config.WorkingDir),
|
|
780
|
+
user: str(config.User),
|
|
781
|
+
networks,
|
|
782
|
+
mounts,
|
|
783
|
+
ports: dedupeBindings(ports),
|
|
784
|
+
env: Array.isArray(config.Env)
|
|
785
|
+
? config.Env.map((line) => str(line)).filter((line): line is string => line !== null)
|
|
786
|
+
: [],
|
|
787
|
+
labels
|
|
788
|
+
};
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
/**
|
|
792
|
+
* What a `prune` actually did.
|
|
793
|
+
*
|
|
794
|
+
* Both runtimes print a list of what went and, usually, a total. "Usually" is
|
|
795
|
+
* the problem: Docker states the space it freed and Podman often does not, and
|
|
796
|
+
* Docker's image prune lists untag operations alongside deletions. So the space
|
|
797
|
+
* is reported when the runtime gives it and left null when it does not — a
|
|
798
|
+
* reclaimed figure invented here would be the least trustworthy number on the
|
|
799
|
+
* screen.
|
|
800
|
+
*/
|
|
801
|
+
export function parsePruneOutput(stdout: string): { removed: number; reclaimed: string | null } {
|
|
802
|
+
let reclaimed: string | null = null;
|
|
803
|
+
let removed = 0;
|
|
804
|
+
|
|
805
|
+
for (const raw of stdout.split('\n')) {
|
|
806
|
+
const line = raw.trim();
|
|
807
|
+
if (!line) continue;
|
|
808
|
+
|
|
809
|
+
const total = line.match(/^Total reclaimed space:\s*(.+)$/i);
|
|
810
|
+
if (total) {
|
|
811
|
+
reclaimed = total[1].trim();
|
|
812
|
+
continue;
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
// Section headers Docker prints above each list.
|
|
816
|
+
if (/^deleted [a-z ]+:$/i.test(line) || /^deleted:?$/i.test(line)) continue;
|
|
817
|
+
// `untagged: repo:tag` is a name being dropped, not a thing being deleted;
|
|
818
|
+
// counting it would report twice as many removals as actually happened.
|
|
819
|
+
if (/^untagged:/i.test(line)) continue;
|
|
820
|
+
|
|
821
|
+
removed++;
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
return { removed, reclaimed };
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
/** Map either runtime's word for a resource onto the four this feature knows. */
|
|
828
|
+
function diskUsageKind(type: string): ContainerDiskUsageRow['kind'] | null {
|
|
829
|
+
const value = type.trim().toLowerCase();
|
|
830
|
+
if (value.startsWith('image')) return 'images';
|
|
831
|
+
if (value.startsWith('container')) return 'containers';
|
|
832
|
+
if (value.includes('volume')) return 'volumes';
|
|
833
|
+
if (value.includes('cache')) return 'build-cache';
|
|
834
|
+
return null;
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
/**
|
|
838
|
+
* `system df`, which is the only honest answer to "what would cleaning up get
|
|
839
|
+
* me back". Docker prints one JSON object per resource with human sizes;
|
|
840
|
+
* Podman prints an array, and in some versions gives the sizes as raw bytes.
|
|
841
|
+
*/
|
|
842
|
+
/** The reading itself; the caller stamps it with when it was taken. */
|
|
843
|
+
export function parseDiskUsage(
|
|
844
|
+
stdout: string,
|
|
845
|
+
runtime: 'docker' | 'podman'
|
|
846
|
+
): Omit<ContainerDiskUsage, 'measuredAt'> {
|
|
847
|
+
const rows = runtime === 'docker' ? readJsonLines(stdout) : readJsonArray(stdout);
|
|
848
|
+
const parsed: ContainerDiskUsageRow[] = [];
|
|
849
|
+
|
|
850
|
+
for (const row of rows) {
|
|
851
|
+
const kind = diskUsageKind(str(row.Type ?? row.type) ?? '');
|
|
852
|
+
if (!kind) continue;
|
|
853
|
+
|
|
854
|
+
const sizeRaw = row.Size ?? row.size;
|
|
855
|
+
const reclaimableRaw = row.Reclaimable ?? row.reclaimable;
|
|
856
|
+
|
|
857
|
+
parsed.push({
|
|
858
|
+
kind,
|
|
859
|
+
total: num(row.TotalCount ?? row.Total ?? row.total),
|
|
860
|
+
active: num(row.Active ?? row.active),
|
|
861
|
+
size: typeof sizeRaw === 'number' ? humanSize(sizeRaw) : (str(sizeRaw) ?? 'unknown'),
|
|
862
|
+
reclaimable:
|
|
863
|
+
typeof reclaimableRaw === 'number'
|
|
864
|
+
? humanSize(reclaimableRaw)
|
|
865
|
+
: (str(reclaimableRaw) ?? 'unknown')
|
|
866
|
+
});
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
return { rows: parsed, error: null };
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
/** A percentage a runtime printed as `1.84%`. */
|
|
873
|
+
function percent(value: unknown): number | null {
|
|
874
|
+
const text = str(value);
|
|
875
|
+
if (!text) return null;
|
|
876
|
+
const parsed = Number.parseFloat(text.replace('%', ''));
|
|
877
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
/**
|
|
881
|
+
* One `stats --no-stream` sample.
|
|
882
|
+
*
|
|
883
|
+
* The two runtimes agree on almost nothing here — Docker capitalises, Podman
|
|
884
|
+
* has used at least three spellings across its versions — so every field is
|
|
885
|
+
* looked up under each name it has been known by, and anything still missing
|
|
886
|
+
* stays null rather than becoming a zero that reads like a measurement.
|
|
887
|
+
*/
|
|
888
|
+
export function parseStats(stdout: string): ContainerStats | null {
|
|
889
|
+
const rows = stdout.trim().startsWith('[') ? readJsonArray(stdout) : readJsonLines(stdout);
|
|
890
|
+
const row = rows[0];
|
|
891
|
+
if (!row) return null;
|
|
892
|
+
|
|
893
|
+
const memUsage = str(row.MemUsage ?? row.mem_usage ?? row.MemoryUsage);
|
|
894
|
+
const memLimit = str(row.MemLimit ?? row.mem_limit);
|
|
895
|
+
|
|
896
|
+
return {
|
|
897
|
+
cpuPercent: percent(row.CPUPerc ?? row.CPU ?? row.cpu_percent ?? row.cpu),
|
|
898
|
+
// Podman reports usage and limit separately where Docker prints one string.
|
|
899
|
+
memoryUsage: memUsage && memLimit && !memUsage.includes('/') ? `${memUsage} / ${memLimit}` : memUsage,
|
|
900
|
+
memoryPercent: percent(row.MemPerc ?? row.mem_percent ?? row.MemPercent),
|
|
901
|
+
networkIO: str(row.NetIO ?? row.net_io ?? row.NetInput),
|
|
902
|
+
blockIO: str(row.BlockIO ?? row.block_io),
|
|
903
|
+
pids: num(row.PIDs ?? row.pids ?? row.PIDS)
|
|
904
|
+
};
|
|
905
|
+
}
|