Skip to content
Draft
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
Original file line number Diff line number Diff line change
Expand Up @@ -129,11 +129,11 @@ completion slot.

Mandatory agent labels keep a pool from taking unrelated workflows.
All generated workflows use their assigned pool. The admission proof covers
every compute and gate slot in the budget. It also rejects a workflow routed
to a pool with no agent, which Woodpecker would hold forever. Its pod backstop
also includes compute services, so partially started workflows cannot fill
every slot before a step can run. The legacy pool has zero slots and no agent
Deployment.
every compute and gate slot in the budget, the RAM workspace pools' included
whenever they have any. It also rejects a workflow routed to a pool with no
agent, which Woodpecker would hold forever. Its pod backstop also includes
compute services, so partially started workflows cannot fill every slot before
a step can run. The legacy pool has zero slots and no agent Deployment.

The reserve slightly reduces compute capacity. It buys predictable access for
short verdict checks without increasing the total CPU, memory, or ephemeral
Expand Down Expand Up @@ -388,6 +388,33 @@ stamping `publishedAt`, so `CIRamRouteStale` fires when the ConfigMap has not
changed for 15 minutes: the routing policy would otherwise keep applying the
last route it saw.

## RAM workspaces come from their own agents

Woodpecker creates each workflow's workspace claim from its agent's settings,
and the claim carries no workflow labels. The only way to give a workflow a RAM
workspace is therefore to run it on an agent whose claims ask for
`ci-workspace-ram`. Two more agent pools, `pr-ram` and `main-ram`, do exactly
that, with the 12Gi RAM workspace size; the routing policy above then keeps
each claim on the pool or moves it to NVMe.

A RAM agent runs only for a pool the admission budget gives slots, and those
slots come out of the ordinary pool beside it, so the compute total, the pods
backstop and the admission proof are unchanged. The budget gains the two pools
in the same change that routes work to them, so no slot sits idle on an agent
nothing routes to. Like every pool, each requires its own `ci-pool` label, so
it takes only the workflows the generator routes to it.

A RAM agent also waits, at every start, for the route published on the node's
current boot. The route ConfigMap survives a reboot, but the pool, its golden
snapshot and every claim on it do not. Until the publisher runs again, a
`ready` route from the previous boot would send new claims to a snapshot that
no longer exists, and they would sit Pending. The publisher records the node's
boot ID with every decision, and each RAM agent's init container,
`workspace-route-boot-gate`, holds the agent until the published boot ID is the
node's own, logging which boot the route it read belongs to. The gate checks
only that the route is current; its state still decides between RAM and NVMe.
A failing API read fails the init container instead of waiting silently.

## Workspaces do not accumulate

Each workflow gets a workspace claim on the `ci-workspace` storage class. The
Expand Down Expand Up @@ -502,8 +529,9 @@ kubelet eviction, whatever the queue says.
runbook in `packages/homelab/src/talos/liskov/README.md`
- Golden workspace clone policy:
`resources/woodpecker/workspace-clone-policy.ts`
- RAM workspace route publisher and routing policy:
- RAM workspace route publisher, routing policy and agent boot gate:
`resources/woodpecker/workspace-route.ts`
- RAM workspace agent pools: `resources/woodpecker/agent.ts`
- Golden refresh and snapshot:
`packages/temporal/src/activities/maintenance/ci-workspace-golden.ts`
- RAM golden claim, seed candidate, and snapshot:
Expand Down
14 changes: 13 additions & 1 deletion packages/homelab/src/cdk8s/src/misc/woodpecker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,19 @@ export const WOODPECKER_MAX_WORKFLOWS = CI_ADMISSION_BUDGET.legacyMaxWorkflows;

export type CiAgentPool = keyof typeof CI_ADMISSION_BUDGET.pools;

/** Every pool whose pods queue for compute quota: PR, main and maintenance. */
/**
* Pools whose agent creates RAM workspace claims instead of NVMe ones. An
* agent runs for each only while the budget gives it slots.
*/
export const CI_RAM_WORKSPACE_POOLS = [
"pr-ram",
"main-ram",
] as const satisfies readonly CiAgentPool[];

/**
* Every pool whose pods queue for compute quota: PR, main, their RAM
* workspace pools and maintenance.
*/
export const CI_COMPUTE_WORKFLOWS =
CI_ADMISSION_BUDGET.legacyMaxWorkflows +
queueWorkflows(CI_ADMISSION_BUDGET.pools, "default");
Expand Down
232 changes: 193 additions & 39 deletions packages/homelab/src/cdk8s/src/resources/woodpecker/agent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,37 @@ import { describe, expect, it } from "vitest";
import { App, Chart } from "cdk8s";
import { parse } from "yaml";
import { z } from "zod";
import { CI_AGENT_MAX_WORKFLOWS_LABEL } from "@shepherdjerred/homelab/cdk8s/src/misc/woodpecker.ts";
import {
CI_ADMISSION_BUDGET,
CI_AGENT_MAX_WORKFLOWS_LABEL,
} from "@shepherdjerred/homelab/cdk8s/src/misc/woodpecker.ts";
import { createWoodpeckerAgent } from "./agent.ts";
import { CI_ADMISSION_BUDGET } from "@shepherdjerred/homelab/cdk8s/src/misc/woodpecker.ts";
import { workspaceRouteBootGateScript } from "./workspace-route.ts";

const ContainerSchema = z.object({
name: z.string(),
args: z.array(z.string()).optional(),
securityContext: z
.object({
allowPrivilegeEscalation: z.boolean().optional(),
readOnlyRootFilesystem: z.boolean().optional(),
seccompProfile: z.object({ type: z.string() }).optional(),
})
.loose()
.optional(),
volumeMounts: z
.array(z.object({ mountPath: z.string(), name: z.string() }))
.optional(),
env: z
.array(
z.object({
name: z.string(),
value: z.string().optional(),
valueFrom: z.unknown().optional(),
}),
)
.optional(),
});

const DeploymentSchema = z.object({
kind: z.literal("Deployment"),
Expand All @@ -18,83 +46,154 @@ const DeploymentSchema = z.object({
template: z.object({
spec: z.object({
serviceAccountName: z.string(),
automountServiceAccountToken: z.boolean().optional(),
affinity: z.unknown(),
containers: z.array(
z.object({
env: z.array(
z.object({
name: z.string(),
value: z.string().optional(),
valueFrom: z.unknown().optional(),
}),
),
}),
),
initContainers: z.array(ContainerSchema).optional(),
containers: z.array(ContainerSchema),
volumes: z
.array(
z.object({ name: z.string(), emptyDir: z.unknown().optional() }),
)
.optional(),
}),
}),
}),
});

function agents() {
const RoleSchema = z.object({
kind: z.literal("Role"),
metadata: z.object({ name: z.string(), namespace: z.string() }),
rules: z.array(z.object({ resources: z.array(z.string()) }).loose()),
});

/**
* A budget that gives the RAM workspace pools slots, carved out of the
* ordinary pools beside them, to exercise their agents. The routing change
* that sends work to them adds the same pools to the real budget.
*/
const RAM_POOLS_BUDGET: typeof CI_ADMISSION_BUDGET = {
...CI_ADMISSION_BUDGET,
pools: {
...CI_ADMISSION_BUDGET.pools,
pr: { maxWorkflows: 8, queue: "default" },
"pr-ram": { maxWorkflows: 4, queue: "default" },
main: { maxWorkflows: 8, queue: "default" },
"main-ram": { maxWorkflows: 2, queue: "default" },
},
};

function manifests(budget = RAM_POOLS_BUDGET): unknown[] {
const app = new App();
createWoodpeckerAgent(
new Chart(app, "woodpecker", { disableResourceNameHashes: true }),
budget,
);
return app
.synthYaml()
.split(/^---$/m)
.map((document): unknown => parse(document))
.map((document): unknown => parse(document));
}

function agents(budget = RAM_POOLS_BUDGET) {
return manifests(budget)
.filter(
(document) =>
z.object({ kind: z.literal("Deployment") }).safeParse(document).success,
)
.map((document) => DeploymentSchema.parse(document));
}

function agent(pool: string) {
const found = agents().find(
(entry) => entry.metadata.name === `woodpecker-woodpecker-agent-${pool}`,
);
if (found === undefined) throw new Error(`missing ${pool} agent`);
return found;
}

function environment(
agent: z.infer<typeof DeploymentSchema>,
deployment: z.infer<typeof DeploymentSchema>,
): Map<string, string | undefined> {
const container = agent.spec.template.spec.containers[0];
const container = deployment.spec.template.spec.containers[0];
if (container === undefined) throw new Error("agent has no container");
return new Map(container.env.map((entry) => [entry.name, entry.value]));
return new Map(
(container.env ?? []).map((entry) => [entry.name, entry.value]),
);
}

describe("dedicated CI agent pools", () => {
it("runs a RAM workspace agent only for a pool the budget gives slots", () => {
const names = (budget: typeof CI_ADMISSION_BUDGET) =>
agents(budget)
.map((deployment) => deployment.metadata.name)
.toSorted();
const ordinary = [
"completion",
"main",
"maintenance",
"pr",
"pr-light",
"review",
].map((pool) => `woodpecker-woodpecker-agent-${pool}`);
const withoutRam = {
...CI_ADMISSION_BUDGET,
pools: {
pr: CI_ADMISSION_BUDGET.pools.pr,
"pr-light": CI_ADMISSION_BUDGET.pools["pr-light"],
main: CI_ADMISSION_BUDGET.pools.main,
maintenance: CI_ADMISSION_BUDGET.pools.maintenance,
review: CI_ADMISSION_BUDGET.pools.review,
completion: CI_ADMISSION_BUDGET.pools.completion,
},
};
expect(names(withoutRam)).toEqual(ordinary);
expect(names(RAM_POOLS_BUDGET)).toEqual(
[
...ordinary,
"woodpecker-woodpecker-agent-main-ram",
"woodpecker-woodpecker-agent-pr-ram",
].toSorted(),
);
});

it("uses only the mandatory-label pools after the legacy drain", () => {
const deployments = agents();
expect(deployments.map((entry) => entry.metadata.name).toSorted()).toEqual(
Object.keys(CI_ADMISSION_BUDGET.pools)
Object.keys(RAM_POOLS_BUDGET.pools)
.map((pool) => `woodpecker-woodpecker-agent-${pool}`)
.toSorted(),
);
for (const [pool, cap, queue, volume] of [
["pr", "12", "default", "32Gi"],
for (const [pool, cap, queue, storageClass, volume] of [
["pr", "8", "default", "ci-workspace", "32Gi"],
["pr-ram", "4", "default", "ci-workspace-ram", "12Gi"],
// Light checks clone the golden snapshot too, but queue in their own
// reserved ClusterQueue.
["pr-light", "4", "ci-light", "32Gi"],
["main", "10", "default", "32Gi"],
["pr-light", "4", "ci-light", "ci-workspace", "32Gi"],
["main", "8", "default", "ci-workspace", "32Gi"],
["main-ram", "2", "default", "ci-workspace-ram", "12Gi"],
// Maintenance workspaces clone the golden snapshot, so they keep the
// compute workspace size rather than the gate's.
["maintenance", "1", "default", "32Gi"],
["review", "3", "ci-gates", "1G"],
["completion", "1", "ci-gates", "1G"],
["maintenance", "1", "default", "ci-workspace", "32Gi"],
["review", "3", "ci-gates", "ci-workspace", "1G"],
["completion", "1", "ci-gates", "ci-workspace", "1G"],
] as const) {
const agent = deployments.find(
(entry) =>
entry.metadata.name === `woodpecker-woodpecker-agent-${pool}`,
);
if (agent === undefined) throw new Error(`missing ${pool} agent`);
const env = environment(agent);
const deployment = agent(pool);
const env = environment(deployment);
expect(env.get("WOODPECKER_MAX_WORKFLOWS")).toBe(cap);
// The label kube-state-metrics exports for the disconnected-agent alert
// must carry the same slot count the agent runs with.
expect(agent.metadata.labels?.[CI_AGENT_MAX_WORKFLOWS_LABEL]).toBe(cap);
expect(deployment.metadata.labels?.[CI_AGENT_MAX_WORKFLOWS_LABEL]).toBe(
cap,
);
expect(env.get("WOODPECKER_AGENT_LABELS")).toBe(
`!ci-pool=${pool},kueue.x-k8s.io/priority-class=*`,
);
expect(env.get("WOODPECKER_BACKEND_K8S_POD_LABELS")).toBe(
JSON.stringify({ "kueue.x-k8s.io/queue-name": queue }),
);
expect(env.get("WOODPECKER_BACKEND_K8S_STORAGE_CLASS")).toBe(
storageClass,
);
expect(env.get("WOODPECKER_BACKEND_K8S_VOLUME_SIZE")).toBe(volume);
}
const legacy = deployments.find(
Expand All @@ -104,11 +203,11 @@ describe("dedicated CI agent pools", () => {
});

it("keeps every agent on liskov with the existing native-secret and pod guards", () => {
for (const agent of agents()) {
const env = environment(agent);
expect(agent.spec.replicas).toBe(1);
expect(agent.spec.strategy.type).toBe("Recreate");
expect(agent.spec.template.spec.affinity).toEqual({
for (const deployment of agents()) {
const env = environment(deployment);
expect(deployment.spec.replicas).toBe(1);
expect(deployment.spec.strategy.type).toBe("Recreate");
expect(deployment.spec.template.spec.affinity).toEqual({
nodeAffinity: {
requiredDuringSchedulingIgnoredDuringExecution: {
nodeSelectorTerms: [
Expand All @@ -125,7 +224,7 @@ describe("dedicated CI agent pools", () => {
},
},
});
expect(agent.spec.template.spec.serviceAccountName).toBe(
expect(deployment.spec.template.spec.serviceAccountName).toBe(
"woodpecker-agent",
);
expect(env.get("WOODPECKER_BACKEND_K8S_NAMESPACE")).toBe("woodpecker-ci");
Expand All @@ -140,4 +239,59 @@ describe("dedicated CI agent pools", () => {
);
}
});

it("gates RAM workspace agents on the route published for this boot, and leaves the others ungated", () => {
for (const pool of ["pr-ram", "main-ram"]) {
const { spec } = agent(pool).spec.template;
expect(spec.automountServiceAccountToken).toBe(true);
expect(spec.initContainers).toHaveLength(1);
const [gate] = spec.initContainers ?? [];
expect(gate?.name).toBe("workspace-route-boot-gate");
expect(gate?.args).toEqual([workspaceRouteBootGateScript()]);
expect(gate?.securityContext).toMatchObject({
allowPrivilegeEscalation: false,
readOnlyRootFilesystem: true,
seccompProfile: { type: "RuntimeDefault" },
});
// kubectl caches discovery under /tmp, an emptyDir on a read-only root.
const tmp = gate?.volumeMounts?.find(
(mount) => mount.mountPath === "/tmp",
);
expect(
spec.volumes?.find((volume) => volume.name === tmp?.name)?.emptyDir,
).toBeDefined();
expect(spec.containers[0]?.securityContext?.seccompProfile).toEqual({
type: "RuntimeDefault",
});
}
for (const pool of ["pr", "main", "review", "completion"]) {
const { spec } = agent(pool).spec.template;
expect(spec.initContainers).toBeUndefined();
expect(spec.volumes).toBeUndefined();
expect(
spec.containers[0]?.securityContext?.seccompProfile,
).toBeUndefined();
}
});

it("grants the agent only a read of the route ConfigMap, by name", () => {
const role = manifests()
.filter(
(document) =>
z.object({ kind: z.literal("Role") }).safeParse(document).success,
)
.map((document) => RoleSchema.parse(document))
.find((entry) => entry.metadata.name === "woodpecker-agent");
expect(role?.metadata.namespace).toBe("woodpecker-ci");
expect(
role?.rules.filter((rule) => rule.resources.includes("configmaps")),
).toEqual([
{
apiGroups: [""],
resources: ["configmaps"],
resourceNames: ["ci-workspace-route"],
verbs: ["get"],
},
]);
});
});
Loading