Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Combine AWS task restarts with candidate deployment (#1027)

Regan Bellc2730476d45e
diff --git a/cli/src/backends/aws.ts b/cli/src/backends/aws.ts
index 40cf91d66..d5b4b6020 100644
--- a/cli/src/backends/aws.ts
+++ b/cli/src/backends/aws.ts
@@ -125,6 +125,7 @@ export interface AwsUpOpts {
buildFromPath?: string;
imageLabel?: string;
only?: string[];
+ restart?: string[];
sandboxDir?: string;
envFile?: string;
buildOnly?: boolean;
@@ -1758,6 +1759,7 @@ function reportTaskChanges(
services: string[],
images: Record<string, string>,
arns: Record<string, string>,
+ restart: ReadonlySet<string> = new Set(),
): Array<{ service: string; task: EcsTaskDefinition; changed: boolean }> {
const desired = services.map((service) => ({
service,
@@ -1770,7 +1772,8 @@ function reportTaskChanges(
`${item.service}: ${changes.length ? `${changes.length} task-definition change${changes.length === 1 ? "" : "s"}` : "no task-definition change"}`,
);
if (changes.length) note(JSON.stringify({ service: item.service, changes }, null, 2));
- return { service: item.service, task: item.task, changed: changes.length > 0 };
+ if (restart.has(item.service)) step(`${item.service}: restart requested with the deployment`);
+ return { service: item.service, task: item.task, changed: changes.length > 0 || restart.has(item.service) };
});
}
@@ -1897,6 +1900,11 @@ export async function awsUp(config: QmConfig, _configDir: string, opts: AwsUpOpt
}
const plugins = new Map(topology.plugins.map((plugin) => [plugin.name, plugin]));
const services = opts.only ?? topology.workloads;
+ const restart = new Set(opts.restart ?? []);
+ if (restart.size && opts.buildOnly) throw new CliError("--restart cannot be used with --build-only");
+ for (const service of restart) {
+ if (!services.includes(service)) throw new CliError(`--restart workload ${service} is not selected for deployment`);
+ }
for (const service of services) workloadArchitecture(config, service);
if (opts.buildOnly && opts.candidate) throw new CliError("--build-only and --candidate are mutually exclusive");
if (opts.candidate && opts.buildFrom) throw new CliError("--candidate and --build-from are mutually exclusive");
@@ -1991,7 +1999,7 @@ export async function awsUp(config: QmConfig, _configDir: string, opts: AwsUpOpt
}
images[service] = plannedWorkloadImage(config, service, plugins.get(service));
}
- reportTaskChanges(config, services, images, arns);
+ reportTaskChanges(config, services, images, arns, restart);
for (const service of services) {
step(`${service}: desired count ${before.counts[service] ?? 0} → ${workloadDesiredCount(config, service)}`);
}
@@ -2006,7 +2014,9 @@ export async function awsUp(config: QmConfig, _configDir: string, opts: AwsUpOpt
} else {
step("deployment layer: preserved (no sandbox directory selected for core)");
}
- note(`Plan only. Re-run \`qm up${opts.candidate ? ` --candidate ${opts.candidate}` : ""} --yes\` to deploy.`);
+ note(
+ `Plan only. Re-run \`qm up${opts.candidate ? ` --candidate ${opts.candidate}` : ""}${restart.size ? ` --restart ${[...restart].join(",")}` : ""} --yes\` to deploy.`,
+ );
return;
}
const lease = acquireLease(aws);
@@ -2105,7 +2115,7 @@ export async function awsUp(config: QmConfig, _configDir: string, opts: AwsUpOpt
images[service] = publishWorkloadImage(config, service, plugins.get(service), stagingLabel, opts);
}
}
- const desired = reportTaskChanges(config, services, images, arns);
+ const desired = reportTaskChanges(config, services, images, arns, restart);
const targets: Record<string, string> = {};
for (const item of desired) {
if (!item.changed) {
diff --git a/cli/src/backends/registry.ts b/cli/src/backends/registry.ts
index 7144118bd..ef2e21d36 100644
--- a/cli/src/backends/registry.ts
+++ b/cli/src/backends/registry.ts
@@ -79,16 +79,16 @@ const buildFromOptions = (
};
};
-const onlyOptions = (flags: Readonly<Record<string, string | boolean>>): string[] | undefined => {
- const raw = stringFlag(flags, "only");
+const workloadOptions = (flags: Readonly<Record<string, string | boolean>>, flag = "only"): string[] | undefined => {
+ const raw = stringFlag(flags, flag);
if (raw === undefined) return undefined;
const names = raw
.split(",")
.map((name) => name.trim())
.filter(Boolean);
- if (names.length === 0) throw new CliError(`--only was given no components (e.g. --only core,web-ui)`);
+ if (names.length === 0) throw new CliError(`--${flag} was given no components (e.g. --${flag} core,web-ui)`);
const duplicate = names.find((name, index) => names.indexOf(name) !== index);
- if (duplicate) throw new CliError(`--only lists ${duplicate} more than once`);
+ if (duplicate) throw new CliError(`--${flag} lists ${duplicate} more than once`);
return names;
};
@@ -152,7 +152,7 @@ const fly: HostingProvider = {
scaffold: flyScaffold,
upFlags: ["build-from", "only", "image-label", "image-from", "image-repo-prefix", "build-only"],
upOptions: (_ctx, flags, dryRun) => {
- const only = onlyOptions(flags);
+ const only = workloadOptions(flags);
const imageFrom = stringFlag(flags, "image-from");
const imageLabel = stringFlag(flags, "image-label");
const imageRepoPrefix = stringFlag(flags, "image-repo-prefix");
@@ -239,14 +239,25 @@ const aws: HostingProvider = {
"delete-task-definitions": (ctx) => deleteAwsTaskDefinitions(ctx.config),
},
scaffold: awsScaffold,
- upFlags: ["build-from", "only", "yes", "image-label", "build-only", "candidate", "candidate-out", "inactive"],
+ upFlags: [
+ "build-from",
+ "only",
+ "yes",
+ "image-label",
+ "build-only",
+ "candidate",
+ "candidate-out",
+ "inactive",
+ "restart",
+ ],
upOptions: (ctx, flags, dryRun) => {
- const only = onlyOptions(flags);
+ const only = workloadOptions(flags);
const unknown = only?.filter((name) => !ctx.config.aws?.services[name]) ?? [];
if (unknown.length) throw new CliError(`--only has unknown AWS workload(s): ${unknown.join(", ")}`);
const imageLabel = stringFlag(flags, "image-label");
const candidate = stringFlag(flags, "candidate");
const candidateOut = stringFlag(flags, "candidate-out");
+ const restart = workloadOptions(flags, "restart");
return {
dryRun,
yes: flags["yes"] === true,
@@ -256,6 +267,7 @@ const aws: HostingProvider = {
...(imageLabel ? { imageLabel } : {}),
...(candidate ? { candidate } : {}),
...(candidateOut ? { candidateOut } : {}),
+ ...(restart ? { restart } : {}),
...(only ? { only } : {}),
};
},
@@ -270,6 +282,7 @@ const aws: HostingProvider = {
...(opts.buildOnly ? { buildOnly: true } : {}),
...(opts.candidate ? { candidate: opts.candidate } : {}),
...(opts.candidateOut ? { candidateOut: opts.candidateOut } : {}),
+ ...(opts.restart ? { restart: opts.restart } : {}),
...(opts.inactive ? { inactive: true } : {}),
...(opts.only ? { only: opts.only } : {}),
sandboxDir: ctx.sandboxDir,
diff --git a/cli/src/backends/types.ts b/cli/src/backends/types.ts
index d909ee0a0..6e626e39c 100644
--- a/cli/src/backends/types.ts
+++ b/cli/src/backends/types.ts
@@ -7,6 +7,7 @@ export interface BackendUpOptions {
buildFromPath?: string;
imageLabel?: string;
only?: string[];
+ restart?: string[];
imageFrom?: string;
imageRepoPrefix?: string;
buildOnly?: boolean;
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 71887957b..eb237a24a 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -126,6 +126,7 @@ ${bold("DEPLOY (operator)")} ${dim("— runs in the deployment directory")}
--candidate-out <file> build immutable AWS images and write their manifest
--candidate <file> snapshot, migrate, and deploy exact AWS candidate images
--inactive deploy that candidate before this stack owns public DNS (AWS only)
+ --restart <workloads> replace selected AWS tasks even when their definition is unchanged
--dry-run resolve the config + report the plan, change nothing
plan an alias for up --dry-run
migrate --candidate <file> --yes run only an AWS candidate's DB migrations in its target network
diff --git a/cli/test/aws.test.ts b/cli/test/aws.test.ts
index 6114a126c..2465f240b 100644
--- a/cli/test/aws.test.ts
+++ b/cli/test/aws.test.ts
@@ -354,7 +354,9 @@ else if (a.includes("ecs list-service-deployments")) {
const service = s.services[name];
const revision = "service-revision-for-" + String(service?.deploymentId || "").replace(/^ecs-svc\\//, "");
const status = (s.blueGreenPolls || 0) === 1 ? "PENDING" : (s.blueGreenPolls || 0) <= ${JSON.stringify(opts.blueGreenBakePolls ?? 0)} ? "IN_PROGRESS" : "SUCCESSFUL";
- console.log(JSON.stringify({ serviceDeployments: service ? [{ targetServiceRevisionArn: "arn:aws:ecs:us-west-2:123456789012:service-revision/acme-qm/" + name + "/" + revision, status, createdAt: 1700000000000 + s.revision }] : [] }));
+ const prior = service?.previousTaskDefinition ? [{ targetServiceRevisionArn: "arn:aws:ecs:us-west-2:123456789012:service-revision/acme-qm/" + name + "/previous", status: "SUCCESSFUL", createdAt: 1700000000000 }] : [];
+ const current = service && (s.blueGreenPolls || 0) !== 1 ? [{ targetServiceRevisionArn: "arn:aws:ecs:us-west-2:123456789012:service-revision/acme-qm/" + name + "/" + revision, status, createdAt: 1700000000000 + s.revision }] : [];
+ console.log(JSON.stringify({ serviceDeployments: [...prior, ...current] }));
}
else if (a.includes("ecs describe-service-revisions")) {
const start = args.indexOf("--service-revision-arns") + 1;
@@ -363,7 +365,7 @@ else if (a.includes("ecs describe-service-revisions")) {
console.log(JSON.stringify({ serviceRevisions: arns.flatMap((arn) => {
const name = arn.split("/").at(-2);
const service = name ? s.services[name] : undefined;
- return service ? [{ serviceRevisionArn: arn, taskDefinition: service.taskDefinition }] : [];
+ return service ? [{ serviceRevisionArn: arn, taskDefinition: arn.endsWith("/previous") ? service.previousTaskDefinition : service.taskDefinition }] : [];
}) }));
}
else if (a.includes("ecs list-tasks")) console.log(JSON.stringify({ taskArns: process.env.AWS_FAKE_NO_RUNNING_TASK ? [] : [...(process.env.AWS_FAKE_LARGE_ROLLOUT ? Array.from({ length: 100 }, (_, i) => "arn:aws:ecs:us-west-2:123456789012:task/old-core-" + i) : []), "arn:aws:ecs:us-west-2:123456789012:task/live-core"] }));
@@ -395,6 +397,7 @@ else if (a.includes("ecs update-service")) {
if (!${JSON.stringify(opts.ignoreUpdate ?? false)} && args.includes("--desired-count")) service.desiredCount = Number(after("--desired-count"));
if (!${JSON.stringify(opts.ignoreUpdate ?? false)}) service.deploymentId = "ecs-svc/" + name + "-" + (++s.revision);
s.updated = true;
+ s.blueGreenPolls = 0;
if (${JSON.stringify(opts.failFirstUpdateAfterMutation ?? false)} && !s.failedFirstUpdate) {
s.failedFirstUpdate = true;
save();
@@ -1354,6 +1357,45 @@ test("a no-op re-deploy records no manifest", async () => {
}
});
+test("AWS up coalesces a requested restart into one deployment even when the task is unchanged", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "qm-aws-restart-"));
+ const dockerBin = join(dir, "docker");
+ writeFileSync(dockerBin, `#!/usr/bin/env node\nconsole.log("Digest: sha256:${"a".repeat(64)}");\n`);
+ chmodSync(dockerBin, 0o755);
+ const single = oneServiceConfig();
+ const fake = statefulAws(dir, single, {}, { blueGreenBakePolls: 3 });
+ const priorPath = process.env.PATH;
+ process.env.PATH = `${dir}:${priorPath}`;
+ try {
+ await awsUp(single, dir, { yes: true });
+ const first = JSON.parse(readFileSync(fake.state, "utf8"));
+ const firstId = first.dynamo["deployment/current"].manifestId.S;
+ const previous = JSON.parse(first.dynamo[`deployment/manifest/${firstId}`].manifest.S);
+ writeFileSync(fake.log, "");
+ await awsUp(single, dir, { dryRun: true, restart: ["core"] });
+ assert.doesNotMatch(readFileSync(fake.log, "utf8"), /ecs (?:register-task-definition|update-service)/);
+ writeFileSync(fake.log, "");
+ await awsUp(single, dir, { yes: true, restart: ["core"] });
+ const second = JSON.parse(readFileSync(fake.state, "utf8"));
+ const nextId = second.dynamo["deployment/current"].manifestId.S;
+ const next = JSON.parse(second.dynamo[`deployment/manifest/${nextId}`].manifest.S);
+ assert.notEqual(nextId, firstId);
+ assert.notEqual(next.tasks.core, previous.tasks.core);
+ assert.deepEqual(next.imageProvenance, previous.imageProvenance);
+ const calls = readFileSync(fake.log, "utf8");
+ assert.equal(calls.match(/ecs register-task-definition/g)?.length, 1);
+ assert.equal(calls.match(/ecs update-service/g)?.length, 1);
+ assert.ok((calls.match(/ecs list-service-deployments/g)?.length ?? 0) >= 4);
+ assert.ok(calls.lastIndexOf("ecs list-service-deployments") < calls.lastIndexOf("dynamodb transact-write-items"));
+ await assert.rejects(() => awsUp(single, dir, { yes: true, restart: ["missing"] }), /not selected/);
+ await assert.rejects(() => awsUp(single, dir, { buildOnly: true, restart: ["core"] }), /cannot be used/);
+ } finally {
+ process.env.PATH = priorPath;
+ fake.restore();
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
test("AWS up renews the deploy lease with a holder-conditioned update while it runs", async () => {
const dir = mkdtempSync(join(tmpdir(), "qm-aws-lease-renew-"));
const dockerBin = join(dir, "docker");
diff --git a/cli/test/providers.test.ts b/cli/test/providers.test.ts
index bfa006f8e..8484a6544 100644
--- a/cli/test/providers.test.ts
+++ b/cli/test/providers.test.ts
@@ -28,6 +28,7 @@ test("the hosting provider registry owns target discovery and lifecycle capabili
"candidate",
"candidate-out",
"inactive",
+ "restart",
]);
});