Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions apps/dokploy/__test__/nomad/nomad-env-substitution.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { parseComposeToNomadServices } from "@nomploy/server/utils/builders/nomad-parser";
import { describe, expect, it } from "vitest";

// Compose interpolation happens on the raw YAML before parsing; assert through the
// parsed service env so we test what actually reaches the Nomad job.
const envOf = (value: string, vars: Record<string, string>) => {
const compose = `services:\n web:\n image: nginx\n environment:\n V: "${value}"\n`;
return parseComposeToNomadServices(compose, vars)[0]?.env.V;
};

describe("nomad parser — compose variable interpolation", () => {
it("keeps the existing ${VAR}, $VAR and default forms", () => {
expect(envOf("${A}", { A: "x" })).toBe("x");
expect(envOf("$A-suffix", { A: "x" })).toBe("x-suffix");
expect(envOf("${A}", {})).toBe("");
expect(envOf("${A:-d}", { A: "" })).toBe("d");
expect(envOf("${A-d}", { A: "" })).toBe("");
expect(envOf("${A-d}", {})).toBe("d");
expect(envOf("${A:-d}", { A: "x" })).toBe("x");
});

it("resolves nested defaults inner-first", () => {
expect(envOf("${A:-${B}}", { B: "b" })).toBe("b");
expect(envOf("${A:-${B:-c}}", {})).toBe("c");
expect(envOf("${A:-${B:-c}}", { A: "a", B: "b" })).toBe("a");
expect(envOf("${A:-pre-${B}-post}", { B: "b" })).toBe("pre-b-post");
});

it("${VAR:?msg} fails when unset or empty", () => {
expect(() => envOf("${A:?A is required}", {})).toThrow(
"Required variable A is missing a value: A is required",
);
expect(() => envOf("${A:?A is required}", { A: "" })).toThrow(
"A is required",
);
expect(envOf("${A:?A is required}", { A: "x" })).toBe("x");
});

it("${VAR?msg} fails only when unset", () => {
expect(() => envOf("${A?need A}", {})).toThrow("need A");
expect(envOf("${A?need A}", { A: "" })).toBe("");
expect(envOf("${A?}", { A: "x" })).toBe("x");
expect(() => envOf("${A?}", {})).toThrow(
"Required variable A is missing a value",
);
});

it("leaves non-variable ${…} text alone", () => {
expect(envOf("${}", {})).toBe("${}");
});
});
57 changes: 57 additions & 0 deletions apps/dokploy/__test__/nomad/nomad-remote-compose.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { beforeEach, describe, expect, it, vi } from "vitest";

// A git-sourced compose on a REMOTE server: the clone lives on that server, so the
// builder must read the compose file over SSH (execAsyncRemote) instead of the
// stored composeFile snapshot (which is "" for git sources).
const execAsyncRemote = vi.fn();
vi.mock("@nomploy/server/utils/process/execAsync", () => ({
execAsync: vi.fn(async () => ({ stdout: "", stderr: "" })),
execAsyncRemote: (serverId: string, command: string) =>
execAsyncRemote(serverId, command),
}));

import { getBuildNomadCommand } from "@nomploy/server/utils/builders/nomad";

const compose = {
appName: "starring",
serverId: "srv-1",
sourceType: "github",
composePath: "./docker-compose.dokploy.yml",
composeFile: "",
env: "",
environment: { project: { env: "" }, env: null },
mounts: [],
domains: [],
} as any;

const decodeJob = (cmd: string) => {
const match = cmd.match(/echo "([A-Za-z0-9+/=]+)" \| base64 -d/);
return Buffer.from(match?.[1] ?? "", "base64").toString();
};

describe("nomad builder — remote git compose", () => {
beforeEach(() => {
execAsyncRemote.mockReset();
});

it("reads the cloned compose file from the remote server", async () => {
execAsyncRemote.mockResolvedValue({
stdout: "services:\n web:\n image: ghcr.io/pipozzz/starring\n",
stderr: "",
});
const cmd = await getBuildNomadCommand(compose);
const [serverId, command] = execAsyncRemote.mock.calls[0] ?? [];
expect(serverId).toBe("srv-1");
expect(command).toMatch(
/^cat .*starring\/code\/docker-compose\.dokploy\.yml/,
);
expect(decodeJob(cmd)).toContain("ghcr.io/pipozzz/starring");
});

it("throws a clear error naming the path and server when unreadable", async () => {
execAsyncRemote.mockRejectedValue(new Error("No such file"));
await expect(getBuildNomadCommand(compose)).rejects.toThrow(
/docker-compose\.dokploy\.yml.*on server srv-1/,
);
});
});
86 changes: 69 additions & 17 deletions packages/server/src/utils/builders/nomad-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -508,21 +508,73 @@ const substituteEnvVars = (
content: string,
envVars: Record<string, string>,
): string => {
// Supports `$VAR`, `${VAR}`, and the default forms `${VAR:-default}` (default
// when VAR is unset OR empty) and `${VAR-default}` (default only when unset) —
// a very common compose pattern (e.g. `TZ=${TZ:-UTC}`). The old regex captured
// the `:-default` suffix but the callback discarded it, substituting "" instead
// of the default — which broke apps that relied on it (an empty TZ made a cron
// library throw "invalid date" and crash the container on boot).
return content.replace(
/\$\{([A-Za-z_][A-Za-z0-9_]*)(?:(:?-)([^}]*))?\}|\$([A-Za-z_][A-Za-z0-9_]*)/g,
(_match, braced, op, defaultVal, bare) => {
const varName = braced || bare;
const val = envVars[varName];
if (op === ":-")
return val !== undefined && val !== "" ? val : defaultVal;
if (op === "-") return val !== undefined ? val : defaultVal;
return val ?? "";
},
);
// Supports `$VAR`, `${VAR}`, the default forms `${VAR:-default}` (default when
// VAR is unset OR empty) and `${VAR-default}` (default only when unset) — e.g.
// `TZ=${TZ:-UTC}` — and the required forms `${VAR:?msg}` (error when unset or
// empty) and `${VAR?msg}` (error only when unset), which fail the deploy with
// msg like docker compose does. The default/message is itself interpolated, so
// nested defaults such as `${A:-${B:-x}}` resolve. A scanner (not a regex) so the
// closing brace of a nested `${…}` doesn't end the outer one.
const bareVar = /\$([A-Za-z_][A-Za-z0-9_]*)/y;
let out = "";
let i = 0;
while (i < content.length) {
if (content[i] !== "$") {
out += content[i++];
continue;
}
if (content[i + 1] === "{") {
// Find the matching `}` (brace depth, so nested `${…}` stay inside).
let depth = 1;
let j = i + 2;
for (; j < content.length; j++) {
if (content[j] === "{") depth++;
else if (content[j] === "}" && --depth === 0) break;
}
if (depth > 0) {
// Unterminated `${` — leave the rest verbatim.
out += content.slice(i);
break;
}
const expr = content
.slice(i + 2, j)
.match(/^([A-Za-z_][A-Za-z0-9_]*)(?:(:?[-?])([\s\S]*))?$/);
if (!expr?.[1]) {
// Not a variable reference (e.g. `${}`) — keep it literally.
out += content.slice(i, j + 1);
i = j + 1;
continue;
}
i = j + 1;
const [, name, op, arg = ""] = expr;
const val = envVars[name];
const isSet = val !== undefined;
const isSetNonEmpty = isSet && val !== "";
if (op === ":-" || op === "-") {
out += (op === ":-" ? isSetNonEmpty : isSet)
? val
: substituteEnvVars(arg, envVars);
} else if (op === ":?" || op === "?") {
if (!(op === ":?" ? isSetNonEmpty : isSet)) {
const msg = substituteEnvVars(arg, envVars);
throw new Error(
`Required variable ${name} is missing a value${msg ? `: ${msg}` : ""}`,
);
}
out += val;
} else {
out += val ?? "";
}
continue;
}
bareVar.lastIndex = i;
const bare = bareVar.exec(content);
if (bare?.[1]) {
out += envVars[bare[1]] ?? "";
i = bareVar.lastIndex;
} else {
out += content[i++];
}
}
return out;
};
26 changes: 22 additions & 4 deletions packages/server/src/utils/builders/nomad.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@ import {
} from "@nomploy/server/services/cert-resolver";
import type { Domain } from "@nomploy/server/services/domain";
import type { InferResultType } from "@nomploy/server/types/with";
import { quote } from "shell-quote";
import {
CROWDSEC_MIDDLEWARE_REF,
isCrowdsecPerServiceActive,
} from "../../setup/crowdsec-flag";
import { allServers, readCluster } from "../../setup/nomad-mesh";
import { encodeBase64, getEnvironmentVariablesObject } from "../docker/utils";
import { execAsyncRemote } from "../process/execAsync";
import { parseComposeToNomadServices } from "./nomad-parser";

export type NomadComposeNested = InferResultType<
Expand Down Expand Up @@ -278,16 +280,32 @@ export const getBuildNomadCommand = async (
// of truth (edited in the panel). For a GIT source the real compose lives in the
// freshly-cloned repo at composePath — the stored composeFile is a stale snapshot,
// so a `git push` (e.g. removing a service) would otherwise never change the
// deployed job. Read the cloned file instead. (Control-plane deploys only; a remote
// server's clone isn't on this filesystem — fall back to the stored copy there.)
// deployed job. Read the cloned file instead — locally for control-plane deploys,
// over SSH for a remote server (its clone isn't on this filesystem, and the stored
// snapshot is never filled for git sources, so falling back to it parsed "").
const relComposePath =
compose.sourceType === "raw"
? "docker-compose.yml"
: compose.composePath || "docker-compose.yml";
let composeFile = compose.composeFile;
if (compose.sourceType !== "raw" && !compose.serverId) {
if (compose.sourceType !== "raw") {
const clonedPath = join(projectPath, relComposePath);
if (existsSync(clonedPath)) composeFile = readFileSync(clonedPath, "utf8");
if (compose.serverId) {
const { stdout } = await execAsyncRemote(
compose.serverId,
`cat ${quote([clonedPath])}`,
).catch(() => ({ stdout: "" }));
if (stdout.trim()) composeFile = stdout;
} else if (existsSync(clonedPath)) {
composeFile = readFileSync(clonedPath, "utf8");
}
if (!composeFile?.trim()) {
throw new Error(
`Compose file "${relComposePath}" not found or empty at ${clonedPath}` +
(compose.serverId ? ` on server ${compose.serverId}` : "") +
" — check the compose path and that the repository was cloned.",
);
}
}

// Native Nomad jobspec passthrough: if the source is already a Nomad HCL job
Expand Down
Loading