304 lines
12 KiB
TypeScript
304 lines
12 KiB
TypeScript
import { execFile } from "node:child_process";
|
|
import { promisify } from "node:util";
|
|
import { ValidationError } from "./util-server";
|
|
|
|
const exec = promisify(execFile);
|
|
const imageId = /^sha256:[0-9a-f]{64}$/;
|
|
const volumeName = /^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/;
|
|
const tagName = /^[a-zA-Z0-9][a-zA-Z0-9./:_-]*:[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/;
|
|
|
|
interface ContainerUsage {
|
|
id: string;
|
|
name: string;
|
|
image: string;
|
|
reference: string;
|
|
state: string;
|
|
mounts: Array<{ Type: string; Name?: string; Source: string }> | null;
|
|
}
|
|
|
|
interface Platform {
|
|
os: string;
|
|
architecture: string;
|
|
variant?: string;
|
|
}
|
|
|
|
interface Image {
|
|
id: string;
|
|
tags: string[] | null;
|
|
created: string | null;
|
|
size: number | null;
|
|
os: string;
|
|
arch: string;
|
|
variant?: string;
|
|
descriptor?: { digest: string; mediaType: string; platform?: Platform };
|
|
}
|
|
|
|
interface Volume {
|
|
name: string;
|
|
driver: string;
|
|
created: string | null;
|
|
}
|
|
|
|
type TagStatus = "current" | "updateAvailable" | "unknown";
|
|
|
|
interface Manifest {
|
|
Descriptor?: { digest: string; platform?: Platform };
|
|
SchemaV2Manifest?: { config?: { digest: string } };
|
|
OCIManifest?: { config?: { digest: string } };
|
|
}
|
|
|
|
const containerFields = "{\"id\":{{json .Id}},\"name\":{{json .Name}},\"image\":{{json .Image}},\"reference\":{{json .Config.Image}},\"state\":{{json .State.Status}},\"mounts\":{{json .Mounts}}}";
|
|
const imageFields = "{\"id\":{{json .Id}},\"tags\":{{json (index . \"RepoTags\")}},\"created\":{{json (index . \"Created\")}},\"size\":{{json (index . \"Size\")}},\"os\":{{json (index . \"Os\")}},\"arch\":{{json (index . \"Architecture\")}},\"variant\":{{json (index . \"Variant\")}},\"descriptor\":{{json (index . \"Descriptor\")}}}";
|
|
const volumeFields = "{\"name\":{{json .Name}},\"driver\":{{json .Driver}},\"created\":{{json (index . \"CreatedAt\")}}}";
|
|
|
|
async function docker(args: string[], timeout = 15000, allowMissing = false): Promise<string> {
|
|
try {
|
|
const { stdout } = await exec("docker", args, {
|
|
encoding: "utf8",
|
|
timeout,
|
|
maxBuffer: 8 * 1024 * 1024,
|
|
windowsHide: true,
|
|
});
|
|
return stdout.trim();
|
|
} catch (error) {
|
|
const result = error as { stderr?: string; stdout?: string };
|
|
const messages = lines(result.stderr?.trim() ?? "");
|
|
if (allowMissing && messages.length && messages.every(line => /^Error response from daemon: No such (image|volume):/.test(line))) {
|
|
return result.stdout?.trim() ?? "";
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
function lines(value: string) {
|
|
return value ? value.split(/\r?\n/) : [];
|
|
}
|
|
|
|
async function inspect<T>(kind: string, format: string, ids: string[], allowMissing = false): Promise<T[]> {
|
|
const result: T[] = [];
|
|
// Bound command-line length on hosts with many Docker resources.
|
|
for (let offset = 0; offset < ids.length; offset += 50) {
|
|
const output = await docker([ kind, "inspect", "--format", format, "--", ...ids.slice(offset, offset + 50) ], 15000, allowMissing);
|
|
result.push(...lines(output).map(line => JSON.parse(line) as T));
|
|
}
|
|
return result;
|
|
}
|
|
|
|
async function containers() {
|
|
const ids = lines(await docker([ "container", "ls", "--all", "--quiet", "--no-trunc" ]));
|
|
return inspect<ContainerUsage>("container", containerFields, ids);
|
|
}
|
|
|
|
function displayUsage(container: ContainerUsage) {
|
|
return {
|
|
id: container.id,
|
|
name: container.name.replace(/^\//, ""),
|
|
state: container.state,
|
|
reference: container.reference,
|
|
};
|
|
}
|
|
|
|
function canonicalTag(reference: string) {
|
|
if (reference.includes("@")) {
|
|
return reference;
|
|
}
|
|
const slash = reference.indexOf("/");
|
|
const first = reference.slice(0, slash);
|
|
const tag = reference.lastIndexOf(":") > reference.lastIndexOf("/") ? reference : reference + ":latest";
|
|
if (slash < 0) {
|
|
return "docker.io/library/" + tag;
|
|
}
|
|
if (/^(docker\.io|index\.docker\.io|registry-1\.docker\.io)$/.test(first)) {
|
|
const name = tag.slice(slash + 1);
|
|
return "docker.io/" + (name.includes("/") ? name : "library/" + name);
|
|
}
|
|
if (first === "localhost" || first.includes(".") || first.includes(":")) {
|
|
return tag;
|
|
}
|
|
return "docker.io/" + tag;
|
|
}
|
|
|
|
function usesVolume(container: ContainerUsage, name: string) {
|
|
return container.mounts?.some(mount => mount.Type === "volume" && mount.Name === name);
|
|
}
|
|
|
|
function usesImage(container: ContainerUsage, id: string) {
|
|
return container.image === id || container.mounts?.some(mount => mount.Type === "image" && mount.Source === id);
|
|
}
|
|
|
|
export class DockerResources {
|
|
private imagesRequest?: ReturnType<DockerResources["loadImages"]>;
|
|
private volumesRequest?: ReturnType<DockerResources["loadVolumes"]>;
|
|
private checkingRegistry = false;
|
|
private readonly checks = new Map<string, { status: TagStatus; expires: number }>();
|
|
|
|
listImages() {
|
|
this.imagesRequest ??= this.loadImages().finally(() => {
|
|
this.imagesRequest = undefined;
|
|
});
|
|
return this.imagesRequest;
|
|
}
|
|
|
|
listVolumes() {
|
|
this.volumesRequest ??= this.loadVolumes().finally(() => {
|
|
this.volumesRequest = undefined;
|
|
});
|
|
return this.volumesRequest;
|
|
}
|
|
|
|
private async loadImages() {
|
|
const [ usage, tagged, dangling ] = await Promise.all([
|
|
containers(),
|
|
docker([ "image", "ls", "--quiet", "--no-trunc" ]),
|
|
docker([ "image", "ls", "--quiet", "--no-trunc", "--filter", "dangling=true" ]),
|
|
]);
|
|
const ids = Array.from(new Set([ ...lines(tagged), ...lines(dangling), ...usage.map(container => container.image) ]));
|
|
const images = await inspect<Image>("image", imageFields, ids, true);
|
|
const inspected = new Set(images.map(image => image.id));
|
|
// Containerd may keep the content of an untagged image only through its container.
|
|
for (const id of new Set(usage.map(container => container.image))) {
|
|
if (imageId.test(id) && !inspected.has(id)) {
|
|
images.push({ id,
|
|
tags: [],
|
|
created: null,
|
|
size: null,
|
|
os: "",
|
|
arch: "" });
|
|
}
|
|
}
|
|
const imagesByTag = new Map(images.flatMap(image => (image.tags ?? []).map(tag => [ canonicalTag(tag), image.id ] as const)));
|
|
return images.map(image => ({
|
|
id: image.id,
|
|
tags: image.tags ?? [],
|
|
created: image.created,
|
|
size: image.size,
|
|
referenceOnly: !inspected.has(image.id),
|
|
platform: [ image.os, image.arch, image.variant ].filter(Boolean).join("/"),
|
|
checks: Object.fromEntries((image.tags ?? []).flatMap(tag => {
|
|
const check = this.checks.get(image.id + " " + tag);
|
|
return check && check.expires > Date.now() ? [[ tag, check.status ]] : [];
|
|
})),
|
|
containers: usage.filter(container => usesImage(container, image.id)).map(container => {
|
|
const current = imagesByTag.get(canonicalTag(container.reference));
|
|
return {
|
|
...displayUsage(container),
|
|
differentTagImage: Boolean(current && current !== container.image),
|
|
};
|
|
}),
|
|
}));
|
|
}
|
|
|
|
private async loadVolumes() {
|
|
const [ usage, listed ] = await Promise.all([ containers(), docker([ "volume", "ls", "--quiet" ]) ]);
|
|
const volumes = await inspect<Volume>("volume", volumeFields, lines(listed), true);
|
|
return volumes.map(volume => ({
|
|
...volume,
|
|
containers: usage.filter(container => usesVolume(container, volume.name)).map(displayUsage),
|
|
}));
|
|
}
|
|
|
|
/** Compare the selected tag for this platform without pulling layers. */
|
|
async checkImage(id: unknown, tag: unknown) {
|
|
const image = await this.getTaggedImage(id, tag);
|
|
if (this.checkingRegistry) {
|
|
throw new ValidationError("resourceRegistryBusy");
|
|
}
|
|
this.checkingRegistry = true;
|
|
try {
|
|
const status = await this.compareTag(image, String(tag));
|
|
const key = image.id + " " + tag;
|
|
this.checks.delete(key);
|
|
this.checks.set(key, { status,
|
|
expires: Date.now() + 15 * 60 * 1000 });
|
|
if (this.checks.size > 512) {
|
|
const oldest = this.checks.keys().next().value;
|
|
if (oldest) {
|
|
this.checks.delete(oldest);
|
|
}
|
|
}
|
|
return status;
|
|
} finally {
|
|
this.checkingRegistry = false;
|
|
}
|
|
}
|
|
|
|
private async compareTag(image: Image, tag: string): Promise<TagStatus> {
|
|
try {
|
|
const platform = image.descriptor?.platform ?? {
|
|
os: image.os,
|
|
architecture: image.arch,
|
|
variant: image.variant,
|
|
};
|
|
let local = image.id;
|
|
if (/index|manifest\.list/.test(image.descriptor?.mediaType ?? "")) {
|
|
const format = [ platform.os, platform.architecture, platform.variant ].filter(Boolean).join("/");
|
|
local = await docker([ "image", "inspect", "--platform", format, "--format", "{{.Id}}", "--", image.id ]);
|
|
}
|
|
|
|
const raw = await docker([ "manifest", "inspect", "--verbose", "--", tag ], 45000);
|
|
const parsed = JSON.parse(raw) as Manifest | Manifest[];
|
|
const matches = (Array.isArray(parsed) ? parsed : [ parsed ]).filter(entry => {
|
|
const remote = entry.Descriptor?.platform;
|
|
return remote?.os === platform.os && remote.architecture === platform.architecture
|
|
&& (!platform.variant || !remote.variant || platform.variant === remote.variant);
|
|
});
|
|
if (matches.length !== 1) {
|
|
return "unknown";
|
|
}
|
|
const match = matches[0];
|
|
const digest = match.Descriptor?.digest;
|
|
const config = (match.OCIManifest ?? match.SchemaV2Manifest)?.config?.digest;
|
|
if (!digest || !imageId.test(digest) || !imageId.test(local)) {
|
|
return "unknown";
|
|
}
|
|
return local === digest || local === config ? "current" : "updateAvailable";
|
|
} catch {
|
|
return "unknown";
|
|
}
|
|
}
|
|
|
|
async removeImage(id: unknown, tag: unknown) {
|
|
if (typeof id !== "string" || !imageId.test(id) || typeof tag !== "string") {
|
|
throw new ValidationError("resourceInvalidSelection");
|
|
}
|
|
if ((await containers()).some(container => usesImage(container, id))) {
|
|
throw new ValidationError("resourceInUse");
|
|
}
|
|
if (tag) {
|
|
await this.getTaggedImage(id, tag);
|
|
} else {
|
|
const [ image ] = await inspect<Image>("image", imageFields, [ id ]);
|
|
if (image.tags?.length) {
|
|
throw new ValidationError("resourceChanged");
|
|
}
|
|
}
|
|
// Docker performs its own usage check as part of the removal.
|
|
await docker([ "image", "rm", "--no-prune", "--", tag || id ]);
|
|
}
|
|
|
|
async removeVolume(name: unknown, created: unknown) {
|
|
if (typeof name !== "string" || !volumeName.test(name) || (typeof created !== "string" && created !== null)) {
|
|
throw new ValidationError("resourceInvalidSelection");
|
|
}
|
|
const [ volume ] = await inspect<Volume>("volume", volumeFields, [ name ]);
|
|
if (volume.created !== created) {
|
|
throw new ValidationError("resourceChanged");
|
|
}
|
|
if ((await containers()).some(container => usesVolume(container, name))) {
|
|
throw new ValidationError("resourceInUse");
|
|
}
|
|
await docker([ "volume", "rm", "--", name ]);
|
|
}
|
|
|
|
private async getTaggedImage(id: unknown, tag: unknown) {
|
|
if (typeof id !== "string" || !imageId.test(id) || typeof tag !== "string" || !tagName.test(tag) || tag.length > 512) {
|
|
throw new ValidationError("resourceInvalidSelection");
|
|
}
|
|
const [ image ] = await inspect<Image>("image", imageFields, [ tag ]);
|
|
if (image.id !== id || !image.tags?.includes(tag)) {
|
|
throw new ValidationError("resourceChanged");
|
|
}
|
|
return image;
|
|
}
|
|
}
|