feat!: release v2 (#6545)
Co-authored-by: Artur <145776561+arturict@users.noreply.github.com> Co-authored-by: arturict <arturict@users.noreply.github.com> Co-authored-by: Thomas <thomas@ajnart.fr> Co-authored-by: Afonso Jorge Ramos <afonsojorgeramos@gmail.com> Co-authored-by: Danura30082 <danura30082+github@gmail.com> Co-authored-by: Kushie <122986913+kushiemoon-dev@users.noreply.github.com> Co-authored-by: ajnart <thomas@ajnart.fr> Co-authored-by: ajnart <thomas@ajnart.dev> Co-authored-by: chenjun <chenjun@foxmail.com> Co-authored-by: Wikibear <wikibear@users.noreply.github.com> Co-authored-by: Bergasha <bergasha@gmail.com> Co-authored-by: leafyelin <43306196+leafyelin@users.noreply.github.com> Co-authored-by: Lucas Araujo <lucas.lra@gmail.com> Co-authored-by: GreenMonito <86085570+GreenMonito@users.noreply.github.com> Co-authored-by: Nerdy-Technician <roffo@nerdy-technician.social> Co-authored-by: Jun <34545896+jcstrong@users.noreply.github.com> Co-authored-by: Edmond Abraham <54119952+gitedmond@users.noreply.github.com> Co-authored-by: thrawnx <tight.bulb9384@fastmail.com> Co-authored-by: Chris <58918656+nordada@users.noreply.github.com> Co-authored-by: yi111 <153097222+Yi-111-a@users.noreply.github.com> Co-authored-by: Yanis <naamaneyanis@gmail.com> Co-authored-by: Wikibear <me@sej.de> Co-authored-by: alessiottavo <93441886+alessiottavo@users.noreply.github.com>
This commit is contained in:
3286 files changed
+284386
-139176
No files matched your search
@@ -0,0 +1,3 @@
|
||||
export { listDiscoveredContainersAsync } from "./list-discovered-containers";
|
||||
export { createDockerSourceId, parseContainerLabels, type ParseContainerLabelsOptions } from "./parse-container-labels";
|
||||
export type { DiscoveredService, DockerDiscoveryHostResult, DockerDiscoveryResult } from "./types";
|
||||
@@ -0,0 +1,89 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const listContainersA = vi.fn();
|
||||
const listContainersB = vi.fn();
|
||||
|
||||
vi.mock("../singleton", () => ({
|
||||
DockerSingleton: {
|
||||
getInstances: () => [
|
||||
{ host: "good", instance: { listContainers: listContainersA } },
|
||||
{ host: "bad", instance: { listContainers: listContainersB } },
|
||||
],
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@homarr/core/infrastructure/logs", () => ({
|
||||
createLogger: () => ({ warn: vi.fn() }),
|
||||
}));
|
||||
|
||||
import { listDiscoveredContainersAsync } from "./list-discovered-containers";
|
||||
|
||||
describe("listDiscoveredContainersAsync", () => {
|
||||
beforeEach(() => {
|
||||
listContainersA.mockReset();
|
||||
listContainersB.mockReset();
|
||||
});
|
||||
|
||||
it("preserves successful hosts when another Docker host fails", async () => {
|
||||
listContainersA.mockResolvedValue([
|
||||
{
|
||||
Id: "sonarr",
|
||||
Labels: {
|
||||
"homarr.name": "Sonarr",
|
||||
"homarr.group": "Media",
|
||||
"homarr.href": "http://sonarr:8989",
|
||||
},
|
||||
},
|
||||
]);
|
||||
listContainersB.mockRejectedValue(new Error("permission denied"));
|
||||
|
||||
const result = await listDiscoveredContainersAsync();
|
||||
|
||||
expect(result.services).toHaveLength(1);
|
||||
expect(result.hosts).toEqual([
|
||||
expect.objectContaining({ host: "good", status: "success" }),
|
||||
{
|
||||
host: "bad",
|
||||
status: "unavailable",
|
||||
reason: "permission denied",
|
||||
containers: [],
|
||||
services: [],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("times out a blackholed host without losing another host's result", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
let blackholedSignal: AbortSignal | undefined;
|
||||
listContainersA.mockResolvedValue([
|
||||
{
|
||||
Id: "sonarr",
|
||||
Labels: {
|
||||
"homarr.name": "Sonarr",
|
||||
"homarr.group": "Media",
|
||||
"homarr.href": "http://sonarr:8989",
|
||||
},
|
||||
},
|
||||
]);
|
||||
listContainersB.mockImplementation(({ abortSignal }: { abortSignal: AbortSignal }) => {
|
||||
blackholedSignal = abortSignal;
|
||||
return new Promise(() => undefined);
|
||||
});
|
||||
|
||||
const resultPromise = listDiscoveredContainersAsync({}, 25);
|
||||
await vi.advanceTimersByTimeAsync(25);
|
||||
const result = await resultPromise;
|
||||
|
||||
expect(result.services).toHaveLength(1);
|
||||
expect(result.hosts).toEqual([
|
||||
expect.objectContaining({ host: "good", status: "success" }),
|
||||
expect.objectContaining({ host: "bad", status: "unavailable", reason: "Docker discovery timed out for bad" }),
|
||||
]);
|
||||
expect(blackholedSignal?.aborted).toBe(true);
|
||||
expect(listContainersB).toHaveBeenCalledWith({ all: false, abortSignal: blackholedSignal });
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import { ErrorWithMetadata } from "@homarr/core/infrastructure/logs/error";
|
||||
|
||||
import { DockerSingleton } from "../singleton";
|
||||
import type { ParseContainerLabelsOptions } from "./parse-container-labels";
|
||||
import { parseContainerLabels } from "./parse-container-labels";
|
||||
import type { DockerDiscoveryHostResult, DockerDiscoveryResult } from "./types";
|
||||
|
||||
const logger = createLogger({ module: "dockerDiscovery" });
|
||||
export const dockerDiscoveryHostTimeoutMs = 5_000;
|
||||
|
||||
const reasonFromError = (error: unknown) => {
|
||||
if (error instanceof Error && error.message.trim()) return error.message;
|
||||
return "Docker is not reachable";
|
||||
};
|
||||
|
||||
export const listDiscoveredContainersAsync = async (
|
||||
options: ParseContainerLabelsOptions = {},
|
||||
timeoutMs = dockerDiscoveryHostTimeoutMs,
|
||||
): Promise<DockerDiscoveryResult> => {
|
||||
const dockerInstances = DockerSingleton.getInstances();
|
||||
const settled = await Promise.allSettled(
|
||||
dockerInstances.map(async ({ instance, host }): Promise<DockerDiscoveryHostResult> => {
|
||||
const controller = new AbortController();
|
||||
const timeoutError = new Error(`Docker discovery timed out for ${host}`);
|
||||
let timeout: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
const containers = await Promise.race([
|
||||
instance.listContainers({ all: false, abortSignal: controller.signal }),
|
||||
new Promise<never>((_, reject) => {
|
||||
timeout = setTimeout(() => {
|
||||
controller.abort(timeoutError);
|
||||
reject(timeoutError);
|
||||
}, timeoutMs);
|
||||
}),
|
||||
]);
|
||||
const services = containers
|
||||
.map((container) => parseContainerLabels(container, host, options))
|
||||
.filter((service) => service !== null);
|
||||
return { host, status: "success", containers, services };
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted) throw timeoutError;
|
||||
throw error;
|
||||
} finally {
|
||||
if (timeout) clearTimeout(timeout);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
const hosts = settled.map<DockerDiscoveryHostResult>((result, index) => {
|
||||
const host = dockerInstances[index]?.host ?? "unknown";
|
||||
if (result.status === "fulfilled") return result.value;
|
||||
|
||||
logger.warn(new ErrorWithMetadata("Failed to list containers for discovery", { host }, { cause: result.reason }));
|
||||
return {
|
||||
host,
|
||||
status: "unavailable",
|
||||
reason: reasonFromError(result.reason),
|
||||
containers: [],
|
||||
services: [],
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
hosts,
|
||||
services: hosts.flatMap((result) => result.services),
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,152 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseContainerLabels } from "./parse-container-labels";
|
||||
|
||||
const container = (Labels: Record<string, string>, Id = "container-1") => ({ Id, Labels });
|
||||
|
||||
describe("parseContainerLabels", () => {
|
||||
it("parses complete Homarr labels", () => {
|
||||
expect(
|
||||
parseContainerLabels(
|
||||
container({
|
||||
"homarr.name": "Sonarr",
|
||||
"homarr.group": "Media",
|
||||
"homarr.href": "http://sonarr:8989",
|
||||
"homarr.icon": "sonarr.svg",
|
||||
"homarr.description": "TV",
|
||||
"homarr.ping": "http://sonarr:8989/ping",
|
||||
"homarr.id": "sonarr-main",
|
||||
"homarr.board": "dashboard",
|
||||
"homarr.integration": "sonarr",
|
||||
"homarr.widget": "calendar",
|
||||
}),
|
||||
"socket",
|
||||
),
|
||||
).toEqual({
|
||||
sourceId: "docker:socket:sonarr-main",
|
||||
containerId: "container-1",
|
||||
host: "socket",
|
||||
group: "Media",
|
||||
name: "Sonarr",
|
||||
href: "http://sonarr:8989",
|
||||
icon: "sonarr.svg",
|
||||
description: "TV",
|
||||
pingUrl: "http://sonarr:8989/ping",
|
||||
externalId: "sonarr-main",
|
||||
boardName: "dashboard",
|
||||
integrationKind: "sonarr",
|
||||
widgetKind: "calendar",
|
||||
});
|
||||
});
|
||||
|
||||
it("supports Homepage labels when Homarr labels are absent", () => {
|
||||
expect(
|
||||
parseContainerLabels(
|
||||
container({
|
||||
"homepage.name": "Jellyfin",
|
||||
"homepage.group": "Media",
|
||||
"homepage.href": "http://jellyfin:8096",
|
||||
"homepage.icon": "jellyfin.svg",
|
||||
}),
|
||||
"remote:2375",
|
||||
),
|
||||
).toMatchObject({
|
||||
sourceId: "docker:remote%3A2375:container-1",
|
||||
name: "Jellyfin",
|
||||
group: "Media",
|
||||
href: "http://jellyfin:8096",
|
||||
icon: "jellyfin.svg",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps host and service identifiers unambiguous", () => {
|
||||
const first = parseContainerLabels(
|
||||
container({ "homarr.name": "Service", "homarr.href": "http://service", "homarr.id": "service" }),
|
||||
"remote:2375",
|
||||
);
|
||||
const second = parseContainerLabels(
|
||||
container({ "homarr.name": "Service", "homarr.href": "http://service", "homarr.id": "2375:service" }),
|
||||
"remote",
|
||||
);
|
||||
|
||||
expect(first?.sourceId).toBe("docker:remote%3A2375:service");
|
||||
expect(second?.sourceId).toBe("docker:remote:2375%3Aservice");
|
||||
expect(first?.sourceId).not.toBe(second?.sourceId);
|
||||
});
|
||||
|
||||
it("keeps a labeled service without a group for root placement", () => {
|
||||
expect(
|
||||
parseContainerLabels(
|
||||
container({
|
||||
"homarr.name": "Status",
|
||||
"homarr.href": "http://status:3001",
|
||||
"homarr.widget": "clock",
|
||||
}),
|
||||
"socket",
|
||||
),
|
||||
).toMatchObject({ name: "Status", href: "http://status:3001", group: undefined, widgetKind: "clock" });
|
||||
});
|
||||
|
||||
it("does not mix Homepage required fields into an explicitly Homarr-labeled service", () => {
|
||||
expect(
|
||||
parseContainerLabels(
|
||||
container({
|
||||
"homarr.name": "Sonarr",
|
||||
"homepage.group": "Media",
|
||||
"homepage.href": "http://sonarr:8989",
|
||||
}),
|
||||
"socket",
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("can disable Homepage fallback", () => {
|
||||
expect(
|
||||
parseContainerLabels(
|
||||
container({
|
||||
"homepage.name": "Sonarr",
|
||||
"homepage.group": "Media",
|
||||
"homepage.href": "http://sonarr:8989",
|
||||
}),
|
||||
"socket",
|
||||
{ readHomepageLabels: false },
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores hidden and incomplete containers", () => {
|
||||
expect(
|
||||
parseContainerLabels(
|
||||
container({
|
||||
"homarr.hide": "true",
|
||||
"homarr.name": "Sonarr",
|
||||
"homarr.group": "Media",
|
||||
"homarr.href": "http://sonarr:8989",
|
||||
}),
|
||||
"socket",
|
||||
),
|
||||
).toBeNull();
|
||||
expect(parseContainerLabels(container({ "homarr.name": "Sonarr" }), "socket")).toBeNull();
|
||||
});
|
||||
|
||||
it("trims values and ignores invalid integration and widget kinds", () => {
|
||||
expect(
|
||||
parseContainerLabels(
|
||||
container({
|
||||
"homarr.name": " Sonarr ",
|
||||
"homarr.group": " Media ",
|
||||
"homarr.href": " http://sonarr:8989 ",
|
||||
"homarr.integration": "not-real",
|
||||
"homarr.widget": "not-real",
|
||||
}),
|
||||
"socket",
|
||||
),
|
||||
).toMatchObject({
|
||||
name: "Sonarr",
|
||||
group: "Media",
|
||||
href: "http://sonarr:8989",
|
||||
integrationKind: undefined,
|
||||
widgetKind: undefined,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import type { ContainerInfo } from "dockerode";
|
||||
|
||||
import { integrationKinds, widgetKinds } from "@homarr/definitions";
|
||||
import type { IntegrationKind, WidgetKind } from "@homarr/definitions";
|
||||
|
||||
import { dockerLabels, homepageLabels } from "../labels";
|
||||
import type { DiscoveredService } from "./types";
|
||||
|
||||
export interface ParseContainerLabelsOptions {
|
||||
readHomepageLabels?: boolean;
|
||||
}
|
||||
|
||||
const integrationKindSet = new Set<string>(integrationKinds);
|
||||
const widgetKindSet = new Set<string>(widgetKinds);
|
||||
|
||||
const readLabel = (labels: Record<string, string>, key: string) => {
|
||||
const value = labels[key]?.trim();
|
||||
return value ? value : undefined;
|
||||
};
|
||||
|
||||
const resolveLabelValue = (
|
||||
labels: Record<string, string>,
|
||||
homarrKey: string,
|
||||
homepageKey: string,
|
||||
useHomepageFallback: boolean,
|
||||
) => readLabel(labels, homarrKey) ?? (useHomepageFallback ? readLabel(labels, homepageKey) : undefined);
|
||||
|
||||
const parseIntegrationKind = (value: string | undefined): IntegrationKind | undefined =>
|
||||
value && integrationKindSet.has(value) ? (value as IntegrationKind) : undefined;
|
||||
|
||||
const parseWidgetKind = (value: string | undefined): WidgetKind | undefined =>
|
||||
value && widgetKindSet.has(value) ? (value as WidgetKind) : undefined;
|
||||
|
||||
export const createDockerSourceId = (host: string, externalId: string) =>
|
||||
`docker:${encodeURIComponent(host)}:${encodeURIComponent(externalId)}`;
|
||||
|
||||
export const parseContainerLabels = (
|
||||
container: Pick<ContainerInfo, "Id" | "Labels">,
|
||||
host: string,
|
||||
options: ParseContainerLabelsOptions = {},
|
||||
): DiscoveredService | null => {
|
||||
const labels = container.Labels ?? {};
|
||||
if (dockerLabels.hide in labels) return null;
|
||||
|
||||
const readHomepageLabels = options.readHomepageLabels ?? true;
|
||||
const useHomepageFallback = readHomepageLabels && !readLabel(labels, dockerLabels.name);
|
||||
const name = resolveLabelValue(labels, dockerLabels.name, homepageLabels.name, useHomepageFallback);
|
||||
const href = resolveLabelValue(labels, dockerLabels.href, homepageLabels.href, useHomepageFallback);
|
||||
const group = resolveLabelValue(labels, dockerLabels.group, homepageLabels.group, useHomepageFallback);
|
||||
if (!name || !href) return null;
|
||||
|
||||
const externalId = readLabel(labels, dockerLabels.id) ?? container.Id;
|
||||
return {
|
||||
sourceId: createDockerSourceId(host, externalId),
|
||||
containerId: container.Id,
|
||||
host,
|
||||
group,
|
||||
name,
|
||||
href,
|
||||
icon: resolveLabelValue(labels, dockerLabels.icon, homepageLabels.icon, useHomepageFallback),
|
||||
description: resolveLabelValue(labels, dockerLabels.description, homepageLabels.description, useHomepageFallback),
|
||||
pingUrl: readLabel(labels, dockerLabels.ping),
|
||||
externalId,
|
||||
boardName: readLabel(labels, dockerLabels.board),
|
||||
integrationKind: parseIntegrationKind(readLabel(labels, dockerLabels.integration)),
|
||||
widgetKind: parseWidgetKind(readLabel(labels, dockerLabels.widget)),
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { ContainerInfo } from "dockerode";
|
||||
|
||||
import type { IntegrationKind, WidgetKind } from "@homarr/definitions";
|
||||
|
||||
export interface DiscoveredService {
|
||||
sourceId: string;
|
||||
containerId: string;
|
||||
host: string;
|
||||
group?: string;
|
||||
name: string;
|
||||
href: string;
|
||||
icon?: string;
|
||||
description?: string;
|
||||
pingUrl?: string;
|
||||
externalId: string;
|
||||
boardName?: string;
|
||||
integrationKind?: IntegrationKind;
|
||||
widgetKind?: WidgetKind;
|
||||
}
|
||||
|
||||
export type DockerDiscoveryHostResult =
|
||||
| {
|
||||
host: string;
|
||||
status: "success";
|
||||
containers: ContainerInfo[];
|
||||
services: DiscoveredService[];
|
||||
}
|
||||
| {
|
||||
host: string;
|
||||
status: "unavailable";
|
||||
reason: string;
|
||||
containers: [];
|
||||
services: [];
|
||||
};
|
||||
|
||||
export interface DockerDiscoveryResult {
|
||||
hosts: DockerDiscoveryHostResult[];
|
||||
services: DiscoveredService[];
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import { isRecord } from "@homarr/common";
|
||||
|
||||
export const dockerEndpointCapabilities = ["inventory", "logs", "lifecycle", "remove"] as const;
|
||||
export type DockerEndpointCapability = (typeof dockerEndpointCapabilities)[number];
|
||||
|
||||
export type DockerEndpointTransport =
|
||||
| { type: "socket"; path: string }
|
||||
| { type: "tcp"; host: string; port: number; allowInsecure: true }
|
||||
| {
|
||||
type: "tls";
|
||||
host: string;
|
||||
port: number;
|
||||
caPath: string;
|
||||
certPath?: string;
|
||||
keyPath?: string;
|
||||
};
|
||||
|
||||
export interface DockerEndpointDescriptor {
|
||||
id: string;
|
||||
name: string;
|
||||
kind: "docker" | "podman";
|
||||
transport: DockerEndpointTransport;
|
||||
capabilities: DockerEndpointCapability[];
|
||||
scope: "admin";
|
||||
source: "environment" | "legacy" | "default";
|
||||
}
|
||||
|
||||
const allCapabilities = [...dockerEndpointCapabilities];
|
||||
|
||||
export const parseDockerEndpointDescriptors = (value: string): DockerEndpointDescriptor[] => {
|
||||
let input: unknown;
|
||||
try {
|
||||
input = JSON.parse(value);
|
||||
} catch (error) {
|
||||
throw new Error("DOCKER_ENDPOINTS must be valid JSON", { cause: error });
|
||||
}
|
||||
if (!Array.isArray(input) || input.length === 0) {
|
||||
throw new Error("DOCKER_ENDPOINTS must be a non-empty JSON array");
|
||||
}
|
||||
|
||||
const descriptors = input.map((entry, index) => parseDescriptor(entry, index));
|
||||
const ids = new Set(descriptors.map(({ id }) => id));
|
||||
if (ids.size !== descriptors.length) throw new Error("DOCKER_ENDPOINTS ids must be unique");
|
||||
return descriptors;
|
||||
};
|
||||
|
||||
const parseDescriptor = (value: unknown, index: number): DockerEndpointDescriptor => {
|
||||
const entry = getRecord(value, `DOCKER_ENDPOINTS[${index}]`);
|
||||
const id = getNonEmptyString(entry.id, `DOCKER_ENDPOINTS[${index}].id`);
|
||||
const name = getNonEmptyString(entry.name, `DOCKER_ENDPOINTS[${index}].name`);
|
||||
const kind =
|
||||
entry.kind === "podman" ? "podman" : entry.kind === "docker" || entry.kind === undefined ? "docker" : null;
|
||||
if (!kind) throw new Error(`DOCKER_ENDPOINTS[${index}].kind must be docker or podman`);
|
||||
const transport = parseTransport(entry.transport, index);
|
||||
const capabilities = parseCapabilities(entry.capabilities, index);
|
||||
|
||||
return { id, name, kind, transport, capabilities, scope: "admin", source: "environment" };
|
||||
};
|
||||
|
||||
const parseTransport = (value: unknown, index: number): DockerEndpointTransport => {
|
||||
const transport = getRecord(value, `DOCKER_ENDPOINTS[${index}].transport`);
|
||||
if (transport.type === "socket") {
|
||||
return { type: "socket", path: getAbsolutePath(transport.path, `DOCKER_ENDPOINTS[${index}].transport.path`) };
|
||||
}
|
||||
if (transport.type === "tcp") {
|
||||
if (transport.allowInsecure !== true) {
|
||||
throw new Error(`DOCKER_ENDPOINTS[${index}] plaintext TCP requires allowInsecure: true`);
|
||||
}
|
||||
return {
|
||||
type: "tcp",
|
||||
host: getNonEmptyString(transport.host, `DOCKER_ENDPOINTS[${index}].transport.host`),
|
||||
port: getPort(transport.port, index),
|
||||
allowInsecure: true,
|
||||
};
|
||||
}
|
||||
if (transport.type === "tls") {
|
||||
const certPath = getOptionalAbsolutePath(transport.certPath, `DOCKER_ENDPOINTS[${index}].transport.certPath`);
|
||||
const keyPath = getOptionalAbsolutePath(transport.keyPath, `DOCKER_ENDPOINTS[${index}].transport.keyPath`);
|
||||
if (Boolean(certPath) !== Boolean(keyPath)) {
|
||||
throw new Error(`DOCKER_ENDPOINTS[${index}] TLS certPath and keyPath must be provided together`);
|
||||
}
|
||||
return {
|
||||
type: "tls",
|
||||
host: getNonEmptyString(transport.host, `DOCKER_ENDPOINTS[${index}].transport.host`),
|
||||
port: getPort(transport.port, index),
|
||||
caPath: getAbsolutePath(transport.caPath, `DOCKER_ENDPOINTS[${index}].transport.caPath`),
|
||||
...(certPath && keyPath ? { certPath, keyPath } : {}),
|
||||
};
|
||||
}
|
||||
throw new Error(`DOCKER_ENDPOINTS[${index}].transport.type must be socket, tcp, or tls`);
|
||||
};
|
||||
|
||||
const parseCapabilities = (value: unknown, index: number): DockerEndpointCapability[] => {
|
||||
if (value === undefined) return [...allCapabilities];
|
||||
if (!Array.isArray(value) || value.some((capability) => !dockerEndpointCapabilities.includes(capability))) {
|
||||
throw new Error(`DOCKER_ENDPOINTS[${index}].capabilities contains an unsupported capability`);
|
||||
}
|
||||
const capabilities = [...new Set(value)] as DockerEndpointCapability[];
|
||||
if (!capabilities.includes("inventory")) {
|
||||
throw new Error(`DOCKER_ENDPOINTS[${index}].capabilities must include inventory`);
|
||||
}
|
||||
return capabilities;
|
||||
};
|
||||
|
||||
const getRecord = (value: unknown, path: string): Record<string, unknown> => {
|
||||
if (!isRecord(value)) throw new Error(`${path} must be an object`);
|
||||
return value;
|
||||
};
|
||||
|
||||
const getNonEmptyString = (value: unknown, path: string) => {
|
||||
if (typeof value !== "string" || value.trim().length === 0) throw new Error(`${path} must be a non-empty string`);
|
||||
return value.trim();
|
||||
};
|
||||
|
||||
const getAbsolutePath = (value: unknown, path: string) => {
|
||||
const result = getNonEmptyString(value, path);
|
||||
if (!result.startsWith("/")) throw new Error(`${path} must be an absolute path`);
|
||||
return result;
|
||||
};
|
||||
|
||||
const getOptionalAbsolutePath = (value: unknown, path: string) =>
|
||||
value === undefined ? undefined : getAbsolutePath(value, path);
|
||||
|
||||
const getPort = (value: unknown, index: number) => {
|
||||
if (!Number.isInteger(value) || Number(value) < 1 || Number(value) > 65_535) {
|
||||
throw new Error(`DOCKER_ENDPOINTS[${index}].transport.port must be an integer from 1 to 65535`);
|
||||
}
|
||||
return Number(value);
|
||||
};
|
||||
|
||||
export const getDockerEndpointHost = (descriptor: DockerEndpointDescriptor) =>
|
||||
descriptor.transport.type === "socket"
|
||||
? descriptor.transport.path
|
||||
: `${descriptor.transport.host}:${descriptor.transport.port}`;
|
||||
|
||||
export const createLegacySocketDescriptor = (path: string): DockerEndpointDescriptor => ({
|
||||
id: `socket:${path}`,
|
||||
name: path,
|
||||
kind: path.toLowerCase().includes("podman") ? "podman" : "docker",
|
||||
transport: { type: "socket", path },
|
||||
capabilities: [...allCapabilities],
|
||||
scope: "admin",
|
||||
source: "legacy",
|
||||
});
|
||||
|
||||
export const createLegacyTcpDescriptor = (host: string, port: number): DockerEndpointDescriptor => ({
|
||||
id: `tcp:${host}:${port}`,
|
||||
name: `${host}:${port}`,
|
||||
kind: "docker",
|
||||
transport: { type: "tcp", host, port, allowInsecure: true },
|
||||
capabilities: [...allCapabilities],
|
||||
scope: "admin",
|
||||
source: "legacy",
|
||||
});
|
||||
@@ -9,6 +9,8 @@ export const env = createEnv({
|
||||
DOCKER_PORTS: z.string().optional(),
|
||||
// Comma separated paths to Docker-compatible Unix sockets (e.g., /var/run/docker.sock,/run/user/1000/podman/podman.sock)
|
||||
DOCKER_SOCKET_PATHS: z.string().optional(),
|
||||
// JSON descriptors for friendly names, TLS, Podman identity, and per-endpoint capabilities.
|
||||
DOCKER_ENDPOINTS: z.string().optional(),
|
||||
ENABLE_DOCKER: createBooleanSchema(true),
|
||||
ENABLE_KUBERNETES: createBooleanSchema(false),
|
||||
},
|
||||
|
||||
@@ -1,11 +1,31 @@
|
||||
import type Docker from "dockerode";
|
||||
import type { DockerEndpointCapability } from "./endpoint-descriptor";
|
||||
|
||||
export type { DockerInstance } from "./singleton";
|
||||
export type { DockerEndpointInitializationFailure, DockerInstance } from "./singleton";
|
||||
export { DockerSingleton } from "./singleton";
|
||||
export * from "./endpoint-descriptor";
|
||||
export type { ContainerInfo, Container, Port } from "dockerode";
|
||||
export type { Docker };
|
||||
|
||||
export const containerStates = ["created", "running", "paused", "restarting", "exited", "removing", "dead"] as const;
|
||||
|
||||
export type ContainerState = (typeof containerStates)[number];
|
||||
|
||||
export interface DockerContainerTarget {
|
||||
endpointId: string;
|
||||
id: string;
|
||||
}
|
||||
|
||||
export interface DockerEndpointStatus {
|
||||
id: string;
|
||||
name: string;
|
||||
status: "available" | "degraded" | "unavailable";
|
||||
kind?: "docker" | "podman";
|
||||
transport?: "socket" | "tcp" | "tls";
|
||||
capabilities?: DockerEndpointCapability[];
|
||||
source?: "environment" | "legacy" | "default";
|
||||
scope?: "admin";
|
||||
}
|
||||
|
||||
export * from "./labels";
|
||||
export * from "./discovery";
|
||||
@@ -1,4 +1,21 @@
|
||||
export const dockerLabels = {
|
||||
// Label to hide a container from Homarrs docker integration
|
||||
hide: "homarr.hide",
|
||||
group: "homarr.group",
|
||||
name: "homarr.name",
|
||||
href: "homarr.href",
|
||||
icon: "homarr.icon",
|
||||
description: "homarr.description",
|
||||
ping: "homarr.ping",
|
||||
id: "homarr.id",
|
||||
board: "homarr.board",
|
||||
integration: "homarr.integration",
|
||||
widget: "homarr.widget",
|
||||
} as const;
|
||||
|
||||
export const homepageLabels = {
|
||||
group: "homepage.group",
|
||||
name: "homepage.name",
|
||||
href: "homepage.href",
|
||||
icon: "homepage.icon",
|
||||
description: "homepage.description",
|
||||
} as const;
|
||||
@@ -13,11 +13,11 @@ export const containerStateColorMap = {
|
||||
} satisfies Record<ContainerState, MantineColor>;
|
||||
|
||||
export const memoryUsageColor = (number: number, state: string): MantineColor => {
|
||||
const mbUsage = number / 1024 / 1024;
|
||||
if (mbUsage === 0 && state !== "running") return "red";
|
||||
if (mbUsage < 128) return "green";
|
||||
if (mbUsage < 256) return "yellow";
|
||||
if (mbUsage < 512) return "orange";
|
||||
const mebibyteUsage = number / 1024 / 1024;
|
||||
if (mebibyteUsage === 0 && state !== "running") return "red";
|
||||
if (mebibyteUsage < 128) return "green";
|
||||
if (mebibyteUsage < 256) return "yellow";
|
||||
if (mebibyteUsage < 512) return "orange";
|
||||
return "red";
|
||||
};
|
||||
|
||||
|
||||
@@ -1,26 +1,70 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import Docker from "dockerode";
|
||||
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import { ErrorWithMetadata } from "@homarr/core/infrastructure/logs/error";
|
||||
|
||||
import { env } from "./env";
|
||||
import type { DockerEndpointCapability, DockerEndpointDescriptor } from "./endpoint-descriptor";
|
||||
import {
|
||||
createLegacySocketDescriptor,
|
||||
createLegacyTcpDescriptor,
|
||||
getDockerEndpointHost,
|
||||
parseDockerEndpointDescriptors,
|
||||
} from "./endpoint-descriptor";
|
||||
|
||||
export interface DockerInstance {
|
||||
endpointId: string;
|
||||
endpointName: string;
|
||||
host: string;
|
||||
descriptor: DockerEndpointDescriptor;
|
||||
instance: Docker;
|
||||
}
|
||||
|
||||
export interface DockerEndpointInitializationFailure {
|
||||
descriptor: DockerEndpointDescriptor;
|
||||
host: string;
|
||||
}
|
||||
|
||||
const logger = createLogger({ module: "dockerSingleton" });
|
||||
|
||||
export class DockerSingleton {
|
||||
private static instances: DockerInstance[] | null = null;
|
||||
private static initializationFailures: DockerEndpointInitializationFailure[] = [];
|
||||
|
||||
private createInstanceSafely(descriptor: DockerEndpointDescriptor): DockerInstance[] {
|
||||
try {
|
||||
return [createInstance(descriptor)];
|
||||
} catch (error) {
|
||||
const host = getDockerEndpointHost(descriptor);
|
||||
DockerSingleton.initializationFailures.push({ descriptor, host });
|
||||
logger.warn(
|
||||
new ErrorWithMetadata(
|
||||
"Failed to initialize Docker endpoint",
|
||||
{ endpointId: descriptor.id, host },
|
||||
{ cause: error },
|
||||
),
|
||||
);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private createInstances() {
|
||||
if (env.DOCKER_ENDPOINTS) {
|
||||
return parseDockerEndpointDescriptors(env.DOCKER_ENDPOINTS).flatMap((descriptor) =>
|
||||
this.createInstanceSafely(descriptor),
|
||||
);
|
||||
}
|
||||
|
||||
const socketPaths = env.DOCKER_SOCKET_PATHS;
|
||||
const hostVariable = env.DOCKER_HOSTNAMES;
|
||||
const portVariable = env.DOCKER_PORTS;
|
||||
|
||||
// Socket instances from DOCKER_SOCKET_PATHS
|
||||
const socketInstances: DockerInstance[] = socketPaths
|
||||
? socketPaths.split(",").map((socketPath) => ({
|
||||
host: socketPath,
|
||||
instance: new Docker({ socketPath }),
|
||||
}))
|
||||
? socketPaths
|
||||
.split(",")
|
||||
.flatMap((socketPath) => this.createInstanceSafely(createLegacySocketDescriptor(socketPath)))
|
||||
: [];
|
||||
|
||||
// TCP instances from existing DOCKER_HOSTNAMES/DOCKER_PORTS
|
||||
@@ -33,25 +77,34 @@ export class DockerSingleton {
|
||||
throw new Error("The number of hosts and ports must match");
|
||||
}
|
||||
|
||||
tcpInstances = hostnames.map((host, i) => ({
|
||||
host: `${host}:${ports[i]}`,
|
||||
tcpInstances = hostnames.flatMap((host, i) =>
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
instance: new Docker({ host, port: parseInt(ports[i]!, 10) }),
|
||||
}));
|
||||
this.createInstanceSafely(createLegacyTcpDescriptor(host, parseInt(ports[i]!, 10))),
|
||||
);
|
||||
}
|
||||
|
||||
const instances = [...socketInstances, ...tcpInstances];
|
||||
|
||||
// Default: local socket if nothing else configured
|
||||
if (instances.length === 0) {
|
||||
return [{ host: "socket", instance: new Docker() }];
|
||||
const descriptor = {
|
||||
...createLegacySocketDescriptor("/var/run/docker.sock"),
|
||||
id: "socket:default",
|
||||
name: "Local Docker",
|
||||
source: "default" as const,
|
||||
};
|
||||
return [createInstance(descriptor)];
|
||||
}
|
||||
|
||||
return instances;
|
||||
}
|
||||
|
||||
public static findInstance(host: string): DockerInstance | undefined {
|
||||
return this.instances?.find((instance) => instance.host === host);
|
||||
public static findInstance(endpointId: string): DockerInstance | undefined {
|
||||
return this.getInstances().find((instance) => instance.endpointId === endpointId);
|
||||
}
|
||||
|
||||
public static hasCapability(endpointId: string, capability: DockerEndpointCapability): boolean {
|
||||
return this.findInstance(endpointId)?.descriptor.capabilities.includes(capability) ?? false;
|
||||
}
|
||||
|
||||
public static getInstances(): DockerInstance[] {
|
||||
@@ -59,7 +112,41 @@ export class DockerSingleton {
|
||||
return this.instances;
|
||||
}
|
||||
|
||||
this.initializationFailures = [];
|
||||
this.instances = new DockerSingleton().createInstances();
|
||||
return this.instances;
|
||||
}
|
||||
|
||||
public static getInitializationFailures(): DockerEndpointInitializationFailure[] {
|
||||
this.getInstances();
|
||||
return [...this.initializationFailures];
|
||||
}
|
||||
|
||||
public static reset(): void {
|
||||
this.instances = null;
|
||||
this.initializationFailures = [];
|
||||
}
|
||||
}
|
||||
|
||||
const createInstance = (descriptor: DockerEndpointDescriptor): DockerInstance => ({
|
||||
endpointId: descriptor.id,
|
||||
endpointName: descriptor.name,
|
||||
host: getDockerEndpointHost(descriptor),
|
||||
descriptor,
|
||||
instance: new Docker(createDockerOptions(descriptor)),
|
||||
});
|
||||
|
||||
const createDockerOptions = (descriptor: DockerEndpointDescriptor) => {
|
||||
const transport = descriptor.transport;
|
||||
if (transport.type === "socket") return { socketPath: transport.path };
|
||||
if (transport.type === "tcp") return { host: transport.host, port: transport.port, protocol: "http" as const };
|
||||
return {
|
||||
host: transport.host,
|
||||
port: transport.port,
|
||||
protocol: "https" as const,
|
||||
ca: readFileSync(transport.caPath),
|
||||
...(transport.certPath && transport.keyPath
|
||||
? { cert: readFileSync(transport.certPath), key: readFileSync(transport.keyPath) }
|
||||
: {}),
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,71 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { parseDockerEndpointDescriptors } from "../endpoint-descriptor";
|
||||
|
||||
describe("parseDockerEndpointDescriptors", () => {
|
||||
test("parses friendly TLS and read-only Podman endpoints", () => {
|
||||
const descriptors = parseDockerEndpointDescriptors(
|
||||
JSON.stringify([
|
||||
{
|
||||
id: "nas",
|
||||
name: "NAS Docker",
|
||||
transport: { type: "tls", host: "nas.internal", port: 2376, caPath: "/run/secrets/docker-ca" },
|
||||
},
|
||||
{
|
||||
id: "podman",
|
||||
name: "Build host",
|
||||
kind: "podman",
|
||||
transport: { type: "socket", path: "/run/podman/podman.sock" },
|
||||
capabilities: ["inventory", "logs"],
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
expect(descriptors).toEqual([
|
||||
expect.objectContaining({ id: "nas", name: "NAS Docker", kind: "docker", source: "environment" }),
|
||||
expect.objectContaining({ id: "podman", kind: "podman", capabilities: ["inventory", "logs"] }),
|
||||
]);
|
||||
});
|
||||
|
||||
test("requires an explicit opt-in for plaintext TCP", () => {
|
||||
expect(() =>
|
||||
parseDockerEndpointDescriptors(
|
||||
JSON.stringify([{ id: "nas", name: "NAS", transport: { type: "tcp", host: "nas", port: 2375 } }]),
|
||||
),
|
||||
).toThrow("allowInsecure: true");
|
||||
});
|
||||
|
||||
test("rejects duplicate identities and capabilities without inventory", () => {
|
||||
expect(() =>
|
||||
parseDockerEndpointDescriptors(
|
||||
JSON.stringify([
|
||||
{ id: "same", name: "A", transport: { type: "socket", path: "/a" } },
|
||||
{ id: "same", name: "B", transport: { type: "socket", path: "/b" } },
|
||||
]),
|
||||
),
|
||||
).toThrow("ids must be unique");
|
||||
expect(() =>
|
||||
parseDockerEndpointDescriptors(
|
||||
JSON.stringify([
|
||||
{
|
||||
id: "limited",
|
||||
name: "Limited",
|
||||
transport: { type: "socket", path: "/run/docker.sock" },
|
||||
capabilities: ["logs"],
|
||||
},
|
||||
]),
|
||||
),
|
||||
).toThrow("must include inventory");
|
||||
});
|
||||
|
||||
test("returns independent default capability arrays", () => {
|
||||
const [first, second] = parseDockerEndpointDescriptors(
|
||||
JSON.stringify([
|
||||
{ id: "first", name: "First", transport: { type: "socket", path: "/first.sock" } },
|
||||
{ id: "second", name: "Second", transport: { type: "socket", path: "/second.sock" } },
|
||||
]),
|
||||
);
|
||||
|
||||
expect(first?.capabilities).not.toBe(second?.capabilities);
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,7 @@ const mockEnv = vi.hoisted(() => ({
|
||||
DOCKER_SOCKET_PATHS: undefined as string | undefined,
|
||||
DOCKER_HOSTNAMES: undefined as string | undefined,
|
||||
DOCKER_PORTS: undefined as string | undefined,
|
||||
DOCKER_ENDPOINTS: undefined as string | undefined,
|
||||
ENABLE_DOCKER: true,
|
||||
ENABLE_KUBERNETES: false,
|
||||
}));
|
||||
@@ -32,13 +33,17 @@ describe("DockerSingleton", () => {
|
||||
mockEnv.DOCKER_SOCKET_PATHS = undefined;
|
||||
mockEnv.DOCKER_HOSTNAMES = undefined;
|
||||
mockEnv.DOCKER_PORTS = undefined;
|
||||
mockEnv.DOCKER_ENDPOINTS = undefined;
|
||||
});
|
||||
|
||||
test("should return default socket when no env vars set", () => {
|
||||
const instances = DockerSingleton.getInstances();
|
||||
|
||||
expect(instances).toHaveLength(1);
|
||||
expect(instances[0]?.host).toBe("socket");
|
||||
expect(instances[0]?.host).toBe("/var/run/docker.sock");
|
||||
expect(instances[0]).toMatchObject({ endpointId: "socket:default", endpointName: "Local Docker" });
|
||||
const options = (instances[0]?.instance as unknown as { opts: { socketPath: string } } | undefined)?.opts;
|
||||
expect(options?.socketPath).toBe("/var/run/docker.sock");
|
||||
});
|
||||
|
||||
test("should return TCP instances only when DOCKER_HOSTNAMES and DOCKER_PORTS set", () => {
|
||||
@@ -60,6 +65,7 @@ describe("DockerSingleton", () => {
|
||||
expect(instances).toHaveLength(2);
|
||||
expect(instances[0]?.host).toBe("host1:2375");
|
||||
expect(instances[1]?.host).toBe("host2:2376");
|
||||
expect(instances.map(({ endpointId }) => endpointId)).toEqual(["tcp:host1:2375", "tcp:host2:2376"]);
|
||||
});
|
||||
|
||||
test("should throw when hostname and port counts do not match", () => {
|
||||
@@ -86,6 +92,7 @@ describe("DockerSingleton", () => {
|
||||
expect(instances).toHaveLength(2);
|
||||
expect(instances[0]?.host).toBe("/var/run/docker.sock");
|
||||
expect(instances[1]?.host).toBe("/run/user/1000/podman/podman.sock");
|
||||
expect(DockerSingleton.findInstance("socket:/run/user/1000/podman/podman.sock")).toBe(instances[1]);
|
||||
});
|
||||
|
||||
test("should combine socket and TCP instances", () => {
|
||||
@@ -107,4 +114,39 @@ describe("DockerSingleton", () => {
|
||||
|
||||
expect(first).toBe(second);
|
||||
});
|
||||
|
||||
test("uses the structured endpoint descriptor and exposes scoped capabilities", () => {
|
||||
mockEnv.DOCKER_ENDPOINTS = JSON.stringify([
|
||||
{
|
||||
id: "readonly-podman",
|
||||
name: "Read-only Podman",
|
||||
kind: "podman",
|
||||
transport: { type: "socket", path: "/run/podman/podman.sock" },
|
||||
capabilities: ["inventory", "logs"],
|
||||
},
|
||||
]);
|
||||
|
||||
const [endpoint] = DockerSingleton.getInstances();
|
||||
|
||||
expect(endpoint).toMatchObject({ endpointId: "readonly-podman", endpointName: "Read-only Podman" });
|
||||
expect(endpoint?.descriptor).toMatchObject({ kind: "podman", source: "environment" });
|
||||
expect(DockerSingleton.hasCapability("readonly-podman", "logs")).toBe(true);
|
||||
expect(DockerSingleton.hasCapability("readonly-podman", "remove")).toBe(false);
|
||||
});
|
||||
|
||||
test("isolates an unreadable TLS endpoint from healthy endpoints", () => {
|
||||
mockEnv.DOCKER_ENDPOINTS = JSON.stringify([
|
||||
{ id: "local", name: "Local", transport: { type: "socket", path: "/var/run/docker.sock" } },
|
||||
{
|
||||
id: "broken-tls",
|
||||
name: "Broken TLS",
|
||||
transport: { type: "tls", host: "broken.example", port: 2376, caPath: "/missing/docker-ca.pem" },
|
||||
},
|
||||
]);
|
||||
|
||||
expect(DockerSingleton.getInstances().map(({ endpointId }) => endpointId)).toEqual(["local"]);
|
||||
expect(DockerSingleton.getInitializationFailures()).toEqual([
|
||||
expect.objectContaining({ descriptor: expect.objectContaining({ id: "broken-tls" }) }),
|
||||
]);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user