Skip to content

Build your personal knowledge base with Trilium Notes

perf(healthcheck): probe with a shell script instead of starting node

Elian Doran8e05dbac20b9
diff --git a/apps/server/Dockerfile b/apps/server/Dockerfile
index f83b0ca698..d32b70c626 100644
--- a/apps/server/Dockerfile
+++ b/apps/server/Dockerfile
@@ -10,7 +10,7 @@ FROM node:24.19.0-trixie-slim
# Install only runtime dependencies
RUN apt-get update && \
apt-get install -y --no-install-recommends \
- gosu && \
+ gosu curl && \
rm -rf \
/var/lib/apt/lists/* \
/var/cache/apt/*
@@ -19,7 +19,10 @@ WORKDIR /usr/src/app
COPY ./dist /usr/src/app
COPY ./start-docker.sh /usr/src/app
+# The healthcheck reads the listening address the server records here.
+ENV TRILIUM_DATA_DIR=/home/node/trilium-data
+
# Configure container
EXPOSE 8080
CMD [ "sh", "./start-docker.sh" ]
-HEALTHCHECK --interval=60s --timeout=5s --start-period=30s CMD exec gosu node node /usr/src/app/docker_healthcheck.cjs
+HEALTHCHECK --interval=60s --timeout=5s --start-period=30s CMD exec gosu node sh /usr/src/app/docker_healthcheck.sh
diff --git a/apps/server/Dockerfile.alpine b/apps/server/Dockerfile.alpine
index c7fdb418bc..1d6b56e629 100644
--- a/apps/server/Dockerfile.alpine
+++ b/apps/server/Dockerfile.alpine
@@ -8,7 +8,7 @@
# stage. They link libstdc++, which node:*-alpine already provides at runtime.
FROM node:24.19.0-alpine3.23
# Install runtime dependencies
-RUN apk add --no-cache su-exec shadow
+RUN apk add --no-cache su-exec shadow curl
WORKDIR /usr/src/app
COPY ./dist /usr/src/app
@@ -17,7 +17,10 @@ COPY ./start-docker.sh /usr/src/app
# Add application user
RUN adduser -s /bin/false node; exit 0
+# The healthcheck reads the listening address the server records here.
+ENV TRILIUM_DATA_DIR=/home/node/trilium-data
+
# Configure container
EXPOSE 8080
CMD [ "sh", "./start-docker.sh" ]
-HEALTHCHECK --interval=60s --timeout=5s --start-period=30s CMD exec su-exec node node /usr/src/app/docker_healthcheck.cjs
\ No newline at end of file
+HEALTHCHECK --interval=60s --timeout=5s --start-period=30s CMD exec su-exec node sh /usr/src/app/docker_healthcheck.sh
\ No newline at end of file
diff --git a/apps/server/Dockerfile.alpine.rootless b/apps/server/Dockerfile.alpine.rootless
index 4a198a637d..b198088466 100644
--- a/apps/server/Dockerfile.alpine.rootless
+++ b/apps/server/Dockerfile.alpine.rootless
@@ -11,7 +11,7 @@ ENV UID=${UID}
ENV GID=${GID}
# Install runtime dependencies and create user with specific UID/GID
-RUN apk add --no-cache dumb-init && \
+RUN apk add --no-cache dumb-init curl && \
apk add --no-cache bash && \
# Alpine uses addgroup/adduser (from busybox) instead of groupadd/useradd
addgroup -g ${GID} ${USER} && \
@@ -39,4 +39,4 @@ ENTRYPOINT ["/usr/bin/dumb-init", "--"]
# Use the entrypoint script
CMD [ "bash", "./rootless-entrypoint.sh" ]
-HEALTHCHECK --interval=60s --timeout=5s --start-period=30s CMD node /home/${USER}/app/docker_healthcheck.js
+HEALTHCHECK --interval=60s --timeout=5s --start-period=30s CMD sh /home/${USER}/app/docker_healthcheck.sh
diff --git a/apps/server/Dockerfile.legacy b/apps/server/Dockerfile.legacy
index bdf9658c08..946e7b868c 100644
--- a/apps/server/Dockerfile.legacy
+++ b/apps/server/Dockerfile.legacy
@@ -30,7 +30,7 @@ FROM node:22.21.0-bullseye-slim
# Install only runtime dependencies
RUN apt-get update && \
apt-get install -y --no-install-recommends \
- gosu && \
+ gosu curl && \
rm -rf \
/var/lib/apt/lists/* \
/var/cache/apt/*
@@ -41,7 +41,10 @@ RUN rm -rf /usr/src/app/node_modules/better-sqlite3
COPY --from=builder /usr/src/app/node_modules/better-sqlite3 /usr/src/app/node_modules/better-sqlite3
COPY ./start-docker.sh /usr/src/app
+# The healthcheck reads the listening address the server records here.
+ENV TRILIUM_DATA_DIR=/home/node/trilium-data
+
# Configure container
EXPOSE 8080
CMD [ "sh", "./start-docker.sh" ]
-HEALTHCHECK --interval=60s --timeout=5s --start-period=30s CMD exec gosu node node /usr/src/app/docker_healthcheck.cjs
\ No newline at end of file
+HEALTHCHECK --interval=60s --timeout=5s --start-period=30s CMD exec gosu node sh /usr/src/app/docker_healthcheck.sh
\ No newline at end of file
diff --git a/apps/server/Dockerfile.rootless b/apps/server/Dockerfile.rootless
index ab29de0632..e5c9049f8a 100644
--- a/apps/server/Dockerfile.rootless
+++ b/apps/server/Dockerfile.rootless
@@ -11,7 +11,9 @@ ENV UID=${UID}
ENV GID=${GID}
# Install only runtime dependencies
-RUN rm -rf \
+RUN apt-get update && \
+ apt-get install -y --no-install-recommends curl && \
+ rm -rf \
/var/lib/apt/lists/* \
/var/cache/apt/* && \
# Create the user/group with the default UID/GID
@@ -37,4 +39,4 @@ ENV TRILIUM_DATA_DIR=/home/${USER}/trilium-data
# Use the entrypoint script
CMD [ "bash", "./rootless-entrypoint.sh" ]
-HEALTHCHECK --interval=60s --timeout=5s --start-period=30s CMD node /home/${USER}/app/docker_healthcheck.js
+HEALTHCHECK --interval=60s --timeout=5s --start-period=30s CMD sh /home/${USER}/app/docker_healthcheck.sh
diff --git a/apps/server/docker_healthcheck.sh b/apps/server/docker_healthcheck.sh
new file mode 100755
index 0000000000..4ad1487bde
--- /dev/null
+++ b/apps/server/docker_healthcheck.sh
@@ -0,0 +1,28 @@
+#!/bin/sh
+# Probes the running server for docker's HEALTHCHECK.
+#
+# The server records where it is listening once it has bound, so there is nothing to resolve
+# here: no config.ini to parse and no guess at a port. A missing file means the server never
+# reached the point of listening, which is itself unhealthy.
+#
+# curl reports its own failures (7 refused, 28 timeout), and treats a 3xx as success, so the
+# status is compared here instead of relying on --fail. Docker reads 0 as healthy and 1 as
+# unhealthy, and reserves 2, so every failure is collapsed onto 1.
+
+data_dir="${TRILIUM_DATA_DIR:-/home/node/trilium-data}"
+url_file="$data_dir/healthcheck-url"
+socket_file="$data_dir/healthcheck-socket"
+
+[ -s "$url_file" ] || exit 1
+url=$(cat "$url_file") || exit 1
+
+# -k because a loopback probe asks whether the server answers, not who it is, and the certificate
+# is usually self-signed and issued for a name this request does not use.
+if [ -s "$socket_file" ]; then
+ status=$(curl -s -k --max-time 2 -o /dev/null -w '%{http_code}' \
+ --unix-socket "$(cat "$socket_file")" "$url") || exit 1
+else
+ status=$(curl -s -k --max-time 2 -o /dev/null -w '%{http_code}' "$url") || exit 1
+fi
+
+[ "$status" = "200" ] || exit 1
diff --git a/apps/server/scripts/build.ts b/apps/server/scripts/build.ts
index f10efa038d..bc97f2428e 100644
--- a/apps/server/scripts/build.ts
+++ b/apps/server/scripts/build.ts
@@ -1,21 +1,17 @@
-import { statSync } from "fs";
-import { join } from "path";
-
import BuildHelper from "../../../scripts/build-utils";
const build = new BuildHelper("apps/server");
-/** Generous next to the few KB the probe needs, far below what a stray import costs. */
-const HEALTHCHECK_MAX_KB = 100;
-
async function main() {
- await build.buildBackend([ "src/main.ts", "src/docker_healthcheck.ts" ])
+ await build.buildBackend([ "src/main.ts" ]);
// Its own call so it lands beside the bundle rather than under a `services/` path: the pool
// looks for it next to whatever is running, and desktop builds it the same way.
await build.buildBackend([ "src/services/image_worker.ts" ]);
// Copy assets
build.copy("src/assets", "assets/");
+ // The healthcheck docker runs; the Dockerfiles point at it inside the image.
+ build.copy("docker_healthcheck.sh", "docker_healthcheck.sh");
// schema.sql lives in trilium-core but is loaded at server startup. The
// bundled main.cjs can't `require.resolve("@triliumnext/core/...")` in
// Docker (no workspace symlinks in the image), so we copy the file
@@ -34,26 +30,6 @@ async function main() {
build.copy("/node_modules/ckeditor5/dist/ckeditor5-content.css", "ckeditor5-content.css");
build.buildFrontend();
-
- assertHealthcheckStaysSmall();
-}
-
-/**
- * Docker runs the healthcheck every 60 seconds, and each run is a cold node process that parses
- * the whole bundle. It resolves its target in healthcheck_target.ts rather than through config.ts
- * so that it pulls in nothing else; importing a server service here costs megabytes and puts that
- * cost on every probe. The limit is generous, so tripping it means a dependency crept back in.
- */
-function assertHealthcheckStaysSmall() {
- const bundle = join(build.outDir, "docker_healthcheck.cjs");
- const sizeKb = statSync(bundle).size / 1024;
-
- if (sizeKb > HEALTHCHECK_MAX_KB) {
- throw new Error(
- `${bundle} is ${sizeKb.toFixed(0)} KB, over the ${HEALTHCHECK_MAX_KB} KB limit. `
- + "Something it imports now pulls in a server service; keep the probe standalone."
- );
- }
}
main();
diff --git a/apps/server/spec/support/self_signed_tls.ts b/apps/server/spec/support/self_signed_tls.ts
index af2cfa19c2..9b76315ec6 100644
--- a/apps/server/spec/support/self_signed_tls.ts
+++ b/apps/server/spec/support/self_signed_tls.ts
@@ -2,29 +2,53 @@
* A throwaway self-signed certificate for tests that need a real TLS listener, generated for
* CN=localhost and valid until 2126. It secures nothing: the key is public in this repository,
* and it exists only so a test can start an https server without shelling out to openssl.
+ *
+ * RSA rather than EC because the curl macOS ships links LibreSSL 3.3.6, which cannot complete an
+ * EC handshake against Node's TLS and would fail the healthcheck script test on every mac.
*/
export const SELF_SIGNED_KEY = `-----BEGIN PRIVATE KEY-----
-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
+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
+Z50hDlrssCmCI6TW9GQLIDKV
-----END PRIVATE KEY-----`;
export const SELF_SIGNED_CERT = `-----BEGIN CERTIFICATE-----
-MIICMzCCAdmgAwIBAgIJANd2MheI5A34MAoGCCqGSM49BAMCMBQxEjAQBgNVBAMM
-CWxvY2FsaG9zdDAgFw0yNjA4MjMxNTA0MzJaGA8yMTI2MDczMDE1MDQzMlowFDES
-MBAGA1UEAwwJbG9jYWxob3N0MIIBSzCCAQMGByqGSM49AgEwgfcCAQEwLAYHKoZI
-zj0BAQIhAP////8AAAABAAAAAAAAAAAAAAAA////////////////MFsEIP////8A
-AAABAAAAAAAAAAAAAAAA///////////////8BCBaxjXYqjqT57PrvVV2mIa8ZR0G
-sMxTsPY7zjw+J9JgSwMVAMSdNgiG5wSTamZ44ROdJreBn36QBEEEaxfR8uEsQkf4
-vOblY6RA8ncDfYEt6zOg9KE5RdiYwpZP40Li/hp/m47n60p8D54WK84zV2sxXs7L
-tkBoN79R9QIhAP////8AAAAA//////////+85vqtpxeehPO5ysL8YyVRAgEBA0IA
-BEKId6j1R5GROrdDCFPIpdmbw0buTikhybK4lctBPOljKxYelFHT0/0lyfJaZpTl
-LriTloTsUGNBfbjYfdmQDIGjHjAcMBoGA1UdEQQTMBGCCWxvY2FsaG9zdIcEfwAA
-ATAKBggqhkjOPQQDAgNIADBFAiBLTh7kJfkGlb435qNAXAy3g9JxQ3Q2DBQJa10T
-Nd+riQIhAMVAviJGOgeezLlI7HR9vS7eUaFFAKWGMKMyhoFTh79s
+MIICyzCCAbOgAwIBAgIJAIsAstDtfD1NMA0GCSqGSIb3DQEBCwUAMBQxEjAQBgNV
+BAMMCWxvY2FsaG9zdDAgFw0yNjA4MjMxNTU3NTFaGA8yMTI2MDczMDE1NTc1MVow
+FDESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
+CgKCAQEAxuNu3Gs2rOw2bvKYdKXmFe+Xgo3Uqnydnxjd5mukspt33fUcbQ9+JfcM
+tja0NfMag2AlwoWkOnqLhJKX9nsKQOW/UQZjfdHwss+6kiGy6LhRakXc2VJ3dXrB
+OrUsZk+gjbePIR7ctXWhupElpquvENuj67R/Vz2jhLBHggkDvh9zpLkFWtOux6Az
+7LXwkLIc1gKHzeLs0+MiJ4maeaxSiMEQJ2gAv6BpjaOTwMhffUDND6gyNcorvmL+
+dkCmj+R2RxgxS5NY8fSkvLL/r/ylbi7EtnTQpVy1VGb3UTUKSd58tX7AqH3UVlm5
+2kvpByLgLOslYDr3sq4nO0W+p0FwowIDAQABox4wHDAaBgNVHREEEzARgglsb2Nh
+bGhvc3SHBH8AAAEwDQYJKoZIhvcNAQELBQADggEBAELpL0D0/tsN2mMhHOSsUpGt
+E4Zwhe1bLBDcT92CfoVIYUKebiPYqbuctUc7PRhaYwrT92bClSRXfWKBKBNRey0H
+4v+bY55MFwIdv64I9OrrUqVXExG1hGP1yJUEAMRxdffGQNBb5dyKM0plczzgu1U2
+b8JLA3x6HRS5MDA05hSlpl3ippaYvyrFRdHA1Eqdauua/mef62XfSkZL3stZiyI5
+Q9pX/OmCd6hicYngxysUi5JZJp2tRSkHf5yYSg7I1txinUDMzrcBBYA5T8Uf+fdJ
+56Dd1E+X4GdeYVXiOHZ5mV2bfU3nF7x4S9qPjTE8y/jru6tE5LDiEsa+0M/I8KM=
-----END CERTIFICATE-----`;
diff --git a/apps/server/src/docker_healthcheck.ts b/apps/server/src/docker_healthcheck.ts
deleted file mode 100644
index 3b450cac3c..0000000000
--- a/apps/server/src/docker_healthcheck.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import { probeHealth, resolveHealthcheckTarget } from "./services/healthcheck.js";
-
-probeHealth(resolveHealthcheckTarget()).then((code) => process.exit(code));
diff --git a/apps/server/src/services/healthcheck.spec.ts b/apps/server/src/services/healthcheck.spec.ts
index b0b16f6471..26d7fb7070 100644
--- a/apps/server/src/services/healthcheck.spec.ts
+++ b/apps/server/src/services/healthcheck.spec.ts
@@ -1,232 +1,240 @@
+import { execFile } from "child_process";
import fs from "fs";
import http from "http";
import https from "https";
import net from "net";
import os from "os";
import path from "path";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { SELF_SIGNED_CERT, SELF_SIGNED_KEY } from "../../spec/support/self_signed_tls.js";
-import { probeHealth, resolveHealthcheckTarget } from "./healthcheck.js";
+import {
+ HEALTHCHECK_SOCKET_FILE, HEALTHCHECK_URL_FILE, publishHealthcheckTarget
+} from "./healthcheck.js";
-//#region Probing the server
+const PROBE_SCRIPT = path.join(__dirname, "../../docker_healthcheck.sh");
-const LOCALHOST = "127.0.0.1";
-/** The probe asks for 2000 ms, so a wait past this is a wait without end. */
-const DEADLINE_ALLOWANCE_MS = 3000;
-const STILL_WAITING = "still waiting for the probe to give up";
+//#region Publishing where the server listens
+
+describe("publishing the healthcheck target", () => {
+ let dataDir: string;
+
+ beforeEach(() => {
+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "trilium-publish-"));
+ });
+
+ afterEach(() => {
+ fs.rmSync(dataDir, { recursive: true, force: true });
+ });
+
+ it("writes the port the server actually bound, not the one that was asked for", () => {
+ const bound = { address: "0.0.0.0", family: "IPv4", port: 9001 };
+
+ publishHealthcheckTarget(dataDir, bound, false);
+
+ expect(readTarget().url).toBe("http://127.0.0.1:9001/api/health-check");
+ expect(readTarget().socket).toBeUndefined();
+ });
+
+ it("dials loopback for wildcard binds, and the interface itself otherwise", () => {
+ const cases: [ string, string, string ][] = [
+ [ "0.0.0.0", "IPv4", "127.0.0.1" ],
+ [ "::", "IPv6", "[::1]" ],
+ [ "192.168.1.5", "IPv4", "192.168.1.5" ],
+ [ "fe80::1", "IPv6", "[fe80::1]" ]
+ ];
+
+ for (const [ address, family, expected ] of cases) {
+ publishHealthcheckTarget(dataDir, { address, family, port: 8080 }, false);
+
+ expect(readTarget().url).toBe(`http://${expected}:8080/api/health-check`);
+ }
+ });
+
+ it("records the scheme the server speaks", () => {
+ publishHealthcheckTarget(dataDir, { address: "0.0.0.0", family: "IPv4", port: 8080 }, true);
+
+ expect(readTarget().url).toBe("https://127.0.0.1:8080/api/health-check");
+ });
+
+ it("passes a unix socket path separately, since the url cannot carry it", () => {
+ publishHealthcheckTarget(dataDir, "/run/trilium.sock", false);
+
+ expect(readTarget()).toEqual({
+ url: "http://localhost/api/health-check",
+ socket: "/run/trilium.sock"
+ });
+ });
+
+ it("clears a stale socket file when the server moves back to a port", () => {
+ publishHealthcheckTarget(dataDir, "/run/trilium.sock", false);
+ publishHealthcheckTarget(dataDir, { address: "0.0.0.0", family: "IPv4", port: 80 }, false);
+
+ expect(readTarget().socket).toBeUndefined();
+ });
+
+ it("writes nothing when the server reports no address", () => {
+ publishHealthcheckTarget(dataDir, null, false);
+
+ expect(fs.existsSync(path.join(dataDir, HEALTHCHECK_URL_FILE))).toBe(false);
+ });
+
+ function readTarget() {
+ const read = (name: string) => {
+ const file = path.join(dataDir, name);
+
+ return fs.existsSync(file) ? fs.readFileSync(file, "utf8") : undefined;
+ };
+
+ return { url: read(HEALTHCHECK_URL_FILE), socket: read(HEALTHCHECK_SOCKET_FILE) };
+ }
+});
+
+//#endregion
+
+//#region The probe docker runs
/**
- * Docker reads two things from the probe: the exit code it resolves, and whatever it prints
- * into the container log. Both are pinned here, against real sockets rather than a mocked
- * `http`, so that socket-level behaviour such as the request timeout is exercised for real.
+ * Drives the shipped shell script rather than a re-implementation of it, against real servers, so
+ * the exit codes docker reads are the ones this asserts. Needs a POSIX shell and curl.
*/
-describe("the docker healthcheck probe", () => {
- let logged: string[];
+describe.skipIf(process.platform === "win32")("the docker healthcheck script", () => {
+ let dataDir: string;
beforeEach(() => {
- logged = [];
- vi.spyOn(console, "log").mockImplementation((message) => {
- logged.push(String(message));
- });
+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "trilium-probe-"));
});
afterEach(async () => {
await stopEverything();
- await new Promise((resolve) => setImmediate(resolve));
- vi.restoreAllMocks();
+ fs.rmSync(dataDir, { recursive: true, force: true });
});
it("reports healthy on 200, having asked for the health-check resource", async () => {
const seen: { method?: string; url?: string }[] = [];
- const port = await startServer((req, res) => {
+ await publishServer((req, res) => {
seen.push({ method: req.method, url: req.url });
res.statusCode = 200;
res.end('{"status":"ok"}');
});
- expect(await probeHealth({ https: false, port, host: LOCALHOST })).toBe(0);
+ expect(await probe()).toBe(0);
expect(seen).toEqual([ { method: "GET", url: "/api/health-check" } ]);
- expect(logged).toEqual([ "STATUS: 200" ]);
});
it("reports unhealthy on any status other than 200", async () => {
let status = 500;
- const port = await startServer((_req, res) => {
+ await publishServer((_req, res) => {
res.statusCode = status;
res.end();
});
for (const next of [ 500, 503, 404, 301 ]) {
status = next;
- expect(await probeHealth({ https: false, port, host: LOCALHOST })).toBe(1);
+ expect(await probe()).toBe(1);
}
-
- expect(logged).toEqual([ "STATUS: 500", "STATUS: 503", "STATUS: 404", "STATUS: 301" ]);
});
it("reports unhealthy when nothing is listening", async () => {
const port = await reserveFreePort();
+ publishHealthcheckTarget(dataDir, { address: "127.0.0.1", family: "IPv4", port }, false);
- expect(await probeHealth({ https: false, port, host: LOCALHOST })).toBe(1);
- expect(logged).toEqual([ "ERROR" ]);
+ expect(await probe()).toBe(1);
});
- it("reaches the server over a unix socket when the port is 0", async () => {
- const seen: (string | undefined)[] = [];
- const socketPath = await startUnixServer((req, res) => {
- seen.push(req.url);
- res.statusCode = 200;
- res.end();
- });
+ it("reports unhealthy when the server never reached listening", async () => {
+ expect(await probe()).toBe(1);
+ });
- expect(await probeHealth({ https: false, port: 0, host: socketPath })).toBe(0);
- expect(seen).toEqual([ "/api/health-check" ]);
- expect(logged).toEqual([ "STATUS: 200" ]);
+ it("gives up and reports unhealthy when the server accepts but never answers", async () => {
+ const server = track(net.createServer(() => { /* accepts, never answers */ }));
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ publishHealthcheckTarget(dataDir, addressOf(server), false);
+
+ const started = Date.now();
+
+ expect(await probe()).toBe(1);
+ expect(Date.now() - started).toBeLessThan(8000);
});
- it("reports unhealthy when the unix socket is not there", async () => {
- const socketPath = path.join(makeTempDir(), "absent.sock");
+ it("speaks TLS, accepting a certificate a loopback probe cannot verify", async () => {
+ await publishServer((_req, res) => {
+ res.statusCode = 200;
+ res.end();
+ }, true);
- expect(await probeHealth({ https: false, port: 0, host: socketPath })).toBe(1);
- expect(logged).toEqual([ "ERROR" ]);
+ expect(await probe()).toBe(0);
});
- it("speaks TLS when trilium terminates it, rather than assuming the server is up", async () => {
+ it("reaches a server listening on a unix socket", async () => {
+ const socketPath = path.join(dataDir, "trilium.sock");
const seen: (string | undefined)[] = [];
- const port = await startTlsServer((req, res) => {
+ const server = track(http.createServer((req, res) => {
seen.push(req.url);
res.statusCode = 200;
res.end();
- });
+ }));
+ await new Promise<void>((resolve) => server.listen(socketPath, resolve));
+ publishHealthcheckTarget(dataDir, socketPath, false);
- expect(await probeHealth({ https: true, port, host: LOCALHOST })).toBe(0);
+ expect(await probe()).toBe(0);
expect(seen).toEqual([ "/api/health-check" ]);
- expect(logged).toEqual([ "STATUS: 200" ]);
- });
-
- it("reports unhealthy over TLS when the server is gone, not passing blindly", async () => {
- const port = await reserveFreePort();
-
- expect(await probeHealth({ https: true, port, host: LOCALHOST })).toBe(1);
- expect(logged).toEqual([ "ERROR" ]);
});
- it("accepts the self-signed certificate a loopback probe cannot verify", async () => {
- // The certificate secures nothing here: the probe is checking that the server answers,
- // not who it is, and a self-signed or expired cert must not read as unhealthy.
- const port = await startTlsServer((_req, res) => {
- res.statusCode = 503;
- res.end();
- });
-
- expect(await probeHealth({ https: true, port, host: LOCALHOST })).toBe(1);
- expect(logged).toEqual([ "STATUS: 503" ]);
- });
+ /** Runs the real script the image ships, with the data directory this test wrote into. */
+ function probe() {
+ return new Promise<number>((resolve) => {
+ const env = { ...process.env, TRILIUM_DATA_DIR: dataDir };
- it("accepts a 200 whatever the body says", async () => {
- // Only the status line is read, so a reverse proxy's own 200 error page passes.
- const port = await startServer((_req, res) => {
- res.statusCode = 200;
- res.end("<html>proxy error</html>");
+ execFile("/bin/sh", [ PROBE_SCRIPT ], { env },
+ (error) => resolve(error ? (typeof error.code === "number" ? error.code : 1) : 0));
});
+ }
- expect(await probeHealth({ https: false, port, host: LOCALHOST })).toBe(0);
- });
-
- it("gives up and reports unhealthy when the server accepts but never answers", async () => {
- // A wedged server still completes the handshake, which is the case the probe exists to
- // catch. Its own 2000 ms deadline has to end the wait and report unhealthy.
- const port = await startServer(() => { /* accepts the request, never answers */ });
- const started = Date.now();
-
- let giveUp: ReturnType<typeof setTimeout> | undefined;
- const outcome = await Promise.race([
- probeHealth({ https: false, port, host: LOCALHOST }),
- new Promise((resolve) => {
- giveUp = setTimeout(() => resolve(STILL_WAITING), DEADLINE_ALLOWANCE_MS);
- })
- ]);
- clearTimeout(giveUp);
-
- expect(outcome).toBe(1);
- expect(Date.now() - started).toBeGreaterThanOrEqual(2000);
- expect(logged).toEqual([ "TIMEOUT after 2000 ms" ]);
- });
+ async function publishServer(handler: http.RequestListener, overTls = false) {
+ const server = track(overTls
+ ? https.createServer({ key: SELF_SIGNED_KEY, cert: SELF_SIGNED_CERT }, handler)
+ : http.createServer(handler));
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ publishHealthcheckTarget(dataDir, addressOf(server), overTls);
+ }
});
+//#endregion
+
/** Everything a test opened, torn down afterwards whether or not the test got that far. */
-const openServers: http.Server[] = [];
+const openServers: (http.Server | net.Server)[] = [];
const openSockets = new Set<net.Socket>();
-const tempDirs: string[] = [];
-async function startServer(handler: http.RequestListener) {
- const server = track(http.createServer(handler));
- await new Promise<void>((resolve) => server.listen(0, LOCALHOST, resolve));
-
- const address = server.address();
- if (address === null || typeof address === "string") {
- throw new Error("expected the server to be listening on a TCP port");
- }
+function track<T extends http.Server | net.Server>(server: T) {
+ openServers.push(server);
+ server.on("connection", (socket: net.Socket) => {
+ openSockets.add(socket);
+ socket.on("close", () => openSockets.delete(socket));
+ });
- return address.port;
+ return server;
}
-async function startTlsServer(handler: http.RequestListener) {
- const tls = { key: SELF_SIGNED_KEY, cert: SELF_SIGNED_CERT };
- const server = track(https.createServer(tls, handler));
- await new Promise<void>((resolve) => server.listen(0, LOCALHOST, resolve));
-
+function addressOf(server: http.Server | net.Server) {
const address = server.address();
if (address === null || typeof address === "string") {
throw new Error("expected the server to be listening on a TCP port");
}
- return address.port;
-}
-
-async function startUnixServer(handler: http.RequestListener) {
- const socketPath = path.join(makeTempDir(), "trilium.sock");
- const server = track(http.createServer(handler));
- await new Promise<void>((resolve) => server.listen(socketPath, resolve));
-
- return socketPath;
+ return address;
}
-/** A port that was listening a moment ago and is now free, so connecting to it is refused. */
async function reserveFreePort() {
const server = net.createServer();
- await new Promise<void>((resolve) => server.listen(0, LOCALHOST, resolve));
-
- const address = server.address();
- if (address === null || typeof address === "string") {
- throw new Error("expected the server to be listening on a TCP port");
- }
-
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const { port } = addressOf(server);
await new Promise<void>((resolve) => server.close(() => resolve()));
- return address.port;
-}
-
-function track(server: http.Server) {
- openServers.push(server);
- server.on("connection", (socket) => {
- openSockets.add(socket);
- socket.on("close", () => openSockets.delete(socket));
- });
-
- return server;
-}
-
-function makeTempDir() {
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "trilium-healthcheck-"));
- tempDirs.push(dir);
-
- return dir;
+ return port;
}
async function stopEverything() {
- // A silent server still holds a live socket, which keeps close() from ever calling back.
for (const socket of openSockets) {
socket.destroy();
}
@@ -235,222 +243,4 @@ async function stopEverything() {
for (const server of openServers.splice(0)) {
await new Promise<void>((resolve) => server.close(() => resolve()));
}
-
- for (const dir of tempDirs.splice(0)) {
- fs.rmSync(dir, { recursive: true, force: true });
- }
-}
-
-//#endregion
-
-//#region Resolving where to probe
-
-/**
- * The probe resolves its target without importing config.ts, port.ts or host.ts, so nothing but
- * these tests keeps the two readings of the same environment and config.ini in step. The last
- * block runs the real config modules over the same inputs and compares.
- */
-describe("resolving the healthcheck target", () => {
- let tempDir: string;
- let iniPath: string;
-
- beforeEach(() => {
- tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "trilium-target-"));
- iniPath = path.join(tempDir, "config.ini");
- });
-
- afterEach(() => {
- fs.rmSync(tempDir, { recursive: true, force: true });
- vi.restoreAllMocks();
- });
-
- it("falls back to localhost:8080 over http when nothing is configured", () => {
- expect(resolveHealthcheckTarget(baseEnv()))
- .toEqual({ https: false, port: 8080, host: "0.0.0.0" });
- });
-
- it("reads the [Network] section of config.ini", () => {
- writeIni("[Network]\nhost=192.168.1.5\nport=9001\nhttps=true\n");
-
- expect(resolveHealthcheckTarget(baseEnv())).toEqual({
- https: true, port: 9001, host: "192.168.1.5"
- });
- });
-
- it("lets the environment override config.ini", () => {
- writeIni("[Network]\nhost=192.168.1.5\nport=9001\n");
- const target = resolveHealthcheckTarget(baseEnv({
- TRILIUM_NETWORK_HOST: "10.0.0.1",
- TRILIUM_NETWORK_PORT: "7777"
- }));
-
- expect(target).toEqual({ https: false, port: 7777, host: "10.0.0.1" });
- });
-
- it("prefers the short TRILIUM_PORT and TRILIUM_HOST aliases over everything else", () => {
- writeIni("[Network]\nhost=192.168.1.5\nport=9001\n");
- const target = resolveHealthcheckTarget(baseEnv({
- TRILIUM_NETWORK_HOST: "10.0.0.1", TRILIUM_NETWORK_PORT: "7777",
- TRILIUM_HOST: "127.0.0.1", TRILIUM_PORT: "8082"
- }));
-
- expect(target).toEqual({ https: false, port: 8082, host: "127.0.0.1" });
- });
-
- it("takes config.ini from TRILIUM_CONFIG_INI_PATH when it is set", () => {
- const elsewhere = path.join(tempDir, "elsewhere.ini");
- fs.writeFileSync(elsewhere, "[Network]\nport=9100\n");
-
- expect(resolveHealthcheckTarget({
- TRILIUM_DATA_DIR: tempDir, TRILIUM_CONFIG_INI_PATH: elsewhere
- }).port).toBe(9100);
- });
-
- it("reads https as true only for true and 1, in any case", () => {
- for (const [ value, expected ] of [
- [ "true", true ], [ "TRUE", true ], [ " true ", true ], [ "1", true ],
- [ "false", false ], [ "0", false ], [ "yes", false ], [ "", false ]
- ] as const) {
- const target = resolveHealthcheckTarget(baseEnv({ TRILIUM_NETWORK_HTTPS: value }));
-
- expect(target.https).toBe(expected);
- }
- });
-
- it("falls back to the default port when the configured one could never be listened on", () => {
- // port.ts exits rather than start, so the server is not listening on anything.
- for (const port of [ "not-a-port", "70000", "-1" ]) {
- expect(resolveHealthcheckTarget(baseEnv({ TRILIUM_PORT: port })).port).toBe(8080);
- }
- });
-
- it("survives a config.ini that is missing, empty or malformed", () => {
- expect(resolveHealthcheckTarget(baseEnv()).port).toBe(8080);
-
- for (const contents of [ "", "not an ini file at all", "[Network]\n" ]) {
- writeIni(contents);
- expect(resolveHealthcheckTarget(baseEnv())).toEqual({
- https: false, port: 8080, host: "0.0.0.0"
- });
- }
- });
-
- it("creates nothing on disk, unlike the config modules it stands in for", () => {
- const untouched = path.join(tempDir, "absent");
-
- resolveHealthcheckTarget({ TRILIUM_DATA_DIR: untouched });
-
- expect(fs.existsSync(untouched)).toBe(false);
- });
-
- it("finds the data directory the server would use when none is configured", () => {
- const home = path.join(tempDir, "home");
- const dataDir = path.join(home, "trilium-data");
- fs.mkdirSync(dataDir, { recursive: true });
- fs.writeFileSync(path.join(dataDir, "config.ini"), "[Network]\nport=9200\n");
- vi.spyOn(os, "homedir").mockReturnValue(home);
-
- expect(resolveHealthcheckTarget({}).port).toBe(9200);
- });
-
- it("falls back to the platform's app-data directory, and to defaults without one", () => {
- const home = path.join(tempDir, "home");
- const appData = path.join(tempDir, "appdata");
- fs.mkdirSync(home, { recursive: true });
- vi.spyOn(os, "homedir").mockReturnValue(home);
-
- const cases = [
- { platform: "linux" as const, dir: path.join(home, ".local", "share"), env: {} },
- { platform: "darwin" as const, env: {},
- dir: path.join(home, "Library", "Application Support") },
- { platform: "win32" as const, dir: appData, env: { APPDATA: appData } }
- ];
-
- for (const [ index, { platform, dir, env } ] of cases.entries()) {
- const dataDir = path.join(dir, "trilium-data");
- fs.mkdirSync(dataDir, { recursive: true });
- fs.writeFileSync(path.join(dataDir, "config.ini"), `[Network]\nport=93${index}0\n`);
- vi.spyOn(os, "platform").mockReturnValue(platform);
-
- expect(resolveHealthcheckTarget(env).port).toBe(9300 + index * 10);
- fs.rmSync(dir, { recursive: true, force: true });
- }
-
- // An unrecognised platform, and Windows without APPDATA, have nowhere else to look.
- vi.spyOn(os, "platform").mockReturnValue("freebsd");
- expect(resolveHealthcheckTarget({}).port).toBe(8080);
-
- vi.spyOn(os, "platform").mockReturnValue("win32");
- expect(resolveHealthcheckTarget({}).port).toBe(8080);
- });
-
- it("treats an unreadable config.ini as absent", () => {
- // A directory where the file should be: it exists, and reading it throws.
- fs.mkdirSync(iniPath);
-
- expect(resolveHealthcheckTarget(baseEnv())).toEqual({
- https: false, port: 8080, host: "0.0.0.0"
- });
- });
-
- describe("agrees with the server's own config modules", () => {
- const CASES = [
- { label: "nothing configured", env: {}, ini: "" },
- { label: "ini only", env: {},
- ini: "[Network]\nhost=192.168.1.5\nport=9001\nhttps=true\n" },
- { label: "standard env vars", ini: "[Network]\nport=9001\n",
- env: { TRILIUM_NETWORK_HOST: "10.0.0.1", TRILIUM_NETWORK_PORT: "7777" } },
- { label: "short aliases", ini: "[Network]\nport=9001\n",
- env: { TRILIUM_HOST: "127.0.0.1", TRILIUM_PORT: "8082" } },
- { label: "https via env", env: { TRILIUM_NETWORK_HTTPS: "true" }, ini: "" },
- { label: "https via ini", env: {}, ini: "[Network]\nhttps=1\n" }
- ];
-
- for (const { label, env, ini: iniText } of CASES) {
- it(label, async () => {
- writeIni(iniText);
- // config.ts and its imports need the ambient test environment to load at all, so
- // both readings are given the same merged environment rather than a bare one.
- const scenario = { ...process.env, ...baseEnv(env) };
-
- const viaConfig = await resolveViaConfigModules(scenario);
-
- expect(resolveHealthcheckTarget(scenario)).toEqual(viaConfig);
- });
- }
- });
-
- /** The env a container hands the probe, with the data dir pointed at this test's temp copy. */
- function baseEnv(extra: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv {
- return { TRILIUM_DATA_DIR: tempDir, ...extra };
- }
-
- function writeIni(contents: string) {
- fs.writeFileSync(iniPath, contents);
- }
-});
-
-/**
- * Loads config.ts, port.ts and host.ts against the given environment and reports the target they
- * describe, so the resolver can be compared against the modules it replaces rather than against
- * hand-written expectations.
- */
-async function resolveViaConfigModules(env: NodeJS.ProcessEnv) {
- const original = process.env;
-
- try {
- process.env = { ...env };
- vi.resetModules();
-
- const { default: config } = await import("./config.js");
- const { default: port } = await import("./port.js");
- const { default: host } = await import("./host.js");
-
- return { https: config.Network.https, port, host };
- } finally {
- process.env = original;
- vi.resetModules();
- }
}
-
-//#endregion
diff --git a/apps/server/src/services/healthcheck.ts b/apps/server/src/services/healthcheck.ts
index 44510248c4..09d69fd541 100644
--- a/apps/server/src/services/healthcheck.ts
+++ b/apps/server/src/services/healthcheck.ts
@@ -1,191 +1,52 @@
import fs from "fs";
-import http from "http";
-import https from "https";
-import ini from "ini";
-import os from "os";
+import type { AddressInfo } from "net";
import path from "path";
-/** Where the probe looks for the server, as the running instance resolved it. */
-export interface HealthcheckTarget {
- /** True when Trilium terminates TLS itself, so the probe has to speak it too. */
- https: boolean;
- /** TCP port to probe, or 0 when `host` names a Unix socket instead. */
- port: number;
- /** Host name, or the Unix socket path when `port` is 0. */
- host: string;
-}
-
-//#region Probing the server
+/** Names the docker healthcheck script looks for, relative to the data directory. */
+export const HEALTHCHECK_URL_FILE = "healthcheck-url";
+export const HEALTHCHECK_SOCKET_FILE = "healthcheck-socket";
const PROBE_PATH = "/api/health-check";
-const TIMEOUT_MS = 2000;
-
-/**
- * Requests `/api/health-check` and resolves the exit code Docker reads from the probe:
- * 0 for healthy, 1 for unhealthy.
- */
-export function probeHealth({ https: overTls, port, host }: HealthcheckTarget): Promise<number> {
- return new Promise((resolve) => {
- const transport = overTls ? https : http;
- const scheme = overTls ? "https" : "http";
- const options: https.RequestOptions = {
- timeout: TIMEOUT_MS,
- // The probe asks whether the server answers, not who it is. A loopback certificate is
- // usually self-signed and issued for a name this request does not use, so verifying it
- // would report a healthy server as dead.
- rejectUnauthorized: false
- };
- const onResponse = (res: http.IncomingMessage) => {
- console.log(`STATUS: ${res.statusCode}`);
- resolve(res.statusCode === 200 ? 0 : 1);
- };
-
- const request = port !== 0
- ? transport.request(`${scheme}://${host}:${port}${PROBE_PATH}`, options, onResponse)
- : transport.request({ ...options, socketPath: host, path: PROBE_PATH }, onResponse);
-
- // `timeout` only arms the socket's idle timer, so the request has to be torn down here.
- // Without this a wedged server that still completes the handshake is waited on forever.
- request.on("timeout", () => {
- console.log(`TIMEOUT after ${TIMEOUT_MS} ms`);
- request.destroy();
- resolve(1);
- });
-
- request.on("error", () => {
- console.log("ERROR");
- resolve(1);
- });
- request.end();
- });
-}
-
-//#endregion
-
-//#region Resolving where to probe
-
-const DEFAULT_HOST = "0.0.0.0";
-const DEFAULT_PORT = 8080;
-const MAX_PORT = 65536;
/**
- * Resolves where to probe, mirroring what config.ts, port.ts and host.ts resolve for the running
- * server. It reads the same environment variables and the same `[Network]` section of config.ini,
- * but imports none of those modules: loading them creates the data directory, writes a config
- * sample and can call process.exit(), none of which a healthcheck should do. The two readings are
- * held in agreement by the tests in healthcheck.spec.ts.
+ * Records where the server is listening so the docker healthcheck can probe it without resolving
+ * any configuration of its own. It writes the address that was actually bound rather than the one
+ * that was configured, and runs once the server is listening, so the files existing at all means
+ * the server got that far.
*/
-export function resolveHealthcheckTarget(env: NodeJS.ProcessEnv = process.env): HealthcheckTarget {
- const network = readNetworkSection(env);
+export function publishHealthcheckTarget(
+ dataDirPath: string,
+ address: string | AddressInfo | null,
+ overTls: boolean
+) {
+ const scheme = overTls ? "https" : "http";
+ const urlFile = path.join(dataDirPath, HEALTHCHECK_URL_FILE);
+ const socketFile = path.join(dataDirPath, HEALTHCHECK_SOCKET_FILE);
- return {
- https: resolveHttps(env.TRILIUM_NETWORK_HTTPS, network.https),
- port: resolvePort(env, network.port),
- host: env.TRILIUM_HOST || fromConfig(env.TRILIUM_NETWORK_HOST, network.host, DEFAULT_HOST)
- };
-}
-
-/** TRILIUM_PORT wins when set, as it does in port.ts, then whatever config.ts would report. */
-function resolvePort(env: NodeJS.ProcessEnv, iniValue: unknown) {
- const resolved = env.TRILIUM_PORT || fromConfig(env.TRILIUM_NETWORK_PORT, iniValue, "");
- const port = parseInt(resolved, 10);
-
- // port.ts exits on a port outside this range, so the server is not listening either way.
- return Number.isInteger(port) && port >= 0 && port < MAX_PORT ? port : DEFAULT_PORT;
-}
-
-function resolveHttps(envValue: string | undefined, iniValue: unknown) {
- if (envValue !== undefined) {
- return toBoolean(envValue);
+ if (address === null) {
+ return;
}
- return hasIniValue(iniValue) ? toBoolean(iniValue) : false;
-}
+ if (typeof address === "string") {
+ // A unix socket carries no host, so curl needs the path passed separately.
+ fs.writeFileSync(urlFile, `${scheme}://localhost${PROBE_PATH}`);
+ fs.writeFileSync(socketFile, address);
-/** Mirrors getConfigValue in config.ts: the environment variable wins even when it is empty. */
-function fromConfig(envValue: string | undefined, iniValue: unknown, fallback: string) {
- if (envValue !== undefined) {
- return envValue;
+ return;
}
- return hasIniValue(iniValue) ? String(iniValue) : fallback;
+ fs.writeFileSync(urlFile, `${scheme}://${probeHost(address)}:${address.port}${PROBE_PATH}`);
+ fs.rmSync(socketFile, { force: true });
}
-function hasIniValue(value: unknown) {
- return value !== undefined && value !== null && value !== "";
-}
-
-/** Mirrors transformBoolean in config.ts: "true"/"false" in any case, plus 1 and 0. */
-function toBoolean(value: unknown) {
- const text = String(value).toLowerCase().trim();
-
- if (text === "true") {
- return true;
+/** The address a probe on the same host should dial, given what the server bound. */
+function probeHost({ address, family }: AddressInfo) {
+ if (address === "0.0.0.0") {
+ return "127.0.0.1";
}
- if (text === "false") {
- return false;
+ if (address === "::" || address === "::0") {
+ return "[::1]";
}
- return value === "1" || value === 1;
+ return family === "IPv6" ? `[${address}]` : address;
}
-
-//#endregion
-
-//#region Reading config.ini
-
-const DATA_DIR_NAME = "trilium-data";
-
-function readNetworkSection(env: NodeJS.ProcessEnv): Record<string, unknown> {
- const iniPath = env.TRILIUM_CONFIG_INI_PATH || path.join(resolveDataDir(env), "config.ini");
-
- try {
- if (!fs.existsSync(iniPath)) {
- return {};
- }
-
- const section = ini.parse(fs.readFileSync(iniPath, "utf8")).Network;
-
- return section && typeof section === "object" ? section : {};
- } catch {
- // An unreadable config.ini leaves the defaults in place, which still probe localhost.
- return {};
- }
-}
-
-/** The read-only half of getTriliumDataDir in data_dir.ts, which creates directories as it goes. */
-function resolveDataDir(env: NodeJS.ProcessEnv) {
- if (env.TRILIUM_DATA_DIR) {
- return env.TRILIUM_DATA_DIR;
- }
-
- const homePath = path.join(os.homedir(), DATA_DIR_NAME);
- if (fs.existsSync(homePath)) {
- return homePath;
- }
-
- const appDataDir = platformAppDataDir(env);
-
- if (appDataDir && fs.existsSync(appDataDir)) {
- return path.join(appDataDir, DATA_DIR_NAME);
- }
-
- return homePath;
-}
-
-function platformAppDataDir(env: NodeJS.ProcessEnv) {
- const platform = os.platform();
-
- if (platform === "win32") {
- return env.APPDATA || null;
- }
- if (platform === "linux") {
- return path.join(os.homedir(), ".local", "share");
- }
- if (platform === "darwin") {
- return path.join(os.homedir(), "Library", "Application Support");
- }
-
- return null;
-}
-
-//#endregion
diff --git a/apps/server/src/www.ts b/apps/server/src/www.ts
index 93bb78bf9a..b2b36ce693 100644
--- a/apps/server/src/www.ts
+++ b/apps/server/src/www.ts
@@ -7,6 +7,7 @@ import tmp from "tmp";
import buildApp from "./app.js";
import config from "./services/config.js";
+import dataDir from "./services/data_dir.js";
import { startCpuProfiler, writeCpuProfile } from "./services/cpu_profiler.js";
import { registerOcrHandlers } from "./services/handlers.js";
import host from "./services/host.js";
@@ -14,6 +15,7 @@ import { registerServerLlmExtensions } from "./services/llm/index.js";
import port from "./services/port.js";
import { installProcessErrorHandlers, markAppReady } from "./services/process_errors.js";
import { isScriptingEnabled } from "./services/scripting_guard.js";
+import { publishHealthcheckTarget } from "./services/healthcheck.js";
import { getDbSize } from "./services/sql_init.js";
import { isHttpAttachableMessagingProvider } from "./services/ws_messaging_provider.js";
@@ -208,6 +210,9 @@ function startHttpServer(app: Express) {
} else {
getLog().info(`Listening on unix socket ${host}`);
}
+
+ publishHealthcheckTarget(
+ dataDir.TRILIUM_DATA_DIR, httpServer.address(), config.Network.https);
});
return httpServer;