38 lines
1.2 KiB
TypeScript
38 lines
1.2 KiB
TypeScript
import { execFile } from "node:child_process";
|
|
import { promisify } from "node:util";
|
|
import { ValidationError } from "./util-server";
|
|
|
|
const exec = promisify(execFile);
|
|
const idPattern = /^[0-9a-f]{64}$/;
|
|
|
|
export function containerId(id: unknown): string {
|
|
if (typeof id !== "string" || !idPattern.test(id)) {
|
|
throw new ValidationError("containerInvalidId");
|
|
}
|
|
return id;
|
|
}
|
|
|
|
export function docker(args: string[], timeout = 15000, maxBuffer = 4 * 1024 * 1024) {
|
|
return exec("docker", args, { timeout,
|
|
maxBuffer,
|
|
encoding: "utf8",
|
|
windowsHide: true });
|
|
}
|
|
|
|
interface ContainerRow {
|
|
id: string;
|
|
name: string;
|
|
image: string;
|
|
state: string;
|
|
project: string;
|
|
}
|
|
|
|
const format = "{\"id\":{{json .ID}},\"name\":{{json .Names}},\"image\":{{json .Image}},\"state\":{{json .State}},\"project\":{{json (.Label \"com.docker.compose.project\")}}}";
|
|
|
|
export class ContainerManagement {
|
|
async list(): Promise<ContainerRow[]> {
|
|
const { stdout } = await docker([ "container", "ls", "--all", "--no-trunc", "--format", format ]);
|
|
return stdout.trim().split(/\r?\n/).filter(Boolean).map(row => JSON.parse(row) as ContainerRow);
|
|
}
|
|
}
|