Name ports after the Docker containers that publish them
The health pass keeps the host ports Dockhand says running containers
publish (new table server_container_ports, migration 0080), matched to a
server by its Docker host's name. They name the port on the server's Ports
card and the network Ports table, ahead of a port preset and behind a
label somebody wrote, and in the new-port alert ("8096/tcp jellyfin
(container)"). Never written onto port notes, so a container's port is
still a new port; an unreadable host keeps its names, a day-old name is
dropped. Dockhand is now read on the health pass even with container
alerts off.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
75f060049f
commit
9ca83994fb
18 files changed
+9026
-29
No files matched your search
@@ -0,0 +1,12 @@
|
||||
CREATE TABLE `server_container_ports` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`server_id` integer NOT NULL,
|
||||
`port` integer NOT NULL,
|
||||
`protocol` text DEFAULT 'tcp' NOT NULL,
|
||||
`container` text NOT NULL,
|
||||
`image` text DEFAULT '' NOT NULL,
|
||||
`updated_at` text NOT NULL,
|
||||
FOREIGN KEY (`server_id`) REFERENCES `servers`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `server_container_ports_unique` ON `server_container_ports` (`server_id`,`port`,`protocol`);
|
||||
File diff suppressed because it is too large.
Load diff
@@ -561,6 +561,13 @@
|
||||
"when": 1793390152367,
|
||||
"tag": "0079_cheerful_talkback",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 80,
|
||||
"version": "6",
|
||||
"when": 1793482370383,
|
||||
"tag": "0080_lazy_iron_fist",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -689,6 +689,24 @@ export const serverPorts = sqliteTable(
|
||||
(t) => [uniqueIndex("server_ports_unique").on(t.serverId, t.port, t.protocol)],
|
||||
);
|
||||
|
||||
// The host ports the containers on a server publish, as Dockhand last said (services/containerPorts.ts): one row per port, replaced at every look at that server's Docker host. They name
|
||||
// the ports on the Ports pages and in the "new port" alert (never written onto server_ports, so a note somebody wrote is never touched, and they do not count as "expected").
|
||||
export const serverContainerPorts = sqliteTable(
|
||||
"server_container_ports",
|
||||
{
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
serverId: integer("server_id")
|
||||
.notNull()
|
||||
.references(() => servers.id, { onDelete: "cascade" }),
|
||||
port: integer("port").notNull(),
|
||||
protocol: text("protocol").$type<"tcp" | "udp">().notNull().default("tcp"),
|
||||
container: text("container").notNull(),
|
||||
image: text("image").notNull().default(""),
|
||||
updatedAt: text("updated_at").notNull(), // ISO
|
||||
},
|
||||
(t) => [uniqueIndex("server_container_ports_unique").on(t.serverId, t.port, t.protocol)],
|
||||
);
|
||||
|
||||
// A manually-recorded port opening on something this app doesn't monitor directly — a router's port forward, an
|
||||
// edge firewall rule, a cloud provider's security group, etc. Distinct from serverPorts (which is what a server
|
||||
// itself, or a scan of it, reports): this is what someone tells the app is open further out on the network path,
|
||||
|
||||
@@ -7,6 +7,7 @@ import { requireAuth, requireRole } from "../auth/middleware.js";
|
||||
import { recordAudit } from "../services/audit.js";
|
||||
import { type AgentPort, groupAgentPorts, parseJson, splitPortKey } from "../services/agentPorts.js";
|
||||
import { listPresets, serviceName, serviceNames } from "../services/portPresets.js";
|
||||
import { containerPortName, containerPortNames, type ContainerPortName } from "../services/containerPorts.js";
|
||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
|
||||
export const portsRouter = Router();
|
||||
@@ -26,6 +27,8 @@ export interface AgentPortRow {
|
||||
localOnly: boolean;
|
||||
/** What a port preset calls it ("RDP"), when one does. */
|
||||
service: string | null;
|
||||
/** The container that publishes it, as Dockhand says, when one does. */
|
||||
container: ContainerPortName | null;
|
||||
lastSeenAt: string | null;
|
||||
}
|
||||
|
||||
@@ -35,6 +38,7 @@ portsRouter.get("/agent", asyncHandler(async (_req, res) => {
|
||||
.from(servers);
|
||||
|
||||
const names = serviceNames(await listPresets());
|
||||
const containers = await containerPortNames();
|
||||
const out: AgentPortRow[] = [];
|
||||
for (const s of rows) {
|
||||
const raw = parseJson<AgentPort[] | null>(s.listeningPorts, null);
|
||||
@@ -51,6 +55,7 @@ portsRouter.get("/agent", asyncHandler(async (_req, res) => {
|
||||
process: grouped.process,
|
||||
localOnly: grouped.localOnly,
|
||||
service: serviceName(names, protocol, port),
|
||||
container: containerPortName(containers, s.id, protocol, port),
|
||||
lastSeenAt: s.lastSeenAt,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { recordAudit } from "../services/audit.js";
|
||||
import { beginScan, endScan, MAX_SCAN_SPAN, resolveScanTarget, scanPorts, toRanges } from "../services/portScan.js";
|
||||
import { type AgentPort, groupAgentPorts, parseJson } from "../services/agentPorts.js";
|
||||
import { listPresets, serviceName, serviceNames } from "../services/portPresets.js";
|
||||
import { containerPortName, containerPortNames, type ContainerPortName } from "../services/containerPorts.js";
|
||||
import { recordPortScan } from "../services/portScanRecord.js";
|
||||
import { newListeningPorts, parseBaseline, portKey } from "../services/newPorts.js";
|
||||
import { getSettings } from "../services/settingsStore.js";
|
||||
@@ -36,6 +37,8 @@ export interface PortEntry {
|
||||
comment: string | null;
|
||||
/** What a port preset calls this port ("RDP"), when one does; shown where there is no label of its own. */
|
||||
service: string | null;
|
||||
/** The container that publishes it, as Dockhand says ("jellyfin"), when one does; shown where there is no label of its own, ahead of the preset's name. */
|
||||
container: ContainerPortName | null;
|
||||
/** The last scan from this app connected to it. */
|
||||
scanOpen: boolean;
|
||||
lastSeenOpenAt: string | null;
|
||||
@@ -60,6 +63,7 @@ async function buildPortList(serverId: number) {
|
||||
const fresh = new Set(alerting ? newListeningPorts(agentRaw, parseBaseline(server.portBaseline), expected).map((p) => portKey(p.protocol, p.port)) : []);
|
||||
|
||||
const names = serviceNames(await listPresets());
|
||||
const containers = await containerPortNames(serverId);
|
||||
const entries = new Map<string, PortEntry>();
|
||||
for (const row of rows) {
|
||||
const key = `${row.protocol}:${row.port}`;
|
||||
@@ -70,6 +74,7 @@ async function buildPortList(serverId: number) {
|
||||
label: row.label,
|
||||
comment: row.comment,
|
||||
service: serviceName(names, row.protocol, row.port),
|
||||
container: containerPortName(containers, serverId, row.protocol, row.port),
|
||||
scanOpen: row.open,
|
||||
lastSeenOpenAt: row.lastSeenOpenAt,
|
||||
agent: agent.get(key) ?? null,
|
||||
@@ -87,6 +92,7 @@ async function buildPortList(serverId: number) {
|
||||
label: null,
|
||||
comment: null,
|
||||
service: serviceName(names, protocol, Number(port)),
|
||||
container: containerPortName(containers, serverId, protocol, Number(port)),
|
||||
scanOpen: false,
|
||||
lastSeenOpenAt: null,
|
||||
agent: info,
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* The ports the containers on a server publish, said by name: "8096 → jellyfin". Dockhand knows which containers run on each Docker host and which host ports they publish; the host an
|
||||
* environment is (its name there) is matched to a server the way Uptime Kuma targets and Dockhand-recognised apps are (services/uptimeKumaMatch.ts), and what it publishes is kept per server
|
||||
* (server_container_ports) so the Ports pages and the "new port" alert can name a port without asking Dockhand each time.
|
||||
*
|
||||
* It is only ever a name shown beside the port. Nothing is written onto the server's own port notes, so a label somebody wrote wins, and a container's port does not count as "expected" —
|
||||
* a container that starts publishing something new is still news, and the alert now says which container.
|
||||
*
|
||||
* Read on the health pass from the container list it already takes. A host Dockhand could not read keeps what it had; what has not been refreshed for a day is dropped.
|
||||
*/
|
||||
import { eq, inArray, lt } from "drizzle-orm";
|
||||
import { db } from "../db/client.js";
|
||||
import { serverContainerPorts, servers } from "../db/schema.js";
|
||||
import { matchServerForTarget, toMatchableServers, type MatchableServer } from "./uptimeKumaMatch.js";
|
||||
|
||||
/** What Dockhand's container list is read as here; the adapter's own types satisfy it. */
|
||||
export interface ContainerPortRead {
|
||||
containers: { name: string; image: string; state: string; environmentId: number; ports: { publicPort: number | null; protocol: string }[] }[];
|
||||
environments: { id: number; name: string }[];
|
||||
unreachable: { environmentId: number }[];
|
||||
}
|
||||
|
||||
export interface ContainerPortRow {
|
||||
port: number;
|
||||
protocol: "tcp" | "udp";
|
||||
container: string;
|
||||
image: string;
|
||||
}
|
||||
|
||||
/** A refresh older than this is not trusted any more: the Docker host stopped being read, or the integration is gone. */
|
||||
export const CONTAINER_PORTS_STALE_MS = 24 * 3_600_000;
|
||||
|
||||
export interface ContainerPortPlan {
|
||||
/** For each server whose Docker host was read: what its running containers publish. A server with a host but nothing published has an empty list, so old rows are cleared. */
|
||||
rows: Map<number, ContainerPortRow[]>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure: which published port belongs to which server. Only running containers count, only host ports (a port with no host side is not on the server), only TCP and UDP. A host Dockhand
|
||||
* could not read, or one that matches no server, is left out altogether. The same host port twice (IPv4 and IPv6 bindings, usually) is one row; if two containers claim it, the first by name.
|
||||
*/
|
||||
export function planContainerPorts(read: ContainerPortRead, servers: MatchableServer[]): ContainerPortPlan {
|
||||
const unreachable = new Set(read.unreachable.map((u) => u.environmentId));
|
||||
const serverOfEnv = new Map<number, number>();
|
||||
const rows = new Map<number, ContainerPortRow[]>();
|
||||
for (const env of read.environments) {
|
||||
if (unreachable.has(env.id)) continue;
|
||||
const server = matchServerForTarget(env.name, servers);
|
||||
if (!server) continue;
|
||||
serverOfEnv.set(env.id, server.id);
|
||||
if (!rows.has(server.id)) rows.set(server.id, []);
|
||||
}
|
||||
|
||||
const seen = new Set<string>();
|
||||
for (const c of [...read.containers].sort((a, b) => a.name.localeCompare(b.name))) {
|
||||
const serverId = serverOfEnv.get(c.environmentId);
|
||||
if (serverId === undefined || c.state !== "running") continue;
|
||||
for (const p of c.ports) {
|
||||
const protocol = p.protocol === "tcp" || p.protocol === "udp" ? p.protocol : null;
|
||||
if (p.publicPort === null || protocol === null) continue;
|
||||
const key = `${serverId}:${protocol}:${p.publicPort}`;
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
rows.get(serverId)!.push({ port: p.publicPort, protocol, container: c.name.replace(/^\//, ""), image: c.image });
|
||||
}
|
||||
}
|
||||
for (const list of rows.values()) list.sort((a, b) => a.port - b.port || a.protocol.localeCompare(b.protocol));
|
||||
return { rows };
|
||||
}
|
||||
|
||||
/** Takes in what a Dockhand read says, replacing what was kept for each server it covers. */
|
||||
export async function refreshContainerPorts(read: ContainerPortRead, now = new Date()): Promise<void> {
|
||||
const matchable = toMatchableServers((await db.select({ id: servers.id, name: servers.name, hostname: servers.hostname, ips: servers.ipAddresses }).from(servers)));
|
||||
const { rows } = planContainerPorts(read, matchable);
|
||||
if (rows.size === 0) return;
|
||||
const updatedAt = now.toISOString();
|
||||
await db.transaction(async (tx) => {
|
||||
await tx.delete(serverContainerPorts).where(inArray(serverContainerPorts.serverId, [...rows.keys()]));
|
||||
for (const [serverId, list] of rows) {
|
||||
if (list.length > 0) await tx.insert(serverContainerPorts).values(list.map((r) => ({ serverId, updatedAt, ...r })));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Drops what has not been refreshed for a day. */
|
||||
export async function purgeStaleContainerPorts(nowMs = Date.now()): Promise<void> {
|
||||
await db.delete(serverContainerPorts).where(lt(serverContainerPorts.updatedAt, new Date(nowMs - CONTAINER_PORTS_STALE_MS).toISOString()));
|
||||
}
|
||||
|
||||
export interface ContainerPortName {
|
||||
container: string;
|
||||
image: string;
|
||||
}
|
||||
|
||||
/** The kept names, by server and then "tcp:8096"; nothing older than a day. Pass a server to read only that one's. */
|
||||
export async function containerPortNames(serverId?: number, nowMs = Date.now()): Promise<Map<number, Map<string, ContainerPortName>>> {
|
||||
const fresh = new Date(nowMs - CONTAINER_PORTS_STALE_MS).toISOString();
|
||||
const rows = await db.select().from(serverContainerPorts).where(serverId === undefined ? undefined : eq(serverContainerPorts.serverId, serverId));
|
||||
const out = new Map<number, Map<string, ContainerPortName>>();
|
||||
for (const r of rows) {
|
||||
if (r.updatedAt < fresh) continue;
|
||||
const byKey = out.get(r.serverId) ?? new Map<string, ContainerPortName>();
|
||||
byKey.set(`${r.protocol}:${r.port}`, { container: r.container, image: r.image });
|
||||
out.set(r.serverId, byKey);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** How a container reads in the new-port alert: "jellyfin (container)". */
|
||||
export const containerLabel = (name: ContainerPortName | null): string | null => (name ? `${name.container} (container)` : null);
|
||||
|
||||
export const containerPortName =(names: Map<number, Map<string, ContainerPortName>>, serverId: number, protocol: string, port: number): ContainerPortName | null => names.get(serverId)?.get(`${protocol}:${port}`) ?? null;
|
||||
@@ -14,6 +14,7 @@ import { getFailingSources } from "./integrationHealthMonitor.js";
|
||||
import { hostHealthConditions, parseHostHealth, withoutIgnoredServices, type HostHealth } from "./hostHealth.js";
|
||||
import { newListeningPorts, newPortMessage, parseBaseline, portKey, type NewPort } from "./newPorts.js";
|
||||
import { listPresets, serviceName, serviceNames } from "./portPresets.js";
|
||||
import { containerLabel, containerPortName, containerPortNames, purgeStaleContainerPorts, refreshContainerPorts } from "./containerPorts.js";
|
||||
import { parseJson, type AgentPort } from "./agentPorts.js";
|
||||
import { diskLimit, parseThresholds, type ServerThresholds } from "./serverThresholds.js";
|
||||
import { computeRuleFindings, findingKey, listRules, type RuleFinding } from "./alertRules.js";
|
||||
@@ -488,6 +489,39 @@ export async function collectSnapshot(): Promise<{ snapshot: HealthSnapshot; hel
|
||||
const snapshot: HealthSnapshot = { servers: [], proxmox: [], synology: [] };
|
||||
|
||||
const { healthChecks: checks } = await getSettings();
|
||||
|
||||
// Docker containers, from Dockhand: what is broken, what stopped unexpectedly. A Dockhand that cannot be read holds its containers' alerts rather than clearing them. Read first, and
|
||||
// whether or not the container alerts are on, because the ports the containers publish are kept from this same read (services/containerPorts.ts) to name them in the new-port alert below.
|
||||
if (checks.containerAlerts) {
|
||||
snapshot.dockerIgnore = checks.containerIgnore;
|
||||
snapshot.dockerMemory = await loadContainerMemory();
|
||||
}
|
||||
try {
|
||||
await purgeStaleContainerPorts();
|
||||
} catch (err) {
|
||||
console.error("[health] couldn't clear old container ports:", err instanceof Error ? err.message : err);
|
||||
}
|
||||
for (const row of await db.select({ id: integrations.id, name: integrations.name }).from(integrations).where(and(eq(integrations.type, "dockhand"), eq(integrations.enabled, true)))) {
|
||||
try {
|
||||
const loaded = await loadIntegrationConfig(row.id);
|
||||
if (!loaded) continue;
|
||||
const read = await createDockhandAdapter(loaded.config as any).listContainersDetailed();
|
||||
if (checks.containerAlerts) {
|
||||
(snapshot.docker ??= []).push({ integrationId: row.id, integrationName: row.name, containers: read.containers, unreachable: read.unreachable });
|
||||
for (const u of read.unreachable) held.add(`dockhand:${row.id}:${u.environmentId}`);
|
||||
}
|
||||
try {
|
||||
await refreshContainerPorts(read);
|
||||
} catch (err) {
|
||||
console.error(`[health] couldn't keep the ports of Docker integration ${row.id}:`, err instanceof Error ? err.message : err);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[health] couldn't read Docker integration ${row.id}:`, err instanceof Error ? err.message : err);
|
||||
if (checks.containerAlerts) held.add(`dockhand:${row.id}`);
|
||||
}
|
||||
}
|
||||
const containerNames = await containerPortNames();
|
||||
|
||||
// The ports somebody has said are expected (a label or a comment on the Ports page); a row that only records an open scan says nothing.
|
||||
const portNames = serviceNames(await listPresets());
|
||||
const expectedByServer = new Map<number, Set<string>>();
|
||||
@@ -506,7 +540,7 @@ export async function collectSnapshot(): Promise<{ snapshot: HealthSnapshot; hel
|
||||
} catch {
|
||||
// a malformed report shouldn't stop every other server being checked
|
||||
}
|
||||
const newPorts = checks.newPortAlerts ? newListeningPorts(parseJson<AgentPort[] | null>(s.listeningPorts, null), parseBaseline(s.portBaseline), expectedByServer.get(s.id) ?? new Set()).map((p) => ({ ...p, service: serviceName(portNames, "tcp", p.port) })) : [];
|
||||
const newPorts = checks.newPortAlerts ? newListeningPorts(parseJson<AgentPort[] | null>(s.listeningPorts, null), parseBaseline(s.portBaseline), expectedByServer.get(s.id) ?? new Set()).map((p) => ({ ...p, service: containerLabel(containerPortName(containerNames, s.id, "tcp", p.port)) ?? serviceName(portNames, "tcp", p.port) })) : [];
|
||||
snapshot.servers.push({ id: s.id, name: s.name, lastSeenAt: s.lastSeenAt, disks, health: withoutIgnoredServices(parseHostHealth(s.hostHealth), parseThresholds(s.thresholds)?.ignoreServices), thresholds: parseThresholds(s.thresholds), newPorts });
|
||||
}
|
||||
|
||||
@@ -801,24 +835,6 @@ export async function collectSnapshot(): Promise<{ snapshot: HealthSnapshot; hel
|
||||
held.add("duplicati");
|
||||
}
|
||||
|
||||
// Docker containers, from Dockhand: what is broken, what stopped unexpectedly. A Dockhand that cannot be read holds its containers' alerts rather than clearing them.
|
||||
if (checks.containerAlerts) {
|
||||
snapshot.dockerIgnore = checks.containerIgnore;
|
||||
snapshot.dockerMemory = await loadContainerMemory();
|
||||
for (const row of await db.select({ id: integrations.id, name: integrations.name }).from(integrations).where(and(eq(integrations.type, "dockhand"), eq(integrations.enabled, true)))) {
|
||||
try {
|
||||
const loaded = await loadIntegrationConfig(row.id);
|
||||
if (!loaded) continue;
|
||||
const read = await createDockhandAdapter(loaded.config as any).listContainersDetailed();
|
||||
(snapshot.docker ??= []).push({ integrationId: row.id, integrationName: row.name, containers: read.containers, unreachable: read.unreachable });
|
||||
for (const u of read.unreachable) held.add(`dockhand:${row.id}:${u.environmentId}`);
|
||||
} catch (err) {
|
||||
console.error(`[health] couldn't read Docker integration ${row.id}:`, err instanceof Error ? err.message : err);
|
||||
held.add(`dockhand:${row.id}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Vulnerabilities Dockhand's scans found, as the sync pass stored them (only critical ones are raised). Switched off with the setting; a reading gone stale is held, not cleared.
|
||||
if (checks.vulnerabilityAlerts) {
|
||||
try {
|
||||
|
||||
@@ -275,7 +275,7 @@ describe("through the health pass, the Alerts page and the Docker page", () => {
|
||||
assert.equal(body.containers.find((x: any) => x.name === "gitea").leftAlone, false);
|
||||
});
|
||||
|
||||
test("it can be switched off, and then nothing is asked of Dockhand", async () => {
|
||||
test("it can be switched off, and then no container alerts are made", async () => {
|
||||
const checks = (await getSettings()).healthChecks;
|
||||
assert.equal(checks.containerAlerts, true, "on by default");
|
||||
await updateSettings({ healthChecks: { ...checks, containerAlerts: false } });
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
/**
|
||||
* The ports containers publish, kept per server from what Dockhand says and used to name them on the Ports pages and in the new-port alert: which published port belongs to which server,
|
||||
* what a refresh replaces and what it leaves alone, how long a name is trusted, and what the two ports routes say.
|
||||
*
|
||||
* Run with: npm test --workspace server
|
||||
*/
|
||||
import { test, describe, before, after } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { createServer as createHttpServer, type Server } from "node:http";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { AddressInfo } from "node:net";
|
||||
|
||||
const dir = mkdtempSync(join(tmpdir(), "hm-containerports-"));
|
||||
process.env.DATABASE_PATH = join(dir, "test.sqlite");
|
||||
process.env.SESSION_DIR = join(dir, "sessions");
|
||||
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
|
||||
|
||||
const express = (await import("express")).default;
|
||||
const { db } = await import("../src/db/client.js");
|
||||
const { users, servers, serverPorts, serverContainerPorts, integrations } = await import("../src/db/schema.js");
|
||||
const { runMigrations } = await import("../src/db/migrate.js");
|
||||
const cp = await import("../src/services/containerPorts.js");
|
||||
const { requireAuth } = await import("../src/auth/middleware.js");
|
||||
const { serverPortsRouter } = await import("../src/routes/serverPorts.js");
|
||||
const { portsRouter } = await import("../src/routes/ports.js");
|
||||
const { newPortMessage } = await import("../src/services/newPorts.js");
|
||||
const { collectSnapshot } = await import("../src/services/healthMonitor.js");
|
||||
const { getSettings, updateSettings } = await import("../src/services/settingsStore.js");
|
||||
const { eq } = await import("drizzle-orm");
|
||||
|
||||
await runMigrations();
|
||||
|
||||
const env = (id: number, name: string) => ({ id, name });
|
||||
const box = (environmentId: number, name: string, state: string, ports: { publicPort: number | null; protocol: string }[], image = `img/${name}`) => ({ name, image, state, environmentId, ports });
|
||||
const servs = [
|
||||
{ id: 1, name: "docker1", hostname: "docker1.lan", ips: ["192.168.1.10"] },
|
||||
{ id: 2, name: "nas", hostname: null, ips: [] },
|
||||
];
|
||||
|
||||
describe("planContainerPorts", () => {
|
||||
test("a running container's published ports go to the server its Docker host is", () => {
|
||||
const { rows } = cp.planContainerPorts(
|
||||
{
|
||||
environments: [env(1, "docker1"), env(2, "nas.lan")],
|
||||
unreachable: [],
|
||||
containers: [
|
||||
box(1, "jellyfin", "running", [{ publicPort: 8096, protocol: "tcp" }, { publicPort: 1900, protocol: "udp" }, { publicPort: null, protocol: "tcp" }]),
|
||||
box(2, "/pihole", "running", [{ publicPort: 53, protocol: "udp" }, { publicPort: 53, protocol: "tcp" }]),
|
||||
],
|
||||
},
|
||||
servs,
|
||||
);
|
||||
assert.deepEqual(rows.get(1)?.map((r) => [r.port, r.protocol, r.container]), [[1900, "udp", "jellyfin"], [8096, "tcp", "jellyfin"]]);
|
||||
assert.deepEqual(rows.get(2)?.map((r) => [r.port, r.protocol, r.container]), [[53, "tcp", "pihole"], [53, "udp", "pihole"]], "the leading slash of a Docker name is dropped; TCP and UDP are two ports");
|
||||
});
|
||||
|
||||
test("a container that isn't running, a port with no host side and a protocol that isn't TCP or UDP name nothing", () => {
|
||||
const { rows } = cp.planContainerPorts(
|
||||
{
|
||||
environments: [env(1, "docker1")],
|
||||
unreachable: [],
|
||||
containers: [box(1, "stopped", "exited", [{ publicPort: 81, protocol: "tcp" }]), box(1, "inner", "running", [{ publicPort: null, protocol: "tcp" }]), box(1, "odd", "running", [{ publicPort: 82, protocol: "sctp" }])],
|
||||
},
|
||||
servs,
|
||||
);
|
||||
assert.deepEqual(rows.get(1), [], "the host was read, and it publishes nothing: so old names are cleared");
|
||||
});
|
||||
|
||||
test("a host Dockhand couldn't read, and one that is no server of ours, are left out altogether", () => {
|
||||
const { rows } = cp.planContainerPorts(
|
||||
{
|
||||
environments: [env(1, "docker1"), env(2, "nas"), env(3, "ghost")],
|
||||
unreachable: [{ environmentId: 2 }],
|
||||
containers: [box(1, "a", "running", [{ publicPort: 80, protocol: "tcp" }]), box(2, "b", "running", [{ publicPort: 81, protocol: "tcp" }]), box(3, "c", "running", [{ publicPort: 82, protocol: "tcp" }])],
|
||||
},
|
||||
servs,
|
||||
);
|
||||
assert.deepEqual([...rows.keys()], [1], "nas wasn't read, so what is kept for it stays; ghost is nobody");
|
||||
});
|
||||
|
||||
test("the same host port twice is one name, and if two containers claim it the first by name has it", () => {
|
||||
const { rows } = cp.planContainerPorts(
|
||||
{
|
||||
environments: [env(1, "docker1")],
|
||||
unreachable: [],
|
||||
containers: [box(1, "zeta", "running", [{ publicPort: 8080, protocol: "tcp" }, { publicPort: 8080, protocol: "tcp" }]), box(1, "alpha", "running", [{ publicPort: 8080, protocol: "tcp" }])],
|
||||
},
|
||||
servs,
|
||||
);
|
||||
assert.deepEqual(rows.get(1)?.map((r) => r.container), ["alpha"]);
|
||||
});
|
||||
|
||||
test("two Docker hosts on one server pool their ports", () => {
|
||||
const { rows } = cp.planContainerPorts(
|
||||
{ environments: [env(1, "docker1"), env(5, "docker1.lan")], unreachable: [], containers: [box(1, "a", "running", [{ publicPort: 80, protocol: "tcp" }]), box(5, "b", "running", [{ publicPort: 81, protocol: "tcp" }])] },
|
||||
servs,
|
||||
);
|
||||
assert.deepEqual(rows.get(1)?.map((r) => r.container), ["a", "b"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("kept names and the routes", () => {
|
||||
let app: Server;
|
||||
let base = "";
|
||||
const ids: Record<string, number> = {};
|
||||
const json = async <T>(r: Response) => (await r.json()) as T;
|
||||
const read = (rest: Partial<Parameters<typeof cp.planContainerPorts>[0]> = {}) => ({
|
||||
environments: [env(1, "web"), env(2, "db")],
|
||||
unreachable: [],
|
||||
containers: [box(1, "jellyfin", "running", [{ publicPort: 8096, protocol: "tcp" }]), box(2, "postgres", "running", [{ publicPort: 5432, protocol: "tcp" }])],
|
||||
...rest,
|
||||
});
|
||||
const namesFor = async (serverId: number) => [...((await cp.containerPortNames(serverId)).get(serverId) ?? new Map()).entries()].map(([k, v]) => `${k}=${v.container}`);
|
||||
|
||||
before(async () => {
|
||||
await db.insert(users).values({ oidcSub: "viewer", name: "Vic", role: "viewer" });
|
||||
const mk = async (name: string, ports: unknown[]) => (await db.insert(servers).values({ name, apiTokenHash: name, apiTokenPrefix: name, listeningPorts: JSON.stringify(ports) }).returning({ id: servers.id }))[0].id;
|
||||
const agent = (port: number, process: string) => ({ protocol: "tcp", port, address: "0.0.0.0", process });
|
||||
ids.web = await mk("web", [agent(22, "sshd"), agent(8096, "docker-proxy"), agent(9999, "x")]);
|
||||
ids.db = await mk("db", [agent(5432, "docker-proxy")]);
|
||||
const a = express();
|
||||
a.use(express.json());
|
||||
a.use((req, _res, next) => {
|
||||
(req as unknown as { session: unknown }).session = { user: { sub: "viewer" } };
|
||||
next();
|
||||
});
|
||||
a.use("/api/servers", requireAuth);
|
||||
a.use("/api/servers/:id/ports", serverPortsRouter);
|
||||
a.use("/api/ports", portsRouter);
|
||||
app = await new Promise<Server>((resolve) => {
|
||||
const s = a.listen(0, "127.0.0.1", () => resolve(s));
|
||||
});
|
||||
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api`;
|
||||
});
|
||||
after(() => {
|
||||
app.close();
|
||||
try {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
} catch {
|
||||
// Windows keeps the database file locked until the process exits.
|
||||
}
|
||||
});
|
||||
|
||||
test("a refresh keeps each server's published ports under its own name", async () => {
|
||||
await cp.refreshContainerPorts(read());
|
||||
assert.deepEqual(await namesFor(ids.web), ["tcp:8096=jellyfin"]);
|
||||
assert.deepEqual(await namesFor(ids.db), ["tcp:5432=postgres"]);
|
||||
});
|
||||
|
||||
test("the next refresh replaces them; a host with nothing published is cleared", async () => {
|
||||
await cp.refreshContainerPorts(read({ containers: [box(1, "emby", "running", [{ publicPort: 8920, protocol: "tcp" }]), box(2, "postgres", "exited", [{ publicPort: 5432, protocol: "tcp" }])] }));
|
||||
assert.deepEqual(await namesFor(ids.web), ["tcp:8920=emby"], "jellyfin is gone");
|
||||
assert.deepEqual(await namesFor(ids.db), [], "postgres stopped");
|
||||
await cp.refreshContainerPorts(read());
|
||||
});
|
||||
|
||||
test("a host that could not be read keeps what it had; a refresh that covers nobody changes nothing", async () => {
|
||||
await cp.refreshContainerPorts(read({ unreachable: [{ environmentId: 2 }], containers: [box(1, "emby", "running", [{ publicPort: 8920, protocol: "tcp" }])] }));
|
||||
assert.deepEqual(await namesFor(ids.db), ["tcp:5432=postgres"]);
|
||||
assert.deepEqual(await namesFor(ids.web), ["tcp:8920=emby"]);
|
||||
await cp.refreshContainerPorts({ environments: [env(9, "elsewhere")], unreachable: [], containers: [box(9, "x", "running", [{ publicPort: 1, protocol: "tcp" }])] });
|
||||
assert.deepEqual(await namesFor(ids.web), ["tcp:8920=emby"]);
|
||||
await cp.refreshContainerPorts(read());
|
||||
});
|
||||
|
||||
test("a name not refreshed for a day is no longer used, and is cleared on the next pass", async () => {
|
||||
const later = Date.now() + cp.CONTAINER_PORTS_STALE_MS + 60_000;
|
||||
assert.deepEqual([...(await cp.containerPortNames(undefined, later)).keys()], [], "too old to trust");
|
||||
assert.equal((await db.select().from(serverContainerPorts)).length, 2);
|
||||
await cp.purgeStaleContainerPorts(later);
|
||||
assert.equal((await db.select().from(serverContainerPorts)).length, 0);
|
||||
await cp.refreshContainerPorts(read());
|
||||
assert.equal((await db.select().from(serverContainerPorts)).length, 2);
|
||||
});
|
||||
|
||||
test("a server's ports say which container publishes a port, and leave a note somebody wrote alone", async () => {
|
||||
await db.insert(serverPorts).values({ serverId: ids.web, port: 8096, protocol: "tcp", label: "Media", updatedAt: new Date().toISOString() });
|
||||
const body = await json<{ ports: { port: number; label: string | null; container: { container: string; image: string } | null; service: string | null }[] }>(await fetch(`${base}/servers/${ids.web}/ports`));
|
||||
const by = new Map(body.ports.map((p) => [p.port, p]));
|
||||
assert.deepEqual(by.get(8096)?.container, { container: "jellyfin", image: "img/jellyfin" });
|
||||
assert.equal(by.get(8096)?.label, "Media", "the note is still the note");
|
||||
assert.equal(by.get(22)?.container, null);
|
||||
assert.equal(by.get(9999)?.container, null);
|
||||
const [row] = await db.select().from(serverPorts).where(eq(serverPorts.serverId, ids.web));
|
||||
assert.equal(row.label, "Media", "nothing was written onto the port notes");
|
||||
});
|
||||
|
||||
test("the ports of every server say it too, only on the right server", async () => {
|
||||
const body = await json<{ ports: { serverName: string; port: number; container: { container: string } | null }[] }>(await fetch(`${base}/ports/agent`));
|
||||
assert.deepEqual(body.ports.filter((p) => p.container).map((p) => `${p.serverName}:${p.port}=${p.container!.container}`).sort(), ["db:5432=postgres", "web:8096=jellyfin"]);
|
||||
});
|
||||
|
||||
test("a container's port is still news: it is named in the alert, not counted as expected", async () => {
|
||||
assert.equal(cp.containerLabel({ container: "jellyfin", image: "" }), "jellyfin (container)");
|
||||
assert.equal(cp.containerLabel(null), null);
|
||||
assert.equal(
|
||||
newPortMessage("web", { protocol: "tcp", port: 8096, process: "docker-proxy", service: cp.containerLabel({ container: "jellyfin", image: "" }) }),
|
||||
"web: a new port is listening — 8096/tcp jellyfin (container) (docker-proxy). If it should be there, note it on the server's Ports card.",
|
||||
);
|
||||
const expectedRows = await db.select().from(serverPorts).where(eq(serverPorts.serverId, ids.db));
|
||||
assert.equal(expectedRows.length, 0, "no port note was made for the container's port");
|
||||
});
|
||||
|
||||
test("the health pass keeps them from Dockhand and names the port in its new-port alert; with the container alerts off it still does; a Dockhand it can't read changes nothing", async () => {
|
||||
let published: { name: string; port: number }[] = [{ name: "jellyfin", port: 8096 }];
|
||||
let broken = false;
|
||||
const dockhand = createHttpServer((req, res) => {
|
||||
const url = new URL(req.url ?? "", "http://x");
|
||||
res.setHeader("content-type", "application/json");
|
||||
if (broken) {
|
||||
res.statusCode = 500;
|
||||
return void res.end("{}");
|
||||
}
|
||||
if (url.pathname === "/api/environments") return void res.end(JSON.stringify([{ id: 1, name: "pass-host", connectionType: "hawser" }]));
|
||||
if (url.pathname === "/api/containers/pending-updates") return void res.end(JSON.stringify({ pendingUpdates: [] }));
|
||||
if (url.pathname === "/api/containers") return void res.end(JSON.stringify(published.map((c) => ({ id: c.name, name: c.name, image: "img", state: "running", status: "Up 1 hour", ports: [{ IP: "0.0.0.0", PrivatePort: 80, PublicPort: c.port, Type: "tcp" }] }))));
|
||||
res.statusCode = 404;
|
||||
res.end("{}");
|
||||
});
|
||||
await new Promise<void>((r) => dockhand.listen(0, "127.0.0.1", r));
|
||||
const [integration] = await db.insert(integrations).values({ type: "dockhand", name: "Dockhand", baseUrl: "", config: JSON.stringify({ url: `http://127.0.0.1:${(dockhand.address() as AddressInfo).port}`, token: "t" }) }).returning({ id: integrations.id });
|
||||
const listening = [8096, 8920].map((port) => ({ protocol: "tcp", port, address: "0.0.0.0", process: "docker-proxy" }));
|
||||
await db.insert(servers).values({ name: "pass-host", apiTokenHash: "p", apiTokenPrefix: "p", listeningPorts: JSON.stringify(listening), portBaseline: JSON.stringify(["tcp:22"]) });
|
||||
const newPorts = async () => (await collectSnapshot()).snapshot.servers.find((s) => s.name === "pass-host")!.newPorts.map((p) => `${p.port} ${p.service ?? "-"}`);
|
||||
try {
|
||||
assert.deepEqual(await newPorts(), ["8096 jellyfin (container)", "8920 -"], "the port the container publishes is named; the other one has no name");
|
||||
|
||||
const checks = (await getSettings()).healthChecks;
|
||||
await updateSettings({ healthChecks: { ...checks, containerAlerts: false } });
|
||||
published = [{ name: "emby", port: 8920 }];
|
||||
const pass = await collectSnapshot();
|
||||
assert.equal(pass.snapshot.docker, undefined, "no container alerts");
|
||||
assert.deepEqual(await newPorts(), ["8096 -", "8920 emby (container)"], "but what the containers publish is still taken in");
|
||||
await updateSettings({ healthChecks: { ...checks, containerAlerts: true } });
|
||||
|
||||
broken = true;
|
||||
const held = await collectSnapshot();
|
||||
assert.ok(held.held.has(`dockhand:${integration.id}`), "an unreadable Dockhand holds its alerts");
|
||||
assert.deepEqual(await newPorts(), ["8096 -", "8920 emby (container)"], "and what was kept is kept");
|
||||
} finally {
|
||||
dockhand.close();
|
||||
await db.delete(integrations).where(eq(integrations.id, integration.id));
|
||||
await db.delete(servers).where(eq(servers.name, "pass-host"));
|
||||
}
|
||||
});
|
||||
|
||||
test("taking a server away takes its names with it", async () => {
|
||||
await db.delete(servers).where(eq(servers.id, ids.db));
|
||||
assert.deepEqual(await namesFor(ids.db), []);
|
||||
assert.deepEqual(await namesFor(ids.web), ["tcp:8096=jellyfin"]);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user