diff --git a/.clomonitor.yml b/.clomonitor.yml new file mode 100644 index 000000000..26444486e --- /dev/null +++ b/.clomonitor.yml @@ -0,0 +1,8 @@ +# CLOMonitor metadata file, read when CLOMonitor lints this repository: +# https://clomonitor.io/projects/cncf/cozystack +# Format: https://github.com/cncf/clomonitor/blob/main/docs/metadata/.clomonitor.yml + +# License scanning results: the CNCF FOSSA project for this repository, kept +# current by the FOSSA GitHub integration on the cozystack organization (#4758). +licenseScanning: + url: https://app.fossa.com/projects/git%2Bgithub.com%2Fcozystack%2Fcozystack diff --git a/.gemini/styleguide.md b/.gemini/styleguide.md index 4b920837e..ef8b926e5 100644 --- a/.gemini/styleguide.md +++ b/.gemini/styleguide.md @@ -35,7 +35,7 @@ Similarly, never propose edits to: Each commit must follow [Conventional Commits](https://www.conventionalcommits.org/) format: `type(scope): brief description`. -Valid types: `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`. +Valid types: `feat`, `fix`, `security` (a fix that comes through a security advisory), `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`. Valid scopes: diff --git a/.gitattributes b/.gitattributes index fd0e72652..b114c596b 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,4 @@ # Unified diff context has a marker before Go tabs and blank lines. packages/system/capi-providers-infraprovider/images/cluster-api-provider-kubevirt/patches/*.diff -whitespace +packages/system/cilium/images/cilium-operator/patches/*.diff -whitespace +packages/system/seaweedfs/images/seaweedfs/patches/*.diff -whitespace diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 1e368718e..cf463c5e8 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,6 +1,6 @@ ## What this PR does + ### Screenshots diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml index 11f413431..3c787d665 100644 --- a/.github/actionlint.yaml +++ b/.github/actionlint.yaml @@ -6,3 +6,5 @@ self-hosted-runner: - oracle-vm-4cpu-16gb-x86-64 - oracle-vm-24cpu-96gb-x86-64 - oracle-vm-32cpu-128gb-x86-64 + - oracle-vm-4cpu-16gb-arm64 + - oracle-vm-24cpu-96gb-arm64 diff --git a/.github/labels.yml b/.github/labels.yml index 4637f17e8..d00744897 100644 --- a/.github/labels.yml +++ b/.github/labels.yml @@ -22,6 +22,7 @@ # do-not-merge/ PR merge blockers # security/ security-finding severity and status (Cozystack-specific) # size/ PR size (auto-applied) +# backport/ maintainer overrides of the backport batch rules (Cozystack-specific) # # `aliases:` lets EndBug/label-sync rename existing labels without losing # references on already-tagged issues and PRs. @@ -78,18 +79,6 @@ color: 'e11d21' description: Indicates the change introduces a breaking API or behaviour change -# kind/backport-previous has no upstream Kubernetes equivalent (k8s has no -# two-release-line model); it stays under kind/ per the file convention. -- name: kind/backport - color: 'fbca04' - description: Categorizes issue or PR as requiring a backport to the current release line - aliases: ['backport'] - -- name: kind/backport-previous - color: 'fbd876' - description: Categorizes issue or PR as requiring a backport to the previous release line - aliases: ['backport-previous'] - # ────────────────────────────────────────────── # priority/ — urgency # ────────────────────────────────────────────── @@ -190,6 +179,10 @@ color: 'bfd4f2' description: Dependency bumps (Renovate, go.mod); scope `deps` +- name: area/dx + color: 'bfd4f2' + description: Issues or PRs related to developer tooling (hack/ scripts, package Makefiles, cozypkg) + - name: area/dashboard color: 'bfd4f2' description: Issues or PRs related to the dashboard / UI @@ -246,6 +239,10 @@ color: 'bfd4f2' description: Issues or PRs related to Keycloak (SSO / identity) +- name: area/openbao + color: 'bfd4f2' + description: Issues or PRs related to OpenBAO (secrets management, seals, auto-unseal) + - name: area/tenant color: 'bfd4f2' description: Issues or PRs related to the tenant chart and multi-tenancy @@ -403,3 +400,17 @@ - name: security/fixed color: '0e8a16' description: Fix released + +# ────────────────────────────────────────────── +# backport/ — maintainer overrides of the backport batch rules +# ────────────────────────────────────────────── + +# Read by cmd/backport-batch from the merged pull request on main; +# docs/release/backports.md describes both. +- name: backport/include + color: 'c2e0c6' + description: The backport batch takes this PR though rules 2-4 keep it out; it must still pick and pass CI + +- name: backport/skip + color: 'f9d0c4' + description: The backport batch keeps this PR out although the rules take it diff --git a/.github/renovate.json b/.github/renovate.json index a2c58d819..f36beeb6b 100644 --- a/.github/renovate.json +++ b/.github/renovate.json @@ -32,6 +32,13 @@ "matchStrings": ["clastix/kubectl:(?v[0-9]+\\.[0-9]+(?:\\.[0-9]+)?)@(?sha256:[a-f0-9]+)"], "datasourceTemplate": "docker", "depNameTemplate": "docker.io/clastix/kubectl" + }, + { + "customType": "regex", + "description": "Track the BuildKit SBOM scanner pinned by tag and digest in hack/common-envs.mk. The dockerfile manager does not read Makefiles and the helm-values manager is disabled repo-wide (see enabledManagers above), so without this manager the pin would stay on the syft it was cut with: the floating stable-1 tag it replaced moved to a fixed syft on its own, a digest pin does not. Tag and digest move together here, as the comment above the pin asks.", + "managerFilePatterns": ["/^hack/common-envs\\.mk$/"], + "matchStrings": ["SBOM_SCANNER \\?= (?docker\\.io/docker/buildkit-syft-scanner):(?[0-9]+\\.[0-9]+\\.[0-9]+)@(?sha256:[a-f0-9]+)"], + "datasourceTemplate": "docker" } ], "packageRules": [ @@ -72,17 +79,45 @@ "groupName": "container image & action digests", "schedule": ["before 6am on monday"] }, + { + "description": "The Harbor rebuilds reproduce one upstream release, so their build bases follow upstream's Makefile at that tag (GOBUILDIMAGE, NODEBUILDIMAGE) rather than the newest image. A golang tag bump builds Harbor with a toolchain upstream never shipped it with, and a node major breaks the Angular portal build. Tag bumps are disabled here; digest refreshes of the same tag still arrive through the digest group above. Move the tags by hand with HARBOR_VERSION.", + "matchManagers": ["dockerfile"], + "matchFileNames": ["packages/system/harbor/images/**"], + "matchUpdateTypes": ["major", "minor", "patch"], + "enabled": false + }, + { + "description": "The cilium-operator rebuild compiles one upstream release with the Go toolchain upstream's builder image pins at that tag, and `make update` in packages/system/cilium re-pins the builder line from there. A Renovate bump, by tag or by digest, builds with a toolchain upstream never shipped the release with, and the next `make update` silently reverts it. The operator-generic base stage and its VERSION and UPSTREAM_DIGEST args are pinned by the same recipe, and VERSION also selects the source archive SOURCE_SHA256 checks. Updates are disabled here; all of them move with the Cilium version.", + "matchManagers": ["dockerfile"], + "matchFileNames": ["packages/system/cilium/images/cilium-operator/**"], + "enabled": false + }, + { + "description": "Split golang patch from minor updates for the e2e sandbox builder, so the rule below can drop the minor bump without taking the patch bump with it. By default both land in one non-major bucket and only the newest release is proposed.", + "matchManagers": ["dockerfile"], + "matchFileNames": ["packages/core/testing/images/e2e-sandbox/**"], + "matchPackageNames": ["golang"], + "separateMinorPatch": true + }, + { + "description": "The e2e sandbox builds a patched chainsaw release with the Go minor upstream shipped that release with. A golang minor or major bump builds it with a toolchain upstream never shipped it with. Patch and digest updates of the same minor still arrive; move the minor by hand together with CHAINSAW_VERSION.", + "matchManagers": ["dockerfile"], + "matchFileNames": ["packages/core/testing/images/e2e-sandbox/**"], + "matchPackageNames": ["golang"], + "matchUpdateTypes": ["major", "minor"], + "enabled": false + }, + { + "description": "The seaweedfs rebuild compiles one upstream release with the Go toolchain upstream's docker/Dockerfile.go_build uses at that tag, lays it over the upstream image of that tag, and `make update` in packages/system/seaweedfs re-pins the builder, the base image digest and the source checksum from there. A Renovate bump of any of them builds a combination upstream never shipped, and the next `make update` silently reverts it. Updates are disabled here; all of them move with the SeaweedFS version.", + "matchManagers": ["dockerfile"], + "matchFileNames": ["packages/system/seaweedfs/images/seaweedfs/**"], + "enabled": false + }, { "description": "kubevirt.io/csi-driver is pinned to an untagged pseudo-version commit and publishes no release tags, so Renovate's go datasource returns no-result and the lookup failure lingers on the Dependency Dashboard. Disable it; this module is advanced deliberately alongside the kubevirt-csi-driver image build.", "matchManagers": ["gomod"], "matchPackageNames": ["kubevirt.io/csi-driver"], "enabled": false - }, - { - "description": "k8s.io/apimachinery is replaced by the cozystack/apimachinery fork at a pseudo-version cut from a rebased branch that carries the ConvertToVersion patch. The fork's release tags are stale upstream mirrors, so Renovate proposes one of them as an 'update' that is in fact a downgrade dropping the patch. Advance the replace by hand whenever the fork is rebased onto a new Kubernetes line.", - "matchManagers": ["gomod"], - "matchPackageNames": ["github.com/cozystack/apimachinery"], - "enabled": false } ] } diff --git a/.github/workflows/api-review-gate-fork.yaml b/.github/workflows/api-review-gate-fork.yaml new file mode 100644 index 000000000..30611f07e --- /dev/null +++ b/.github/workflows/api-review-gate-fork.yaml @@ -0,0 +1,413 @@ +name: API Review Gate (fork) + +# Privileged publisher for the "API Review Gate" merge gate on FORK pull +# requests, after the split e2e-fork.yaml uses for "E2E Tests" +# (docs/agents/e2e-testing.md §10). +# +# No run of api-review-gate.yaml can post a status for a fork: the GITHUB_TOKEN +# is read-only for a fork PR on both the `pull_request` and the +# `pull_request_review` trigger. Nor can that run's verdict be relayed, because a +# fork's run executes the fork's own copy of the workflow, so its conclusion is +# whatever the fork wants it to be. This workflow runs from the DEFAULT branch +# and reaches the verdict itself, from inputs a fork cannot forge: the detector +# built from the default branch, reading the PR head as data, plus the base repo's +# PR and review APIs. The fork's run is used only as a trigger. +# +# Fork code never executes here. The head is fetched into a worktree that only +# the default-branch detector reads, in a job whose token can write nothing; the jobs +# that can write statuses never see the head at all. That is why this is a +# workflow_run and not a pull_request_target run, which would offer fork code a +# privileged token for no gain. +# +# Two ways in: +# - workflow_run, after any gate run that evaluated: a push, or a review on a +# PR whose runs need no maintainer approval. Full evaluation. +# - schedule, for reviews on PRs from external contributors. The repository +# makes every run from them wait for a maintainer's approval, and a run in +# `action_required` never fires workflow_run, so an API owner's approval +# would otherwise not reach the status until a maintainer approved the +# review-triggered run. The sweep never runs the detector. It moves only a +# status that the full evaluation set after finding a sizeable change, +# between "needs an approving review" and "approved", as the reviews on the +# head commit now dictate. A fork PR whose push run still awaits approval +# has no status to move and stays unmergeable, as it does for "E2E Tests". +# +# Same-repo PRs are published by api-review-gate.yaml's `api-gate-report`. Every +# path here acts only on PRs whose head lives in another repository, decided +# from the base repo's PR list: for a `pull_request_review` run on a fork PR, +# `workflow_run.head_repository` names the BASE repository and +# `workflow_run.pull_requests` is empty, so neither can tell a fork apart. +# +# A status lives on the SHA, not on a PR. A head that an open same-repo PR +# carries is therefore left to `api-gate-report` whatever else carries it. A head +# carried only by fork PRs fails closed: `resolve` writes the failure, and the +# sweep turns a success already standing there into the same failure. One commit +# status cannot hold a verdict per base, so every PR on a head shared with a +# same-repo PR shows whichever verdict stands there, as two same-repo PRs at +# different bases already do. + +on: + workflow_run: + workflows: ["API Review Gate"] + types: [completed] + schedule: + - cron: "*/15 * * * *" + workflow_dispatch: {} + +# Keyed by head SHA: a newer evaluation of the same commit reads newer reviews, +# so it may supersede an older one, while a push gets a new SHA and leaves the +# old commit's run alone. A cancelled or skipped gate run evaluated nothing and +# `resolve` ignores it; in the shared group it would still cancel the live run +# that owns the SHA after that run had posted `pending`, leaving nothing to +# conclude it. Keyed by its own run id, it can cancel only itself. +concurrency: + group: >- + api-review-gate-fork-${{ + github.event_name != 'workflow_run' && 'sweep' + || (github.event.workflow_run.conclusion == 'cancelled' + || github.event.workflow_run.conclusion == 'skipped') + && format('discarded-{0}', github.event.workflow_run.id) + || github.event.workflow_run.head_sha }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + resolve: + name: Resolve fork PR + # A `commented` review skips every job of the gate run, so it concludes + # `skipped`; a run superseded by a newer one concludes `cancelled`. Neither is + # a reason to re-evaluate. A fork can force either outcome by editing its copy + # of the gate, which can only withhold a re-evaluation: a push then leaves no + # status at all, and a withdrawn approval is caught by the sweep. + if: >- + ${{ github.event_name == 'workflow_run' + && github.event.workflow_run.conclusion != 'cancelled' + && github.event.workflow_run.conclusion != 'skipped' }} + runs-on: ubuntu-latest + permissions: + pull-requests: read + statuses: write + outputs: + should_run: ${{ steps.r.outputs.should_run }} + pr_number: ${{ steps.r.outputs.pr_number }} + base_ref: ${{ steps.r.outputs.base_ref }} + steps: + - name: Resolve fork PR and claim "API Review Gate" + id: r + uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7 + env: + HEAD_SHA: ${{ github.event.workflow_run.head_sha }} + with: + script: | + const { HEAD_SHA } = process.env; + const { owner, repo } = context.repo; + core.setOutput('should_run', 'false'); + if (!/^[0-9a-f]{40}$/.test(HEAD_SHA)) { + core.setFailed(`unexpected head_sha '${HEAD_SHA}'`); + return; + } + const setStatus = (state, description) => github.rest.repos.createCommitStatus({ + owner, repo, sha: HEAD_SHA, state, context: 'API Review Gate', description, + target_url: `${context.serverUrl}/${owner}/${repo}/actions/runs/${context.runId}`, + }); + + // The association endpoint does not index fork heads, so match the + // open PR list on the head SHA, as e2e-fork.yaml's `resolve` does. + // A closed or merged PR never counts. + const openPrs = await github.paginate( + github.rest.pulls.list, + { owner, repo, state: 'open', per_page: 100 }, + ); + const atHead = openPrs.filter(p => p.head && p.head.sha === HEAD_SHA); + const isFork = p => !p.head.repo || p.head.repo.full_name !== `${owner}/${repo}`; + // The status lives on the SHA, so a head that an open same-repo PR + // carries is that PR's: api-gate-report publishes it, and a failure + // written here would overwrite its verdict. A fork sees every commit + // of this repository, so a fork PR at that head can be opened on + // purpose, not only by accident. It inherits the verdict whatever its + // base: one commit status cannot hold two. + if (atHead.length === 0 || atHead.some(p => !isFork(p))) { + core.info(`no open PR, or a same-repo PR, carries head ${HEAD_SHA} — nothing to publish`); + return; + } + // Only fork PRs are left. Their bases may differ, so one status cannot + // speak for all of them while being computed from one. + if (atHead.length !== 1) { + await setStatus('failure', `expected exactly one open PR for ${HEAD_SHA}, found ${atHead.length}`); + return; + } + const pr = atHead[0]; + if (!/^[A-Za-z0-9._\/-]+$/.test(pr.base.ref)) { + core.setFailed(`unexpected base ref '${pr.base.ref}'`); + return; + } + + // Claimed before the minute-long evaluation, so a dismissal cannot + // leave a stale `success` mergeable meanwhile. + await setStatus('pending', 're-evaluating in the privileged fork workflow'); + core.setOutput('pr_number', String(pr.number)); + core.setOutput('base_ref', pr.base.ref); + core.setOutput('should_run', 'true'); + + # The only job that touches fork bytes, so its token can write nothing and it + # reaches no secret. The detector is built from the default branch, never + # from the head or the merge base. + detect: + name: Detect sizeable API changes + needs: [resolve] + if: ${{ needs.resolve.outputs.should_run == 'true' }} + runs-on: ubuntu-latest + permissions: + contents: read + outputs: + sizeable: ${{ steps.detect.outputs.sizeable }} + env: + HEAD_SHA: ${{ github.event.workflow_run.head_sha }} + PR_NUMBER: ${{ needs.resolve.outputs.pr_number }} + BASE_REF: ${{ needs.resolve.outputs.base_ref }} + GOPROXY: "https://proxy.golang.org|direct" + steps: + - name: Checkout default branch + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + fetch-depth: 0 + persist-credentials: false + + # From the default branch's go.mod, and with no cache: a cache saved here + # would be keyed in the default branch's scope. + - name: Set up Go + uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5 + with: + go-version-file: go.mod + cache: false + + - name: Materialize head and merge-base worktrees + run: | + set -euo pipefail + git fetch --no-tags origin "refs/pull/${PR_NUMBER}/head" "${BASE_REF}" + got="$(git rev-parse FETCH_HEAD)" + if [ "${got}" != "${HEAD_SHA}" ]; then + echo "::error::PR head moved: refs/pull/${PR_NUMBER}/head is ${got}, resolved ${HEAD_SHA}" + exit 1 + fi + merge_base="$(git merge-base "${HEAD_SHA}" "origin/${BASE_REF}")" + echo "Merge base: ${merge_base}" + # Links stay links: a checkout that flattened them would hide a CRD + # behind a file link from the detector while Helm still ships it, and + # the verdict would differ from the one the same-repo gate reaches. + git worktree add --detach "${RUNNER_TEMP}/head" "${HEAD_SHA}" + git worktree add --detach "${RUNNER_TEMP}/base" "${merge_base}" + + # Always from the default branch, the commit this workflow and its approval + # rule come from. Not from the merge base: a fork's author chooses that, + # and an old one would select an old detector, so a fix to the detector + # would not reach the PRs that most need it. + - name: Build api-gate + run: | + set -euo pipefail + ( cd "${GITHUB_WORKSPACE}" && go build -o "${RUNNER_TEMP}/api-gate" ./cmd/api-gate ) + + - name: Detect sizeable API changes + id: detect + run: | + set -uo pipefail + # api-gate exits 2 for a sizeable change; the runner's default `bash -e` + # would end the step there, before the code is read. + set +e + "${RUNNER_TEMP}/api-gate" \ + --base "${RUNNER_TEMP}/base" \ + --head "${RUNNER_TEMP}/head" \ + --format markdown > "${RUNNER_TEMP}/report.md" + code=$? + set -e + cat "${RUNNER_TEMP}/report.md" + { echo "## API Review Gate (fork PR #${PR_NUMBER})"; echo; cat "${RUNNER_TEMP}/report.md"; } >> "$GITHUB_STEP_SUMMARY" + case "${code}" in + 0) echo "sizeable=false" >> "$GITHUB_OUTPUT" ;; + 2) echo "sizeable=true" >> "$GITHUB_OUTPUT" ;; + *) echo "::error::api-gate failed with exit code ${code}"; exit "${code}" ;; + esac + + # Publishes the verdict of a workflow_run evaluation, or sweeps on a schedule. + # One script for both, so the approval rule exists once in this file. + conclude: + name: Report fork API review gate status + needs: [resolve, detect] + if: >- + ${{ !cancelled() + && (github.event_name != 'workflow_run' + || needs.resolve.outputs.should_run == 'true') }} + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read + statuses: write + steps: + - name: Checkout the gate workflow + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + sparse-checkout: .github/workflows/api-review-gate.yaml + sparse-checkout-cone-mode: false + persist-credentials: false + + # api-review-gate.yaml owns the list, so the two publishers cannot drift. + # Read from the default branch, which is where this workflow runs from. + - name: Read API owners + id: owners + run: | + set -euo pipefail + owners="$(yq -r '.env.API_OWNERS' .github/workflows/api-review-gate.yaml)" + if ! [[ "${owners}" =~ ^[A-Za-z0-9-]+(\ [A-Za-z0-9-]+)*$ ]]; then + echo "::error::unexpected API_OWNERS '${owners}' in api-review-gate.yaml" + exit 1 + fi + echo "owners=${owners}" >> "$GITHUB_OUTPUT" + + - name: Report "API Review Gate" commit status + uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7 + env: + API_OWNERS: ${{ steps.owners.outputs.owners }} + HEAD_SHA: ${{ github.event.workflow_run.head_sha }} + PR_NUMBER: ${{ needs.resolve.outputs.pr_number }} + DETECT_RESULT: ${{ needs.detect.result }} + SIZEABLE: ${{ needs.detect.outputs.sizeable }} + with: + script: | + const { API_OWNERS, HEAD_SHA, PR_NUMBER, DETECT_RESULT, SIZEABLE } = process.env; + const { owner, repo } = context.repo; + const owners = new Set(API_OWNERS.toLowerCase().split(' ')); + // The same descriptions api-gate-report posts. The sweep reads the + // first two back as state, so change them only together with it. + const APPROVED = 'sizeable API change approved by an API owner'; + const NEEDS_PREFIX = 'sizeable API change needs an approving review from: '; + const NEEDS = NEEDS_PREFIX + API_OWNERS; + + const setStatus = (sha, state, description) => github.rest.repos.createCommitStatus({ + owner, repo, sha, state, context: 'API Review Gate', description, + target_url: `${context.serverUrl}/${owner}/${repo}/actions/runs/${context.runId}`, + }); + + // The rule of api-review-gate.yaml's approval step: each reviewer's + // latest non-comment review on this exact commit, so an approval of an + // older commit, a dismissed one and one superseded by a request for + // changes all fail to count. + const ownerApproved = async (pull_number, sha) => { + const reviews = await github.paginate( + github.rest.pulls.listReviews, + { owner, repo, pull_number, per_page: 100 }, + ); + const latest = new Map(); + for (const r of reviews) { + if (!r.user || r.commit_id !== sha || r.state === 'COMMENTED') continue; + const login = r.user.login.toLowerCase(); + const prev = latest.get(login); + if (!prev || (r.submitted_at || '') >= (prev.submitted_at || '')) latest.set(login, r); + } + return [...latest].some(([login, r]) => owners.has(login) && r.state === 'APPROVED'); + }; + + if (context.eventName === 'workflow_run') { + const { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number: Number(PR_NUMBER) }); + // A push since `resolve` started a newer run, which owns the new head. + if (pr.state !== 'open' || pr.head.sha !== HEAD_SHA) { + core.info(`PR #${PR_NUMBER} is no longer open at ${HEAD_SHA} — posting nothing`); + return; + } + if (DETECT_RESULT === 'success' && SIZEABLE === 'false') { + await setStatus(HEAD_SHA, 'success', 'no sizeable API change'); + } else if (DETECT_RESULT === 'success' && SIZEABLE === 'true') { + const ok = await ownerApproved(pr.number, HEAD_SHA); + await setStatus(HEAD_SHA, ok ? 'success' : 'failure', ok ? APPROVED : NEEDS); + } else { + await setStatus(HEAD_SHA, 'failure', 'gate evaluation did not complete — see the run for details'); + } + return; + } + + // Sweep. One GraphQL page returns 100 open PRs with the gate's status + // on each head, which keeps a 15-minute cadence well inside the + // GITHUB_TOKEN rate limit; reviews are fetched only for the few PRs + // whose status the reviews can move. + const query = `query($owner: String!, $repo: String!, $cursor: String) { + repository(owner: $owner, name: $repo) { + pullRequests(states: OPEN, first: 100, after: $cursor) { + pageInfo { hasNextPage endCursor } + nodes { + number + isCrossRepository + headRefOid + commits(last: 1) { nodes { commit { oid status { + context(name: "API Review Gate") { state description creator { login } } + } } } } + } + } + } + }`; + // Every open PR is read before any is swept: whether a head is shared + // is a fact about all of them, not about the page a PR sits on. + const nodes = []; + let cursor = null; + do { + const page = (await github.graphql(query, { owner, repo, cursor })).repository.pullRequests; + nodes.push(...page.nodes); + cursor = page.pageInfo.hasNextPage ? page.pageInfo.endCursor : null; + } while (cursor); + const carriers = new Map(); + for (const pr of nodes) { + const c = carriers.get(pr.headRefOid) || { count: 0, sameRepo: false }; + c.count++; + c.sameRepo = c.sameRepo || !pr.isCrossRepository; + carriers.set(pr.headRefOid, c); + } + + let errors = 0; + const closed = new Set(); + for (const pr of nodes) { + const commit = pr.commits.nodes[0]?.commit; + const status = commit?.status?.context; + const shared = carriers.get(pr.headRefOid); + if (shared.count > 1) { + // These PRs share one status. A same-repo carrier owns it through + // api-gate-report. Among forks it is ambiguous: a success standing + // there may belong to a PR on another base, or rest on an approval + // withdrawn on a PR whose run awaits a maintainer and never reaches + // `resolve`. Close it as `resolve` does, once per head, and never + // create a status here. + if (!shared.sameRepo && !closed.has(pr.headRefOid) && commit?.oid === pr.headRefOid + && status?.creator?.login === 'github-actions' && status.state === 'SUCCESS') { + closed.add(pr.headRefOid); + try { + await setStatus(pr.headRefOid, 'failure', `expected exactly one open PR for ${pr.headRefOid}, found ${shared.count}`); + core.info(`${pr.headRefOid}: head carried by ${shared.count} fork PRs → failure`); + } catch (err) { + errors++; + core.warning(`${pr.headRefOid}: ${err}`); + } + } + continue; + } + // Only a status a workflow posted: a fork's own runs cannot post + // one, so on a fork head that means this workflow. + if (!pr.isCrossRepository || !status || commit.oid !== pr.headRefOid + || status.creator?.login !== 'github-actions') continue; + const description = status.description || ''; + const awaiting = status.state === 'FAILURE' && description.startsWith(NEEDS_PREFIX); + const approved = status.state === 'SUCCESS' && description === APPROVED; + if (!awaiting && !approved) continue; + try { + const ok = await ownerApproved(pr.number, pr.headRefOid); + if (awaiting && ok) { + await setStatus(pr.headRefOid, 'success', APPROVED); + core.info(`#${pr.number}: approved by an API owner → success`); + } else if (approved && !ok) { + await setStatus(pr.headRefOid, 'failure', NEEDS); + core.info(`#${pr.number}: API owner approval withdrawn → failure`); + } + } catch (err) { + errors++; + core.warning(`#${pr.number}: ${err}`); + } + } + if (errors) core.setFailed(`${errors} PR(s) could not be swept`); diff --git a/.github/workflows/api-review-gate.yaml b/.github/workflows/api-review-gate.yaml index 846a305c7..7e670a7c9 100644 --- a/.github/workflows/api-review-gate.yaml +++ b/.github/workflows/api-review-gate.yaml @@ -5,38 +5,97 @@ name: API Review Gate # API group, a new resource, or a breaking change to an existing resource's # schema. Detection is deterministic (cmd/api-gate); no LLM or network calls. # -# The job runs on every PR (no path filter) so it can always report a status -# and therefore be marked as a required check in branch protection without -# leaving PRs that touch no API stuck in "pending". When nothing sizeable -# changed it passes immediately. +# The job runs on every PR (no path filter) so it can always reach a verdict +# without leaving PRs that touch no API stuck in "pending". When nothing +# sizeable changed it passes immediately. +# +# The merge gate is the COMMIT STATUS named "API Review Gate", posted by the +# `api-gate-report` job for same-repo PRs and by api-review-gate-fork.yaml for +# fork PRs — NOT by the evaluating job below. Same reasoning as the "E2E Tests" +# gate (docs/agents/e2e-testing.md §10), and it is what makes the +# `commented`-review skip below safe: +# - A required *job* that skips counts as PASSED by branch protection, so any +# path that skips the evaluating job would hand out a free pass (#3257). A +# status is "success" only when a report step posts it, and a never-posted +# required status stays "Expected", which blocks the merge. +# - Check runs are NOT deduplicated per name: every workflow run gets its own +# check suite, so `GET /commits/{sha}/check-runs?filter=latest` returns the +# same set as `filter=all` and the rollup is worst-of. Two runs on one head +# SHA leave two verdicts standing for the same name, and a cancelled run +# then poisons the context for good. Commit statuses ARE deduplicated per +# context, newest wins. +# +# Consequence, and the invariant every change here must preserve: declining to +# post can only preserve a verdict some real run reached, never invent one. So +# skipped and cancelled runs post no verdict. The one thing a run posts before it +# has one is `pending`, which is not a pass and blocks the merge until a real +# verdict replaces it. +# +# For the gate to actually block a merge, main branch protection must require +# the "API Review Gate" status CONTEXT; without that it is advisory. Never wire +# branch protection to a job name. on: pull_request: types: [opened, synchronize, reopened] # Re-evaluate when a review is submitted or dismissed so an approval by an - # API owner flips the check from failing to passing without a new push. + # API owner flips the status from failing to passing without a new push. The + # job-level `if` below drops the review-bot noise (plain `commented` reviews); + # only reviews that can move the gate — approved, changes_requested, + # dismissed — actually re-run it. pull_request_review: types: [submitted, dismissed] +# A run that computes a verdict must never be cancelled by a run that does not. +# A plain `commented` review skips the evaluation (see the job `if`), so it gets +# its own group and can only cancel other no-op runs, while pushes and +# actionable reviews share the `eval` group and legitimately supersede each +# other. Under a single shared group a review bot commenting during the ~30s +# evaluation cancelled it and then contributed nothing — observed on real PRs +# (41d1153c, 4b1966c5), leaving a cancelled run as that SHA's only verdict. concurrency: - group: api-review-gate-${{ github.event.pull_request.number }} + group: >- + api-review-gate-${{ github.event.pull_request.number }}-${{ + github.event_name == 'pull_request_review' + && github.event.review.state == 'commented' && 'noop' || 'eval' }} cancel-in-progress: true permissions: contents: read pull-requests: read +env: + # Space-separated GitHub logins allowed to satisfy the gate. Edit here to + # change who can approve sizeable API changes. Workflow-level so the + # evaluating job and the published status description cannot drift apart. + API_OWNERS: "lllamnyp kvaps" + jobs: api-review-gate: - name: Require API owner review for sizeable API changes + # Deliberately NOT named after the gate: the merge gate is the "API Review + # Gate" commit status, and a required context that is also a job name + # inherits the skip-to-green and no-dedup problems in the header. + name: API review gate (evaluate) + # A push always evaluates the gate. A review event re-runs it only when the + # review can move the verdict: an approval can flip fail->pass, a dismissal + # or changes_requested can flip pass->fail. Plain `commented` reviews — all + # that the review bots (CodeRabbit, dosubot) ever post — cannot, so they skip + # here instead of rebuilding the detector on every bot comment. Safe because + # `api-gate-report` skips in lockstep and posts nothing, which leaves the + # last real verdict standing. + if: >- + github.event_name != 'pull_request_review' || + github.event.review.state != 'commented' runs-on: ubuntu-22.04 + outputs: + sizeable: ${{ steps.detect.outputs.sizeable }} + verdict: ${{ steps.approve.outputs.verdict }} env: - # Space-separated GitHub logins allowed to satisfy the gate. Edit here to - # change who can approve sizeable API changes. - API_OWNERS: "lllamnyp kvaps" BASE_REF: ${{ github.event.pull_request.base.ref }} HEAD_SHA: ${{ github.event.pull_request.head.sha }} PR_NUMBER: ${{ github.event.pull_request.number }} + # The pipe falls back to direct on any proxy error (hack/common-envs.mk). + GOPROXY: "https://proxy.golang.org|direct" steps: - name: Checkout head uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 @@ -119,6 +178,7 @@ jobs: esac - name: Check for an API owner approval + id: approve if: steps.detect.outputs.sizeable == 'true' env: GH_TOKEN: ${{ github.token }} @@ -133,14 +193,18 @@ jobs: # An APPROVED review by any API owner satisfies the gate, but only # each reviewer's *latest* review *on the current head commit* counts: # this drops approvals that a later commit invalidated, and approvals - # an owner subsequently superseded with CHANGES_REQUESTED. GitHub - # forbids self-approval, so a sizeable PR authored by an owner still - # needs the other owner. + # an owner subsequently superseded with CHANGES_REQUESTED or that was + # dismissed. A COMMENTED review is dropped before picking the latest: + # GitHub does not let a comment withdraw an approval, and the review + # trigger skips comments, so counting one here would make the verdict + # depend on which event happened to re-run the gate. GitHub forbids + # self-approval, so a sizeable PR authored by an owner still needs the + # other owner. api-review-gate-fork.yaml applies the same rule. approvals="$( gh api "repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}/reviews" --paginate | jq -rs --arg head "${HEAD_SHA}" ' add - | map(select(.commit_id == $head)) + | map(select(.commit_id == $head and .state != "COMMENTED")) | sort_by(.submitted_at // "") | group_by(.user.login) | map(last) @@ -150,12 +214,138 @@ jobs: ' )" + # The verdict is recorded as a step output so `api-gate-report` can tell + # "sizeable change, no owner approval" apart from "the evaluation itself + # broke" — both of which fail this job. Written before the exit in each + # branch, since a step output set after exiting is never emitted. for owner in ${API_OWNERS}; do if grep -qxi "${owner}" <<<"${approvals}"; then echo "Sizeable API change approved by @${owner}." + echo "verdict=pass-approved" >> "$GITHUB_OUTPUT" exit 0 fi done + echo "verdict=fail-needs-approval" >> "$GITHUB_OUTPUT" echo "::error::This PR makes a sizeable API change (new group, new resource, or breaking change) and needs an approving review from one of: ${API_OWNERS}. See the job summary for details." exit 1 + + # A dismissal or a request for changes can turn a green head red, and until + # the evaluation reports, about a minute later, the old `success` would still + # let the PR merge. Same opener as the "E2E Tests" lane. Pushes need none: a + # new head SHA starts with no status. Losing it to a transient API error only + # reopens that window, so it must not fail the run. + api-gate-pending: + name: Mark API review gate as re-evaluating + if: >- + ${{ github.event_name == 'pull_request_review' + && github.event.review.state != 'commented' + && !github.event.pull_request.head.repo.fork }} + runs-on: ubuntu-latest + continue-on-error: true + permissions: + statuses: write + steps: + - name: Report pending "API Review Gate" commit status + uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7 + env: + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + with: + script: | + const { HEAD_SHA, RUN_URL } = process.env; + const { owner, repo } = context.repo; + await github.rest.repos.createCommitStatus({ + owner, repo, sha: HEAD_SHA, state: 'pending', + context: 'API Review Gate', description: 're-evaluating after a review', + target_url: RUN_URL, + }); + + # Publish the required "API Review Gate" commit status. Separate from the + # evaluating job for the reasons in the header: the gate must not be a job + # name, and a run that reached no verdict must post none. + # + # The `if` guard stays in LOCKSTEP with the evaluating job's — this job runs if + # and only if that one does. A `commented` review skips both, so the previous + # real status stands untouched. `!cancelled()` rather than `always()`: a run + # killed by the concurrency group has no verdict, and posting one anyway would + # overwrite a green status with red — the exact failure #3262 hit twice with + # "E2E Tests" (see its `e2e-report`). + # + # Fork PRs skip this job. Their GITHUB_TOKEN is read-only on BOTH the + # `pull_request` and `pull_request_review` triggers, so no run of this workflow + # can post a status for a fork, and its verdict could not be relayed anyway: a + # fork's run executes the fork's copy of this file. api-review-gate-fork.yaml + # evaluates fork PRs again from the default branch. Until it does, the required + # status is unposted and the fork PR is not mergeable — fail-closed by + # construction. + api-gate-report: + name: Report API review gate status + needs: [api-gate-pending, api-review-gate] + if: >- + ${{ !cancelled() + && !github.event.pull_request.head.repo.fork + && (github.event_name != 'pull_request_review' + || github.event.review.state != 'commented') }} + runs-on: ubuntu-latest + permissions: + contents: read + statuses: write + steps: + - name: Report "API Review Gate" commit status + uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7 + env: + GATE_RESULT: ${{ needs.api-review-gate.result }} + SIZEABLE: ${{ needs.api-review-gate.outputs.sizeable }} + VERDICT: ${{ needs.api-review-gate.outputs.verdict }} + # Inherited from the workflow-level env; passed explicitly so the + # script's use of it is visible at the call site. + API_OWNERS: ${{ env.API_OWNERS }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + with: + script: | + const { GATE_RESULT, SIZEABLE, VERDICT, API_OWNERS, HEAD_SHA, RUN_URL } = process.env; + const { owner, repo } = context.repo; + + // No verdict to publish — say nothing and let the last real status + // stand. Reachable when the evaluating job was skipped despite the + // lockstep guard (a `needs` short-circuit), and defensive against a + // future guard drift. + if (GATE_RESULT !== 'success' && GATE_RESULT !== 'failure') { + core.info(`evaluation result '${GATE_RESULT}' — posting nothing, previous status stands`); + return; + } + + let state, description; + if (GATE_RESULT === 'success') { + state = 'success'; + description = SIZEABLE === 'true' + ? 'sizeable API change approved by an API owner' + : 'no sizeable API change'; + } else if (VERDICT === 'fail-needs-approval') { + state = 'failure'; + description = `sizeable API change needs an approving review from: ${API_OWNERS}`; + } else { + // Either the job failed before reaching a verdict (checkout, build or + // the detector), or it reached `fail-needs-approval` but the output did + // not survive the failing job — whether a failed job propagates its + // outputs is not something the docs pin down. Only the description + // degrades: the state is `failure` down both paths, so the gate itself + // is unaffected. Fail-closed either way — an unverifiable gate is red. + state = 'failure'; + description = 'gate evaluation did not complete — see the run for details'; + } + + try { + await github.rest.repos.createCommitStatus({ + owner, repo, sha: HEAD_SHA, state, + context: 'API Review Gate', description, target_url: RUN_URL, + }); + } catch (err) { + // Fail loudly and fail-closed: setFailed keeps this job red and the + // required status unposted ("Expected"), so the PR stays unmergeable. + core.setFailed(`Failed to report API Review Gate status: ${err}`); + return; + } + core.info(`API Review Gate → ${state}: ${description}`); diff --git a/.github/workflows/backport-batch.yaml b/.github/workflows/backport-batch.yaml new file mode 100644 index 000000000..8196c7468 --- /dev/null +++ b/.github/workflows/backport-batch.yaml @@ -0,0 +1,107 @@ +name: Backport batch + +# Builds the backport batch for each line `backport-batch lines` names, the +# newest released lines and any line in its rc window, newest line first, as +# docs/release/backports.md describes. The steps live in +# hack/backport-batch-scheduled.sh, which a maintainer can also run by hand. +# +# The batch runs as the cozystack-ci App, with a token minted for this +# repository alone with Contents and Pull requests write. It has no +# workflows permission, so an original that changes .github/workflows/ +# waits on the batch for a maintainer (--no-workflow-files). Its pushes, +# unlike GITHUB_TOKEN's, start CI on the batch pull request. +# +# Repository settings it reads; none is created here: +# secret COZYSTACK_CI_APP_ID, COZYSTACK_CI_PRIVATE_KEY +# the cozystack-ci App, shared with the +# release workflows. Required. +# variable BACKPORT_ALERT_TEAM the team or person the batch's comment +# mentions, org/team or a login. +# +# A batch open since the previous run, deferred conflicts and originals that +# change workflows wait for a maintainer: the batch's comment lists them. A +# failed batch CI waits too, and shows on the batch pull request's checks. + +on: + schedule: + # Monday and Thursday: each run leaves working days to cut an rc, run its + # e2e and promote it before the weekend. 06:23 UTC is after the nightly + # and the daily sweeps. + - cron: '23 6 * * 1,4' + workflow_dispatch: {} + +permissions: {} + +concurrency: + group: backport-batch + cancel-in-progress: false + +jobs: + batch: + name: Backport batch + if: github.repository == 'cozystack/cozystack' + runs-on: ubuntu-latest + # The App token lives an hour from its mint, a few minutes in; a run takes + # minutes, so the job ends well before the token does. + timeout-minutes: 30 + permissions: + contents: read + env: + # The pipe falls back to direct on any proxy error (hack/common-envs.mk). + GOPROXY: "https://proxy.golang.org|direct" + steps: + - name: Require the cozystack-ci App + env: + APP_ID: ${{ secrets.COZYSTACK_CI_APP_ID }} + APP_KEY: ${{ secrets.COZYSTACK_CI_PRIVATE_KEY }} + run: | + if [ -z "$APP_ID" ] || [ -z "$APP_KEY" ]; then + echo "::error::COZYSTACK_CI_APP_ID or COZYSTACK_CI_PRIVATE_KEY is not set. The batch pushes and opens pull requests as the cozystack-ci App only; see docs/release/backports.md#the-scheduled-run." + exit 1 + fi + + - name: Checkout + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Set up Go + uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5 + with: + go-version-file: go.mod + cache: false + + - name: Build backport-batch + run: go build -o "$RUNNER_TEMP/backport-batch" ./cmd/backport-batch + + - name: Generate GitHub App token + id: app-token + uses: actions/create-github-app-token@d72941d797fd3113feb6b93fd0dec494b13a2547 # v1 + with: + app-id: ${{ secrets.COZYSTACK_CI_APP_ID }} + private-key: ${{ secrets.COZYSTACK_CI_PRIVATE_KEY }} + owner: cozystack + repositories: cozystack + permission-contents: write + permission-pull-requests: write + + # git pushes through gh, which reads the token from the environment of + # each call, so the token is never written into the checkout. + - name: Use the App's bot as git identity and credential + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + APP_SLUG: ${{ steps.app-token.outputs.app-slug }} + run: | + gh auth setup-git + id=$(gh api "/users/${APP_SLUG}[bot]" --jq .id) + git config --global user.name "${APP_SLUG}[bot]" + git config --global user.email "${id}+${APP_SLUG}[bot]@users.noreply.github.com" + + - name: Run the batch + env: + BACKPORT_BATCH: ${{ runner.temp }}/backport-batch + BACKPORT_BATCH_TOKEN: ${{ steps.app-token.outputs.token }} + BACKPORT_BATCH_BOT: ${{ steps.app-token.outputs.app-slug }}[bot] + BACKPORT_ALERT_TEAM: ${{ vars.BACKPORT_ALERT_TEAM }} + run: hack/backport-batch-scheduled.sh --no-workflow-files diff --git a/.github/workflows/backport.yaml b/.github/workflows/backport.yaml deleted file mode 100644 index a2b9b75a9..000000000 --- a/.github/workflows/backport.yaml +++ /dev/null @@ -1,305 +0,0 @@ -name: Automatic Backport - -on: - pull_request_target: - types: [closed, labeled] # fires when PR is closed (merged) or labeled - -# Two mechanisms here, answering two different failures. -# -# A run joins its concurrency group before any job-level `if` is evaluated, so -# `prepare`'s guard below cannot stop a label event from disturbing the run -# already backporting this PR; it only decides what the label run does after the -# damage. Labels set with the default GITHUB_TOKEN start no run, but labels set -# by third-party GitHub Apps do, and they arrive in bursts. Under a plain -# `cancel-in-progress: true` each one cancelled the backport the merge had just -# started, and nothing reports that beyond a cancelled run sitting next to a -# green one. -# -# The delivery survived anyway, because the old guard admitted a run on the PR's -# cumulative labels: the last label of a burst requalified and redid the work. -# `prepare`'s narrowing below removes that accidental safety net, so the two -# changes land together — narrowing alone would turn a noisy delivery into an -# absent one. -# -# So the group key moves a label event that is NOT a backport request aside, and -# `cancel-in-progress` stops one that IS from cancelling rather than queuing. -# Both are load-bearing. `backport` and `backport-previous` are separate requests -# that both have to complete, so they share the main group and must not cancel -# each other; every other label does no work here and only has to stay out of -# the way. -# -# That is also why this file does not simply copy pull-requests.yaml, which -# splits the key and leaves cancellation unconditional: a discarded label run -# there publishes nothing, so isolating it is the whole fix. -# -# Queuing protects a pending run from the run ahead of it and never from the one -# behind: the group holds a single pending run, and a newer one evicts it. With -# the split in place that costs nothing, and for the same reason the fan-out -# below is harmless — the only events left in this group are backport requests, -# the evictor is by definition the newer of the two, and `prepare`'s `Check which -# labels are present` step reads the cumulative label set. So the survivor covers -# a superset of what the evicted run would have delivered, for any sequence that -# only adds labels. Removing one in between is the exception and needs no cover: -# the evictor then carries less because the request was withdrawn. -# -# That is exactly what the split buys. Without it the evictor could be any label -# at all, and a run that does not qualify delivers nothing in place of the -# request it displaced. -# -# `queue: max` raises the single pending slot to a hundred and is the obvious -# thing to reach for instead of the split. Taking it means giving up the -# conditional cancel, because `queue: max` and `cancel-in-progress: true` are a -# validation error together and this key still evaluates to true on a merge. -# The trade is available and was not taken: eviction is what keeps a burst to one -# surviving run rather than a hundred queued ones, and the feature only shipped -# 2026-05-07, on a path that delivers fixes to release lines. -concurrency: - group: backport-${{ github.workflow }}-${{ github.event.pull_request.number }}${{ (github.event.action == 'labeled' && github.event.label.name != 'backport' && github.event.label.name != 'backport-previous' && github.event.label.name != 'kind/backport' && github.event.label.name != 'kind/backport-previous') && '-label' || '' }} - # Stated positively, matching the group key above. `!= 'labeled'` is equivalent - # only while `types:` holds exactly these two, and that form fails open: adding - # `unlabeled` or `reopened` there would hand those events cancellation in the - # main group, which is the behaviour this file exists to remove. - # - # The positive form removes the cancelling, not the occupying. A third type - # still lands in the main group, still takes its single pending slot, and its - # `prepare` still skips — so it can evict a genuine backport request and - # deliver nothing in its place. `types:` is load-bearing for that reason and is - # pinned in hack/release-freeze-contract.bats; widening it needs the group key - # widened with it. - cancel-in-progress: ${{ github.event.action == 'closed' }} - -# Top-level token defaults to read-only. A job-level block replaces this one -# rather than adding to it, so each job restates every scope it needs. -permissions: - contents: read - -jobs: - # Determine which backports are needed - prepare: - # This guard admits each action on the labels it is entitled to. `closed` - # carries no label of its own, so it reads the set the PR ended up with. - # `labeled` reads only the label just added: matching the cumulative set - # here means every later unrelated label on a merged PR that still carries - # `backport` re-enters this job to redo a backport already delivered. - # - # Scope, so this is not read as covering the whole job: the `Check which - # labels are present` step below still reads the cumulative set, so a - # `backport-previous` event on a PR also carrying `backport` fans out to - # both matrix legs. That is deliberate, and each state a re-entered leg can - # find is already accounted for: delivered is skipped by the merged-backport - # guard, still open is skipped by backport-action on the 422, and closed - # unmerged gets a fresh backport PR, which is the retry that guard - # deliberately preserves rather than an accident. What the narrowing here - # decides is whether the job RUNS, not which targets it picks. - if: | - github.event.pull_request.merged == true && - github.event.pull_request.base.ref == 'main' && - ( - (github.event.action == 'closed' && (contains(github.event.pull_request.labels.*.name, 'backport') || contains(github.event.pull_request.labels.*.name, 'backport-previous') || contains(github.event.pull_request.labels.*.name, 'kind/backport') || contains(github.event.pull_request.labels.*.name, 'kind/backport-previous'))) || - (github.event.action == 'labeled' && (github.event.label.name == 'backport' || github.event.label.name == 'backport-previous' || github.event.label.name == 'kind/backport' || github.event.label.name == 'kind/backport-previous')) - ) - # GitHub API calls only — no docker, no repo toolchain: GitHub-hosted. - runs-on: ubuntu-latest - # Queuing gives a stuck run a way to hurt the next one that a cancelling key - # did not: the label event that used to kill it now waits behind it rather - # than clearing it. - # - # This ceiling bounds a stuck JOB, which is the case it can reach. A run can - # also wedge at the RUN level with every job already finished, and no - # job-level key expires that one; it holds the group until GitHub retires the - # run. Rare but real: run 31232645133 has been `in_progress` since - # 2026-08-08 with `prepare` and `backport` both skipped. Nothing here - # reaches that state, so docs/release.md tells an operator to look for a run - # still in flight and clear it before re-applying the label. - # - # What it bounds is EXECUTION, not the wait for a runner. GitHub's limits - # page says "job execution time" for the 6-hour job cap while spelling out - # that the 35-day run cap "includes execution duration, and time spent on - # waiting and approval" — the contrast is deliberate — and - # orgs/community#50926 shows a job sitting six hours on "Waiting for a runner - # to pick up this job" under `timeout-minutes: 5`. So queue time is a third - # unbounded case alongside the run-level wedge, not something this covers. - # - # 30 is therefore generous rather than calculated. Execution on run - # 29844315422 was 6s for `prepare` and 2s and 16s for the two matrix legs, - # against 9m24s, 5m28s and 5m45s of queue for the same three jobs. Every - # execution measured on this workflow has been seconds, and no maximum is - # quoted on purpose: an absolute maximum over a growing set is stale as soon - # as a slower run lands. The value leaves room for a cherry-pick far larger - # than anything seen while replacing the 6-hour default, and nothing here is - # sized against the queue because nothing here can be. - timeout-minutes: 30 - permissions: - contents: read - outputs: - backport_current: ${{ steps.labels.outputs.backport }} - backport_previous: ${{ steps.labels.outputs.backport_previous }} - current_branch: ${{ steps.branches.outputs.current_branch }} - previous_branch: ${{ steps.branches.outputs.previous_branch }} - steps: - - name: Check which labels are present - id: labels - uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7 - with: - script: | - const pr = context.payload.pull_request; - const labels = pr.labels.map(l => l.name); - // TRANSITIONAL: both spellings are accepted so the rename can land - // in any order relative to the org-level dosubot, which still - // applies the legacy names and is today the dominant applier on - // real backports. Once dosubot's PR labelling is switched off and - // the in-repo labeler is the only applier, the legacy arms here, - // in the `if:` gate above and in the concurrency group can all be - // deleted in one pass. - const isBackport = labels.includes('kind/backport') || labels.includes('backport'); - const isBackportPrevious = labels.includes('kind/backport-previous') || labels.includes('backport-previous'); - - core.setOutput('backport', isBackport ? 'true' : 'false'); - core.setOutput('backport_previous', isBackportPrevious ? 'true' : 'false'); - - console.log(`backport label: ${isBackport}, backport-previous label: ${isBackportPrevious}`); - - - name: Determine target branches - id: branches - uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7 - with: - script: | - // Enumerate the real release-X.Y branches rather than deriving them - // from the latest published release. - // - // Since cutting an rc freezes the line (cut-prerelease.yaml), - // release-X.Y is created when the first vX.Y.0-rc.N is cut — before - // vX.Y.0 is ever published. getLatestRelease returns the newest - // published STABLE, so throughout the freeze window it still named - // the previous line: a `backport` on a fix for the release being - // stabilised would have landed on release-X.(Y-1) and missed the - // release it was written for. That window is exactly when backports - // matter most, since the frozen branch is the only way in. - // - // Enumerating branches also drops the contiguous-minor assumption: - // `previous` used to be computed as min-1, which named a - // non-existent branch whenever a minor was skipped. - const branches = await github.paginate(github.rest.repos.listBranches, { - owner: context.repo.owner, - repo: context.repo.repo, - per_page: 100 - }); - - const lines = branches - .map(b => /^release-(\d+)\.(\d+)$/.exec(b.name)) - .filter(Boolean) - .map(m => ({ name: m[0], maj: Number(m[1]), min: Number(m[2]) })) - .sort((a, b) => (b.maj - a.maj) || (b.min - a.min)); - - if (lines.length === 0) { - core.setFailed('No release-X.Y branches found; cannot determine backport target.'); - return; - } - - const currentBranch = lines[0].name; - const previousBranch = lines.length > 1 ? lines[1].name : ''; - - core.setOutput('current_branch', currentBranch); - core.setOutput('previous_branch', previousBranch); - - console.log(`Release lines found: ${lines.map(l => l.name).join(', ')}`); - console.log(`Current branch: ${currentBranch}, Previous branch: ${previousBranch || 'N/A'}`); - - // Both targets come from the enumeration above, so they exist by - // construction — no getBranch probe needed. What CAN still fail is - // asking for a previous line when only one exists. - if (!previousBranch && '${{ steps.labels.outputs.backport_previous }}' === 'true') { - core.setFailed('backport-previous requested, but only one release line exists.'); - return; - } - - backport: - needs: prepare - if: | - github.event.pull_request.merged == true && - github.event.pull_request.base.ref == 'main' && - (needs.prepare.outputs.backport_current == 'true' || needs.prepare.outputs.backport_previous == 'true') - # git cherry-picks via backport-action — no docker, no repo toolchain: GitHub-hosted. - runs-on: ubuntu-latest - # See `prepare` above: a queued request waits on this one, so it needs a - # ceiling rather than the 6-hour default. Bounds this job's execution only; - # the wait for a runner is outside it either way. - timeout-minutes: 30 - permissions: - contents: write - pull-requests: write - strategy: - matrix: - backport_type: [current, previous] - steps: - # 1. Determine target branch based on matrix - - name: Set target branch - id: target - if: | - (matrix.backport_type == 'current' && needs.prepare.outputs.backport_current == 'true') || - (matrix.backport_type == 'previous' && needs.prepare.outputs.backport_previous == 'true') - run: | - if [ "${{ matrix.backport_type }}" == "current" ]; then - echo "branch=${{ needs.prepare.outputs.current_branch }}" >> $GITHUB_OUTPUT - echo "Target branch: ${{ needs.prepare.outputs.current_branch }}" - else - echo "branch=${{ needs.prepare.outputs.previous_branch }}" >> $GITHUB_OUTPUT - echo "Target branch: ${{ needs.prepare.outputs.previous_branch }}" - fi - - # 2. Skip if this target already has a merged backport. - # - # The action's backport branch name is deterministic, - # backport--to-. A merged PR with that head - # means an earlier run already delivered this change to the target — a - # second label event (e.g. backport-previous added after backport - # already merged) would re-enter this job and cherry-pick commits the - # target branch already has. Git reports that as an empty pick (exit 1) - # rather than a conflict, which draft_commit_conflicts below misreads - # as a real conflict and reports as a failed backport on the original - # PR. Skipping here avoids the false report; it does not touch the - # empty-pick behavior itself, which lives in the action. - - name: Check for existing merged backport - id: guard - if: steps.target.outcome == 'success' - uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7 - with: - script: | - const targetBranch = '${{ steps.target.outputs.branch }}'; - const head = `backport-${context.payload.pull_request.number}-to-${targetBranch}`; - const { data: prs } = await github.rest.pulls.list({ - owner: context.repo.owner, - repo: context.repo.repo, - state: 'closed', - head: `${context.repo.owner}:${head}`, - }); - const alreadyMerged = prs.some(p => p.merged_at !== null); - core.setOutput('already_merged', alreadyMerged ? 'true' : 'false'); - if (alreadyMerged) { - console.log(`Skipping backport to ${targetBranch}: ${head} already merged.`); - } - - # 3. Checkout (required by backport‑action) - - name: Checkout repository - if: steps.target.outcome == 'success' && steps.guard.outputs.already_merged != 'true' - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - - # 4. Create the back‑port pull request - - name: Create back‑port PR - id: backport - if: steps.target.outcome == 'success' && steps.guard.outputs.already_merged != 'true' - uses: korthout/backport-action@0193454f0c5947491d348f33a275c119f30eb736 # v3.2.1 - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - label_pattern: '' # don't read labels for targets - target_branches: ${{ steps.target.outputs.branch }} - merge_commits: skip - # conflict_resolution lives inside the experimental JSON input, not as a - # top-level key. Passed top-level it is silently ignored and the action - # falls back to the experimental default ("fail"), which on a conflict - # creates no PR and only comments. Nesting it here makes a conflicting - # backport open a draft PR with the conflict committed for manual fixup. - experimental: | - { - "conflict_resolution": "draft_commit_conflicts" - } diff --git a/.github/workflows/build-arm64-nightly.yaml b/.github/workflows/build-arm64-nightly.yaml new file mode 100644 index 000000000..781e192d5 --- /dev/null +++ b/.github/workflows/build-arm64-nightly.yaml @@ -0,0 +1,111 @@ +name: Build arm64 (nightly) + +# Builds main's images for arm64 once a day, the same way the pre-release leg +# in tags.yaml does, so an arm64 break surfaces here rather than on the next +# rc, which fails with its arm64 build. The images are pushed under +# nightly-arm64 only because buildx needs somewhere to put them; nothing +# consumes them. This run also owns the arm64 build cache the rc leg reads. +# +# It first prints which refs main pins that are not amd64+arm64 indexes. The +# rc gate fails on every one of them that the stitch does not turn into an +# index, so the list is the work left before the next rc can ship. + +on: + schedule: + - cron: '0 3 * * *' # daily 03:00 UTC + workflow_dispatch: + +concurrency: + group: build-arm64-nightly + cancel-in-progress: true + +permissions: + contents: read + +jobs: + build-arm64: + name: Build main arm64 images + runs-on: oracle-vm-24cpu-96gb-arm64 + # Starts from the rc leg's budget; re-measure after the first runs. + timeout-minutes: 120 + permissions: + contents: read + + steps: + # A dispatch from another ref would overwrite main's arm64 cache. + - name: Refuse a build for a ref other than main + env: + REF: ${{ github.ref }} + run: | + if [ "$REF" != refs/heads/main ]; then + echo "::error::Refusing to build '$REF'; only main is built here." + exit 1 + fi + + - name: Checkout code + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + fetch-depth: 0 + fetch-tags: true + persist-credentials: false + + - name: Set up build toolchain + run: | + command -v skopeo >/dev/null \ + || { sudo apt-get update -qq && sudo apt-get install -y -qq skopeo; } + command -V docker jq yq skopeo + yq --version | grep -q mikefarah + + # Before the build, which stamps the tree with this run's digests. + - name: Report refs that are not multi-arch + run: hack/verify-multiarch.sh --report packages + + - name: Set up Docker config + run: | + if [ -d ~/.docker ]; then + cp -r ~/.docker "${{ runner.temp }}/.docker" + fi + + - name: Login to OCIR + uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3 + with: + username: ${{ secrets.OCIR_USER }} + password: ${{ secrets.OCIR_TOKEN }} + registry: iad.ocir.io + env: + DOCKER_CONFIG: ${{ runner.temp }}/.docker + + # docker.io pulls go through the mirror in hack/buildkitd.toml, as the + # PR builds' do: anonymous Docker Hub pulls from these runners are rate + # limited. + - name: Set up Buildx (docker-container driver, docker.io mirror) + id: buildx + uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3 + with: + driver: docker-container + buildkitd-config: hack/buildkitd.toml + env: + DOCKER_CONFIG: ${{ runner.temp }}/.docker + + - name: Build arm64 images + run: | + set -euo pipefail + # Checked first, for the reason given in tags.yaml's build-arm64. + units="$(MATRIX_ARCH=arm64 hack/build-matrix.sh | jq -r '.[]')" + [ -n "$units" ] + for unit in $units; do + make -C "$unit" image + done + make -C packages/core/installer image-operator + env: + DOCKER_CONFIG: ${{ runner.temp }}/.docker + BUILDER: ${{ steps.buildx.outputs.name }} + PLATFORM: linux/arm64 + REGISTRY: iad.ocir.io/idyksih5sir9/cozystack + # The only writer of the arm64 cache, as build-main.yaml is of the + # amd64 one, so no two builds race on the cache manifest. + CACHE_TAG: buildcache-arm64 + WRITE_CACHE: '1' + IMAGE_TAG: nightly-arm64 + PUBLISH_VERSIONED: '0' + PUBLISH_FLOATING: '0' diff --git a/.github/workflows/build-main.yaml b/.github/workflows/build-main.yaml index 97b8ac6c1..7de6c53f5 100644 --- a/.github/workflows/build-main.yaml +++ b/.github/workflows/build-main.yaml @@ -45,6 +45,9 @@ jobs: # background main-push job, latency is not critical. runs-on: oracle-vm-24cpu-96gb-x86-64 timeout-minutes: 120 + env: + # The pipe falls back to direct on any proxy error (hack/common-envs.mk). + GOPROXY: "https://proxy.golang.org|direct" permissions: contents: read packages: write @@ -60,12 +63,46 @@ jobs: # .git/config where a later build step could read it. persist-credentials: false - # Ephemeral runners lack the flux CLI the installer's image-packages step - # shells out to; install if absent (idempotent). - - name: Set up build toolchain + # Writes the Go module cache pull-requests.yaml's unit test job restores: + # an entry saved on main is readable from every PR, while one a PR run + # saves is visible to that PR alone. It is saved before the image build so + # a cancelled or failed build still leaves it, and none of these steps may + # stop the build, which does not use it. Only an exact key is restored: a + # partial match saved under the new key would carry every superseded + # module version forward forever. + - name: Locate Go module cache + id: gomodcache + continue-on-error: true + run: echo "dir=$(go env GOMODCACHE)" >> "$GITHUB_OUTPUT" + - name: Restore Go module cache + id: gomod-restore + continue-on-error: true + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ steps.gomodcache.outputs.dir }} + key: go-mod-${{ runner.os }}-${{ hashFiles('**/go.sum') }} + - name: Download Go modules + id: gomod-download + if: steps.gomod-restore.outputs.cache-hit != 'true' + continue-on-error: true run: | - command -v flux >/dev/null \ - || curl -fsSL https://fluxcd.io/install.sh | sudo bash + for mod in $(git ls-files go.mod '*/go.mod' | xargs -n1 dirname); do + (cd "$mod" && "$GITHUB_WORKSPACE/hack/go-mod-download.sh") + done + - name: Save Go module cache + if: steps.gomod-download.outcome == 'success' + continue-on-error: true + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ steps.gomodcache.outputs.dir }} + key: go-mod-${{ runner.os }}-${{ hashFiles('**/go.sum') }} + + # Ephemeral runners lack the flux CLI the installer's image-packages step + # shells out to. + - name: Set up flux + uses: fluxcd/flux2/action@04acaec6161ac4fb1a82ffafa88901c03271d34f # v2.8.6 + with: + version: "2.8.6" - name: Set up Docker config run: | @@ -106,6 +143,10 @@ jobs: # --builder=$(BUILDER)); buildx forwards the OCIR auth from DOCKER_CONFIG # to the container builder for cache reads/writes and image pushes. BUILDER: ${{ steps.buildx.outputs.name }} + # common-envs.mk defaults to amd64+arm64. Nothing here sets up QEMU, + # and on this x86-64 runner the arm64 half would be emulated anyway; + # CI builds amd64 until arm64 has a native leg of its own. + PLATFORM: linux/amd64 # WRITE_CACHE=1 turns on --cache-to (mode=max) for every image. WRITE_CACHE: '1' # Publish a floating :main handle; do not move :latest (releases do). diff --git a/.github/workflows/build-release.yaml b/.github/workflows/build-release.yaml index a58a24832..27ad5db73 100644 --- a/.github/workflows/build-release.yaml +++ b/.github/workflows/build-release.yaml @@ -107,11 +107,11 @@ jobs: persist-credentials: false # Ephemeral runners lack the flux CLI the installer's image-packages step - # shells out to; install if absent (idempotent). - - name: Set up build toolchain - run: | - command -v flux >/dev/null \ - || curl -fsSL https://fluxcd.io/install.sh | sudo bash + # shells out to. + - name: Set up flux + uses: fluxcd/flux2/action@04acaec6161ac4fb1a82ffafa88901c03271d34f # v2.8.6 + with: + version: "2.8.6" - name: Set up Docker config run: | @@ -143,6 +143,8 @@ jobs: env: DOCKER_CONFIG: ${{ runner.temp }}/.docker BUILDER: ${{ steps.buildx.outputs.name }} + # amd64 only, as in build-main.yaml. + PLATFORM: linux/amd64 # READ the shared mode=max cache, never write it. CACHE_REGISTRY/: # buildcache is a single ref per image and build-main.yaml is # deliberately its only writer, serialized, precisely so concurrent diff --git a/.github/workflows/changelog-generate.yaml b/.github/workflows/changelog-generate.yaml index b31813a59..ff67b4f7e 100644 --- a/.github/workflows/changelog-generate.yaml +++ b/.github/workflows/changelog-generate.yaml @@ -154,6 +154,7 @@ jobs: sparse-checkout: | hack docs/agents + docs/release persist-credentials: false # The agent reads docs/agents/changelog.md from the WORKING TREE, which is @@ -163,10 +164,17 @@ jobs: # detached rc-tag checkout is exactly that, so a COMPLIANT agent would # silently decline to generate on every promotion of an existing rc. # Overlay the current instructions so the agent reads today's contract. + # changelog.md sends the agent to the checks in docs/release/changelogs.md + # and to hack/validate-changelog.sh, so those are overlaid too: the rc + # tag's copies predate any check added since, and an rc cut before the + # release docs were split into docs/release/ has no such directory. - name: Refresh agent instructions run: | cp .release-tooling/docs/agents/changelog.md docs/agents/changelog.md - echo "Refreshed docs/agents/changelog.md from ${GITHUB_REF_NAME}." + mkdir -p docs/release + cp .release-tooling/docs/release/changelogs.md docs/release/changelogs.md + cp .release-tooling/hack/validate-changelog.sh hack/validate-changelog.sh + echo "Refreshed docs/agents/changelog.md, docs/release/changelogs.md and hack/validate-changelog.sh from ${GITHUB_REF_NAME}." # Skip-priority + validate-then-fall-through: use a pre-existing changelog # only if it is USABLE, so an invalid higher-priority source can never diff --git a/.github/workflows/codegen-drift.yml b/.github/workflows/codegen-drift.yml index 0c02e5605..773a758f7 100644 --- a/.github/workflows/codegen-drift.yml +++ b/.github/workflows/codegen-drift.yml @@ -32,6 +32,9 @@ jobs: codegen-drift: name: Verify generated code is up to date runs-on: ubuntu-22.04 + env: + # The pipe falls back to direct on any proxy error (hack/common-envs.mk). + GOPROXY: "https://proxy.golang.org|direct" permissions: contents: read steps: diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 5d5ded72c..85b05a66e 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -24,6 +24,9 @@ jobs: name: Analyze (${{ matrix.language }}) runs-on: ubuntu-latest timeout-minutes: 120 + env: + # The pipe falls back to direct on any proxy error (hack/common-envs.mk). + GOPROXY: "https://proxy.golang.org|direct" permissions: # Upload CodeQL results to the code-scanning dashboard. On pull_request # this is also what lets CodeQL post new-alert annotations on the diff. diff --git a/.github/workflows/cut-prerelease.yaml b/.github/workflows/cut-prerelease.yaml index c3c31450f..bfd159d94 100644 --- a/.github/workflows/cut-prerelease.yaml +++ b/.github/workflows/cut-prerelease.yaml @@ -6,7 +6,7 @@ name: Cut Pre-release Tag # This is the single entry point for creating a pre-release. Stable vX.Y.Z tags # are never cut here (or by hand) — they are created write-once by # pull-requests-release.yaml finalize at a promote PR's merge commit. See -# docs/release.md and #2677. +# docs/release/stable-tags.md and #2677. # # Dispatch from the branch the tag belongs to: `main` for a new minor's # pre-release (vX.Y.0-rc.N), or `release-X.Y` for a patch line (vX.Y.Z-rc.N). @@ -48,8 +48,7 @@ concurrency: group: cut-prerelease cancel-in-progress: false -# The tag write happens via the app token, not GITHUB_TOKEN, so the job needs -# only read scope on the default token. +# Tag and branch writes use the app token so their push events trigger CI. permissions: contents: read @@ -58,6 +57,9 @@ jobs: name: Cut ${{ inputs.tag }} runs-on: ubuntu-latest timeout-minutes: 10 + permissions: + contents: read + actions: write steps: # Pure-input validation first — no token minted, no checkout, so a bad tag @@ -345,13 +347,14 @@ jobs: - name: Build the frozen line's packages artifact if: steps.freeze.outputs.created == 'true' env: - GH_TOKEN: ${{ steps.app-token.outputs.token }} + # workflow_dispatch can trigger a run with GITHUB_TOKEN. + GH_TOKEN: ${{ github.token }} BRANCH: release-${{ steps.parse.outputs.line }} run: | if gh workflow run build-release.yaml --ref "$BRANCH"; then echo "Dispatched build-release.yaml for $BRANCH; it publishes cozystack-packages:$BRANCH." else - echo "::warning::Could not dispatch build-release.yaml for $BRANCH (the CI app may lack 'actions: write')." + echo "::warning::Could not dispatch build-release.yaml for $BRANCH." echo "::warning::Until it runs, cozystack-packages:$BRANCH does not exist, and PRs onto $BRANCH test the image refs committed in the tree rather than the line's own build." echo "::warning::Start it by hand: gh workflow run build-release.yaml --ref $BRANCH" fi diff --git a/.github/workflows/e2e-fork.yaml b/.github/workflows/e2e-fork.yaml index 75ba10fe8..03c568395 100644 --- a/.github/workflows/e2e-fork.yaml +++ b/.github/workflows/e2e-fork.yaml @@ -61,7 +61,8 @@ jobs: # base-repo PR file list — NOT from the presence/absence of an artifact the # fork's own build controls. Fail-closed if the fork build failed or the # pr-patch artifact is missing; green-and-stop only for a PR whose file list is - # entirely under docs/ (verified against the base-repo API). + # entirely under docs/ or the CI-only tools cmd/backport-batch/ and + # cmd/api-gate/ (verified against the base-repo API). resolve: name: Resolve fork PR # Only fork PRs: head_repository differs from the base repository. Same-repo @@ -266,15 +267,21 @@ jobs: await decide('failure', 'PR file list hit the 3000-file API cap — cannot verify docs-only'); return; } + // Paths with nothing to build and nothing for e2e to install: docs, + // and the CI-only Go tools no image builds. pull-requests.yaml's + // plan job answers the same question with the same prefixes, and + // hack/gate-concurrency-contract.bats holds the two lists equal. + // // A rename reports the NEW path in `filename` and the old one in // `previous_filename`. Checking only `filename` would read a // packages/… -> docs/… rename as docs-only, when it in fact removes - // a code path. BOTH sides must be under docs/ to count as docs-only. - const isDocs = p => typeof p === 'string' && p.startsWith('docs/'); - const hasNonDocs = files.some(f => - !isDocs(f.filename) || (f.previous_filename && !isDocs(f.previous_filename))); - if (!hasNonDocs) { - await decide('success', 'docs-only PR (verified via PR file list) — e2e not required'); + // a code path. BOTH sides must be under these prefixes to count. + const noRuntimePrefixes = ['docs/', 'cmd/backport-batch/', 'cmd/api-gate/']; + const isNoRuntime = p => typeof p === 'string' && noRuntimePrefixes.some(x => p.startsWith(x)); + const hasRuntime = files.some(f => + !isNoRuntime(f.filename) || (f.previous_filename && !isNoRuntime(f.previous_filename))); + if (!hasRuntime) { + await decide('success', 'docs or CI-only tools (verified via PR file list) — e2e not required'); return; } @@ -349,22 +356,13 @@ jobs: outputs: packages_digest: ${{ steps.push.outputs.packages_digest }} steps: - - name: Set up toolchain (skopeo, flux) - env: - # Pin the flux CLI instead of install.sh's rolling latest. This is the - # one privileged job that runs a remote installer as root right before - # the OCIR token is loaded, so it pins where the rest of CI does not; - # keep it in step with the flux distro cozystack ships - # (packages/system/fluxcd, 2.8.x). - FLUX_VERSION: "2.8.6" + - name: Set up flux + uses: fluxcd/flux2/action@04acaec6161ac4fb1a82ffafa88901c03271d34f # v2.8.6 + with: + version: "2.8.6" + - name: Set up toolchain (skopeo) run: | command -v skopeo >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq skopeo; } - if ! command -v flux >/dev/null; then - s="$(mktemp)" - curl -fsSL https://fluxcd.io/install.sh -o "$s" - sudo env "FLUX_VERSION=$FLUX_VERSION" bash "$s" - rm -f "$s" - fi # The base repo's own merge ref — safe to fetch, not fork-controlled code # execution. pr.patch is applied as DATA below; nothing from the tree runs. - name: Checkout PR merge ref @@ -373,6 +371,11 @@ jobs: ref: refs/pull/${{ needs.resolve.outputs.pr_number }}/merge fetch-depth: 0 persist-credentials: false + # checkout v4.4.0 and later refuse a fork's code under workflow_run + # without this opt-in. The boundary is the one the header describes: + # no fork-authored script runs in `publish`, and `e2e` holds no push + # token. + allow-unsafe-pr-checkout: true # Guard against a TOCTOU race: the status is stamped on the SHA `resolve` # saw, but refs/pull/N/merge tracks the live PR head. If the fork pushed # again between resolve and here, HEAD^2 (the merge ref's PR-head parent) @@ -544,9 +547,10 @@ jobs: # per-node 8 CPU / 24 GiB in hack/e2e-compose.yaml is why the class is this # one. See the `e2e` job there for the full sizing note. runs-on: oracle-vm-32cpu-128gb-x86-64 - # Sized above what the tenant-Kubernetes pair can spend on a failing run, and - # held to one figure across every lane that runs the suite. - timeout-minutes: 215 + # Covers a green full suite. It does not cover a tenant-Kubernetes suite + # running into its node-join deadline, so a red there can end as a + # cancelled job. Held to one figure across every lane that runs the suite. + timeout-minutes: 265 permissions: contents: read packages: read @@ -566,6 +570,7 @@ jobs: ref: refs/pull/${{ needs.resolve.outputs.pr_number }}/merge fetch-depth: 0 persist-credentials: false + allow-unsafe-pr-checkout: true # Same TOCTOU guard as `publish`: refuse to test a merge ref that moved off # the SHA the status is stamped on (see the publish job for the rationale). - name: Assert checkout matches resolved head SHA @@ -575,8 +580,18 @@ jobs: got="$(git rev-parse HEAD^2)" [ "$got" = "$EXPECTED_SHA" ] || { echo "::error::merge ref moved: HEAD^2=$got != resolved $EXPECTED_SHA"; exit 1; } - name: Set up toolchain (yq) + env: + YQ_VERSION: "4.53.3" + YQ_SHA256: "fa52a4e758c63d38299163fbdd1edfb4c4963247918bf9c1c5d31d84789eded4" run: | - command -v yq >/dev/null || { sudo curl -sSL -o /usr/local/bin/yq https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 && sudo chmod +x /usr/local/bin/yq; } + if ! yq --version 2>/dev/null | grep -q "mikefarah.* version v${YQ_VERSION}\$"; then + yq_bin="$(mktemp)" + curl -fsSL -o "$yq_bin" \ + "https://github.com/mikefarah/yq/releases/download/v${YQ_VERSION}/yq_linux_amd64" + printf '%s %s\n' "$YQ_SHA256" "$yq_bin" | sha256sum -c - + sudo install -m 0755 "$yq_bin" /usr/local/bin/yq + rm -f "$yq_bin" + fi - name: Download pr.patch uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 with: @@ -633,29 +648,6 @@ jobs: echo "Attempt $attempt failed, retrying..." make -C packages/core/testing SANDBOX_NAME=$SANDBOX_NAME delete-cluster-container || true done - - name: Install Cozystack into sandbox - env: - COZY_APISERVER_ENDPOINT: https://192.168.123.11:6443 - COZY_LINSTOR_DRBD_ENABLED: "false" - COZY_E2E_STORAGE_CLASS: local - run: | - if ! make -C packages/core/testing SANDBOX_NAME=$SANDBOX_NAME install-cozystack; then - echo "❌ Install failed (no retry — diagnostics below)" - echo "::group::HelmRelease status" - docker exec "$SANDBOX_NAME" sh -c 'kubectl get hr -A -o wide 2>&1 | tail -100' || true - echo "::endgroup::" - echo "::group::not-Ready HelmReleases" - docker exec "$SANDBOX_NAME" sh -c 'kubectl get hr -A --no-headers 2>/dev/null | awk "\$4 != \"True\" {print \$1\" \"\$2}"' \ - | while read -r ns name; do - echo "--- $ns/$name ---" - docker exec "$SANDBOX_NAME" sh -c "kubectl describe hr '$name' -n '$ns' 2>&1 | tail -50" || true - done - echo "::endgroup::" - exit 1 - fi - - name: Run OpenAPI tests - run: | - make -C packages/core/testing SANDBOX_NAME=$SANDBOX_NAME test-openapi # Test-Impact Analysis: select only the Chainsaw suites the PR diff # affects. The changed-file list is resolve's TRUSTED base-repo listFiles # (base64 through the job output), NOT a git diff on the fork-controlled @@ -689,10 +681,43 @@ jobs: else echo "skip=false" >> "$GITHUB_OUTPUT" fi - # Single `chainsaw test` invocation, no per-app retry loop (e2e-testing.md - # §1) — Chainsaw polls each assertion to its own timeout. Full suite only - # when the full-e2e label skipped selection: if `select` ran and came back - # empty it set skip=true and this step never starts. + # The complement of what the selected suites need, for a reduced + # install. An empty selection installs everything as before. + disabled="" + if [ -n "${apps}" ]; then + disabled="$(./hack/select-install.sh --disabled "${apps}")" + fi + echo "Disabled packages: ${disabled:-}" + echo "disabled=${disabled}" >> "$GITHUB_OUTPUT" + - name: Install Cozystack into sandbox + env: + COZY_APISERVER_ENDPOINT: https://192.168.123.11:6443 + COZY_LINSTOR_DRBD_ENABLED: "false" + COZY_E2E_STORAGE_CLASS: local + COZY_DISABLED_PACKAGES: ${{ steps.select.outputs.disabled }} + run: | + if ! make -C packages/core/testing SANDBOX_NAME=$SANDBOX_NAME install-cozystack; then + echo "❌ Install failed (no retry — diagnostics below)" + echo "::group::HelmRelease status" + docker exec "$SANDBOX_NAME" sh -c 'kubectl get hr -A -o wide 2>&1 | tail -100' || true + echo "::endgroup::" + echo "::group::not-Ready HelmReleases" + docker exec "$SANDBOX_NAME" sh -c 'kubectl get hr -A --no-headers 2>/dev/null | awk "\$4 != \"True\" {print \$1\" \"\$2}"' \ + | while read -r ns name; do + echo "--- $ns/$name ---" + docker exec "$SANDBOX_NAME" sh -c "kubectl describe hr '$name' -n '$ns' 2>&1 | tail -50" || true + done + echo "::endgroup::" + exit 1 + fi + - name: Run OpenAPI tests + run: | + make -C packages/core/testing SANDBOX_NAME=$SANDBOX_NAME test-openapi + # Each suite runs once, one `chainsaw test` per suite directory, with no + # retry loop (e2e-testing.md §1) — Chainsaw polls each assertion to its own + # timeout. Full suite only when the full-e2e label skipped selection: if + # `select` ran and came back empty it set skip=true and this step never + # starts. - name: Run E2E tests id: e2e_tests if: ${{ steps.select.outputs.skip != 'true' }} @@ -712,7 +737,7 @@ jobs: echo "Running selected chainsaw suites: $suites" fi if ! make -C packages/core/testing SANDBOX_NAME=$SANDBOX_NAME test-chainsaw CHAINSAW_SUITES="$suites"; then - echo "❌ Chainsaw E2E failed (see the assertion diffs above and diagnostics below)" + echo "❌ Chainsaw E2E failed (see the assertion diffs or LEAKED-PODS lines above and diagnostics below)" echo "::group::Diagnostics: HelmRelease status" docker exec "$SANDBOX_NAME" sh -c 'kubectl get hr -A -o wide 2>&1 | tail -50' || true echo "::endgroup::" @@ -753,21 +778,6 @@ jobs: name: cozyreport path: _out/cozyreport.tgz if-no-files-found: warn - # Both halves, and in this order: the compose project owns the nodes and - # the zpools outlive it. - - name: Tear down sandbox - if: always() - run: | - # Annotated, not fatal: same reasoning as the in-tree lane. The runner - # is discarded after the job, so a dirty host has no next tenant, and - # failing here would post the required "E2E Tests" status as a failure - # indistinguishable from a real one. - cleanup_rc=0 - make -C packages/core/testing SANDBOX_NAME=$SANDBOX_NAME delete-cluster-container || cleanup_rc=$? - make -C packages/core/testing SANDBOX_NAME=$SANDBOX_NAME delete || true - if [ "$cleanup_rc" -ne 0 ]; then - echo "::error title=sandbox teardown::teardown exited $cleanup_rc; the host may hold a stale compose project or zpool" - fi # Flip the pending "E2E Tests" commit status posted by `resolve` to its # terminal state. Runs on failure too, so a failed publish or e2e turns the diff --git a/.github/workflows/e2e-isp-hosted.yaml b/.github/workflows/e2e-isp-hosted.yaml new file mode 100644 index 000000000..9d17e4508 --- /dev/null +++ b/.github/workflows/e2e-isp-hosted.yaml @@ -0,0 +1,187 @@ +name: E2E isp-hosted + +# Installs the isp-hosted platform variant, through the hosted installer +# variant, on a kind cluster, and checks that every HelmRelease goes Ready. No +# other lane installs either variant: the PR, nightly and tag lanes all run +# isp-full on Talos, where Cozystack itself provides the CNI and the storage. +# kind is the managed-cluster shape isp-hosted is for: its CNI, kube-proxy and +# default StorageClass come from the cluster, and there is no Cilium, no +# LINSTOR and no `replicated` class. That absence is the thing under test. +# +# It installs the latest nightly rather than building anything: the GHCR +# nightly closure is complete and public. A pull request trigger is +# deliberately absent, because a run here would install the nightly images, +# not the pull request's, and report on code the pull request did not change. + +on: + schedule: + - cron: '0 5 * * *' # 05:00 UTC, after nightly.yaml's 02:00 mirror has published + workflow_dispatch: {} + +env: + PACKAGES_REPO: ghcr.io/cozystack/cozystack/cozystack-packages + # Release notes of kind v0.32.0 are the source of both pins: the binary's + # published kind-linux-amd64.sha256sum, and the node image digest listed for + # it. v1.33.12 matches the Kubernetes version hack/e2e-container-up.sh gives + # the Talos lanes, so the variant is the only thing that differs. + KIND_VERSION: v0.32.0 + KIND_SHA256: 50030de23cf40a18505f20426f6a8506bedf13c6e509244bd1fa9463721b0f54 + KIND_NODE_IMAGE: kindest/node:v1.33.12@sha256:3f5c8443c620245e4d355cfe09e96a91ead32ceaa569d3f1ca9edf0cb2fe2ff4 + KIND_CLUSTER: cozy-hosted + +concurrency: + group: e2e-isp-hosted + cancel-in-progress: false + +permissions: + contents: read + +jobs: + e2e: + name: E2E (isp-hosted on kind) + # The whole platform lands on one kind node with nothing pre-pulled. The + # smaller 4-vCPU class was not tried; sizing down is left to a measured run. + runs-on: oracle-vm-24cpu-96gb-x86-64 + # Above the failing path's sum, so the job ceiling never cuts off the + # report: three prepare attempts at kind's 5m wait, the install's 30m + # readiness gate plus its setup, and the 30m collect step. + timeout-minutes: 120 + permissions: + contents: read + packages: read + steps: + - name: Set up flux + uses: fluxcd/flux2/action@04acaec6161ac4fb1a82ffafa88901c03271d34f # v2.8.6 + with: + version: "2.8.6" + - name: Set up toolchain (oras) + run: | + command -v oras >/dev/null || { curl -fsSL https://github.com/oras-project/oras/releases/download/v1.2.0/oras_1.2.0_linux_amd64.tar.gz | sudo tar -xz -C /usr/local/bin oras; } + + - name: Login to GHCR + env: + GHCR_USER: ${{ github.actor }} + GHCR_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + echo "$GHCR_TOKEN" | docker login ghcr.io -u "$GHCR_USER" --password-stdin + echo "$GHCR_TOKEN" | oras login ghcr.io -u "$GHCR_USER" --password-stdin + + # One manifest fetch gives both the digest and the revision, so a nightly + # published between two reads cannot pair one commit's name with another + # tree in the log. + - name: Resolve the latest nightly + id: resolve + run: | + set -eu + manifest="${RUNNER_TEMP}/cozystack-packages-nightly.json" + oras manifest fetch "${PACKAGES_REPO}:nightly" > "$manifest" + digest="sha256:$(sha256sum "$manifest" | cut -d' ' -f1)" + rev="$(yq -r '.annotations["org.opencontainers.image.revision"] // ""' -p json "$manifest")" + echo "digest=$digest" >> "$GITHUB_OUTPUT" + echo "Installing nightly ${rev:-}, packages ${digest}" + + - name: Checkout code + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + fetch-depth: 1 + persist-credentials: false + + # The product under test is the nightly's packages tree, overlaid as + # nightly.yaml does. The harness (hack/ and the testing Makefile's + # recipes) stays at the commit that triggered the run, so a change to the + # lane can be tried on a branch before any nightly carries it; on the + # schedule that commit is main a few hours past the nightly's. + - name: Stage the nightly install tree + env: + DIGEST: ${{ steps.resolve.outputs.digest }} + run: | + set -eu + rm -rf _rw && mkdir -p _rw + flux pull artifact "oci://${PACKAGES_REPO}@${DIGEST}" --output _rw + cp -r _rw/. packages/ + rm -rf _rw + git checkout HEAD -- packages/core/testing/Makefile + yq -i ".cozystackOperator.platformSourceUrl = \"oci://${PACKAGES_REPO}\"" packages/core/installer/values.yaml + yq -i ".cozystackOperator.platformSourceRef = \"digest=${DIGEST}\"" packages/core/installer/values.yaml + + - name: Install kind + run: | + set -eu + curl -fsSLo "${RUNNER_TEMP}/kind" "https://github.com/kubernetes-sigs/kind/releases/download/${KIND_VERSION}/kind-linux-amd64" + echo "${KIND_SHA256} ${RUNNER_TEMP}/kind" | sha256sum --check + sudo install -m 0755 "${RUNNER_TEMP}/kind" /usr/local/bin/kind + + - name: Set sandbox ID + run: echo "SANDBOX_NAME=cozy-e2e-sandbox-$(echo "${GITHUB_REPOSITORY}:${GITHUB_WORKFLOW}:${GITHUB_REF}" | sha256sum | cut -c1-10)" >> "$GITHUB_ENV" + + # Pure infrastructure, so it may be retried; the cluster and the sandbox are + # both removed between attempts so no attempt adopts a half-built one. + # `kubeconfig` at the checkout root is what `apply` copies to + # /workspace/kubeconfig, the sandbox's KUBECONFIG; --internal addresses + # the control plane by container name, which the sandbox resolves once + # it is on the kind network. + - name: Prepare environment + run: | + # Many controllers on one node exhaust the stock inotify limits, which + # kind documents as a cause of pods failing with "too many open files". + sudo sysctl -w fs.inotify.max_user_instances=8192 fs.inotify.max_user_watches=524288 + attempt=0 + until kind create cluster --name "$KIND_CLUSTER" --image "$KIND_NODE_IMAGE" --config hack/e2e-isp-hosted-kind.yaml --wait 5m \ + && kind get kubeconfig --internal --name "$KIND_CLUSTER" > ./kubeconfig \ + && make -C packages/core/testing SANDBOX_NAME="$SANDBOX_NAME" apply \ + && docker network connect kind "$SANDBOX_NAME"; do + attempt=$((attempt + 1)) + make -C packages/core/testing SANDBOX_NAME="$SANDBOX_NAME" delete || true + kind delete cluster --name "$KIND_CLUSTER" || true + if [ $attempt -ge 3 ]; then echo "Attempt $attempt failed, exiting..."; exit 1; fi + echo "Attempt $attempt failed, retrying..." + done + + - name: Install Cozystack into sandbox + run: | + if ! make -C packages/core/testing SANDBOX_NAME="$SANDBOX_NAME" install-cozystack-hosted; then + echo "❌ Install failed (no retry — diagnostics below)" + echo "::group::HelmRelease status" + docker exec "$SANDBOX_NAME" sh -c 'kubectl get hr -A -o wide 2>&1 | tail -100' || true + echo "::endgroup::" + echo "::group::not-Ready HelmReleases" + docker exec "$SANDBOX_NAME" sh -c 'kubectl get hr -A --no-headers 2>/dev/null | awk "\$4 != \"True\" {print \$1\" \"\$2}"' \ + | while read -r ns name; do + echo "--- $ns/$name ---" + docker exec "$SANDBOX_NAME" sh -c "kubectl describe hr '$name' -n '$ns' 2>&1 | tail -50" || true + done + echo "::endgroup::" + echo "::group::Pods not Running" + docker exec "$SANDBOX_NAME" sh -c 'kubectl get pods -A --field-selector=status.phase!=Running,status.phase!=Succeeded -o wide 2>&1 | tail -60' || true + echo "::endgroup::" + exit 1 + fi + + # Same bound and the same tolerance as the collect step in nightly.yaml, + # for the reasons written there. + - name: Collect report + id: collect_report + if: always() + timeout-minutes: 30 + continue-on-error: true + run: | + make -C packages/core/testing SANDBOX_NAME="$SANDBOX_NAME" collect-report || true + + - name: Report collection overran its ceiling + if: always() && steps.collect_report.outcome == 'failure' + run: | + echo "::warning title=cozyreport::Collect report ended non-zero -- its timeout-minutes fired, or the step failed before the collector ran; cozyreport.tgz is missing or partial for this run" + + - name: Upload cozyreport.tgz + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: cozyreport-isp-hosted + path: _out/cozyreport.tgz + if-no-files-found: warn + + - name: Tear down + if: always() + run: | + make -C packages/core/testing SANDBOX_NAME="$SANDBOX_NAME" delete || true + kind delete cluster --name "$KIND_CLUSTER" || true diff --git a/.github/workflows/e2e-proxmox.yaml b/.github/workflows/e2e-proxmox.yaml new file mode 100644 index 000000000..21515016d --- /dev/null +++ b/.github/workflows/e2e-proxmox.yaml @@ -0,0 +1,167 @@ +name: E2E (proxmox) + +# The Proxmox substrate's own lane, separate from every other e2e workflow for +# one reason that cannot be engineered away: it needs a Proxmox hypervisor, and +# the oracle-vm-* runners the other lanes use will never have one. +# +# Deliberately NOT triggered by pull_request. A self-hosted runner executes +# whatever the workflow checks out, and this one holds credentials to a +# hypervisor and a live cluster; letting an arbitrary fork PR start it would +# hand both to its author. Manual dispatch and a schedule are the whole trigger +# surface, and both come from someone who already has write access. +on: + workflow_dispatch: + inputs: + keep_tenant: + description: "Leave the tenant in place after the run, for debugging" + type: boolean + default: false + schedule: + # Nightly, offset from the upstream lanes so a shared hypervisor is not + # asked to do two things at once. + - cron: "40 2 * * *" + +permissions: + contents: read + +concurrency: + # One hypervisor, one tenant namespace, fixed VM ids — two runs would fight + # over all three. Never cancel in progress: a killed run leaks VMs. + group: e2e-proxmox + cancel-in-progress: false + +jobs: + e2e: + name: Proxmox substrate + # The job needs a self-hosted runner carrying the `proxmox` label. On a + # repository without one a scheduled run would sit in the queue until GitHub + # cancels it, so the schedule fires only where the stand is declared; + # manual dispatch always runs. + if: github.event_name == 'workflow_dispatch' || vars.PROXMOX_NIGHTLY == 'true' + runs-on: [self-hosted, proxmox] + timeout-minutes: 90 + env: + COZY_PROXMOX_NS: tenant-e2eproxmox + COZY_PROXMOX_CLUSTER: k8s-e2e + # No fallbacks: an unset variable fails the first step below instead of + # sending a key to a guessed address or probing a storage the stand lacks. + COZY_PROXMOX_STORAGE: ${{ vars.PROXMOX_STORAGE }} + COZY_PVE_SSH: ${{ vars.PROXMOX_SSH }} + COZY_PVE_SSH_KEY: ${{ github.workspace }}/.ssh-pve + COZY_KEEP_TENANT: ${{ inputs.keep_tenant == true }} + steps: + - name: Checkout + uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + with: + persist-credentials: false + + - name: Require the stand's variables + env: + PVE_URL: ${{ vars.PROXMOX_URL }} + PVE_REGION: ${{ vars.PROXMOX_REGION }} + run: | + set -eu + for v in COZY_PROXMOX_STORAGE COZY_PVE_SSH PVE_URL PVE_REGION; do + eval "val=\${$v:-}" + [ -n "$val" ] || { echo "$v is unset: set the PROXMOX_* repository variables for this stand" >&2; exit 1; } + done + + - name: Stage credentials + id: stage + env: + KUBECONFIG_B64: ${{ secrets.COZY_KUBECONFIG }} + PVE_SSH_KEY: ${{ secrets.PROXMOX_SSH_KEY }} + PVE_TOKEN_ID: ${{ secrets.PROXMOX_TOKEN_ID }} + PVE_TOKEN_SECRET: ${{ secrets.PROXMOX_TOKEN_SECRET }} + PVE_URL: ${{ vars.PROXMOX_URL }} + PVE_REGION: ${{ vars.PROXMOX_REGION }} + run: | + set -eu + umask 077 + printf '%s' "$KUBECONFIG_B64" | base64 -d > "$GITHUB_WORKSPACE/.kubeconfig" + # Unless the current context resolves to a server, client-go either + # fails or falls back to its defaults, in-cluster credentials among + # them, and the calls below would reach a cluster other than the + # stand's. Tear down repeats this check. + server=$(kubectl --kubeconfig "$GITHUB_WORKSPACE/.kubeconfig" config view --minify \ + -o jsonpath='{.clusters[0].cluster.server}' 2>"$RUNNER_TEMP/kubeconfig-check.err" || true) + if [ -z "$server" ]; then + echo "COZY_KUBECONFIG does not resolve to a server" >&2 + # Empty when the context resolves to a cluster with no server. + cat "$RUNNER_TEMP/kubeconfig-check.err" >&2 + exit 1 + fi + # OpenSSH refuses a private key whose last line has no newline ("error + # in libcrypto"), and `gh secret set` strips it from a key read from + # stdin. A second newline, when the secret kept its own, is harmless. + printf '%s\n' "$PVE_SSH_KEY" > "$COZY_PVE_SSH_KEY" + + # The credentials the management-side CSI controller and CCM read. A + # Secret rather than values so no token is ever written into a + # rendered HelmRelease. + kubectl --kubeconfig "$GITHUB_WORKSPACE/.kubeconfig" create namespace "$COZY_PROXMOX_NS" \ + --dry-run=client -o yaml | kubectl --kubeconfig "$GITHUB_WORKSPACE/.kubeconfig" apply -f - + kubectl --kubeconfig "$GITHUB_WORKSPACE/.kubeconfig" -n "$COZY_PROXMOX_NS" \ + create secret generic proxmox-credentials \ + --from-literal=url="$PVE_URL" \ + --from-literal=token_id="$PVE_TOKEN_ID" \ + --from-literal=token_secret="$PVE_TOKEN_SECRET" \ + --from-literal=region="$PVE_REGION" \ + --dry-run=client -o yaml | kubectl --kubeconfig "$GITHUB_WORKSPACE/.kubeconfig" apply -f - + + - name: Enable the suite + # It ships disabled so the normal lanes cannot select it; this is the + # one place that is allowed to turn it on. + run: mv hack/e2e-chainsaw/kubernetes-proxmox/chainsaw-test.yaml.disabled + hack/e2e-chainsaw/kubernetes-proxmox/chainsaw-test.yaml + + - name: Run the Proxmox suite + env: + KUBECONFIG: ${{ github.workspace }}/.kubeconfig + run: | + chainsaw test \ + --config hack/e2e-chainsaw/.chainsaw.yaml \ + --test-dir hack/e2e-chainsaw/kubernetes-proxmox + + - name: Tear down + # always(), because the whole point of the teardown is the failing run: + # a leaked tenant leaves VMs on the hypervisor and the next run inherits + # them. + if: always() && !inputs.keep_tenant + env: + STAGE_OUTCOME: ${{ steps.stage.outcome }} + run: | + set -eu + kc="$GITHUB_WORKSPACE/.kubeconfig" + # The suite runs only after Stage succeeds, so without that this run + # created no tenant. + if [ "$STAGE_OUTCOME" != success ]; then + echo "::notice::Tear down skipped: Stage credentials ended $STAGE_OUTCOME, so this run created no tenant" + exit 0 + fi + # The check Stage makes. Every call names the file, so none falls back + # to this self-hosted runner's own kubeconfig. Failing it here means + # the file broke after Stage, and the tenant may still be live. + server=$(kubectl --kubeconfig "$kc" config view --minify \ + -o jsonpath='{.clusters[0].cluster.server}' 2>"$RUNNER_TEMP/kubeconfig-check.err" || true) + if [ -z "$server" ]; then + echo "::error::Tear down did not run: $kc no longer resolves to a server, so tenant e2eproxmox and its VMs may still be live" + cat "$RUNNER_TEMP/kubeconfig-check.err" + exit 1 + fi + # A failed delete must not stop the ones after it: stopping there leaves + # behind exactly the VMs this step exists to remove. The step still + # fails at the end. + rc=0 + kubectl --kubeconfig "$kc" delete kubernetesnodes.apps.cozystack.io -n "$COZY_PROXMOX_NS" --all --ignore-not-found || rc=1 + kubectl --kubeconfig "$kc" delete kubernetes.apps.cozystack.io -n "$COZY_PROXMOX_NS" --all --ignore-not-found || rc=1 + kubectl --kubeconfig "$kc" delete tenant.apps.cozystack.io e2eproxmox -n tenant-root --ignore-not-found || rc=1 + exit "$rc" + + - name: Remove staged credentials + if: always() + # The tenant kubeconfig is the suite's, fetched by run-proxmox.sh into + # RUNNER_TEMP, which the runner exports into every step (the runner + # context is not allowed in job-level env); its finally removes it too, + # but a run killed mid-step never reaches that. + run: rm -f "$GITHUB_WORKSPACE/.kubeconfig" "$COZY_PVE_SSH_KEY" "$RUNNER_TEMP/proxmox-e2e-tenant.kubeconfig" diff --git a/.github/workflows/e2e-tag.yaml b/.github/workflows/e2e-tag.yaml index dd072449c..d9bba8559 100644 --- a/.github/workflows/e2e-tag.yaml +++ b/.github/workflows/e2e-tag.yaml @@ -11,8 +11,10 @@ name: E2E Release Tag # This lane validates published tags only; draft and promote-time validation are # explicitly out of scope because release checks run at RC publication time. # Prerelease tags use the matching digest-pinned staging branch, while stable -# tags use their pinned merge tree directly. In both cases the nocloud disk -# comes from the published release identified by the same tag. +# tags use their pinned merge tree directly. The nodes run as Talos containers +# booted from the upstream image, so the release's nocloud disk is required to +# exist but is not what the suite runs on. It is still required because users +# install from it, and promote-rc.yaml checks it for an rc only. on: workflow_call: @@ -37,8 +39,8 @@ concurrency: group: e2e-tag-${{ inputs.tag }} cancel-in-progress: false -# Listing published releases, reading Git refs, downloading a release asset, and -# checking out the pinned tree require only repository contents read access. +# Listing published releases, reading Git refs and checking out the pinned tree +# require only repository contents read access. # Draft releases are not part of this lane's contract. The public GHCR images # referenced by that tree need no package token. # @@ -57,7 +59,6 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 10 outputs: - disk_id: ${{ steps.resolve.outputs.disk_id }} tree_ref: ${{ steps.resolve.outputs.tree_ref }} steps: - name: Validate tag and resolve release @@ -123,20 +124,20 @@ jobs: throw error; } - core.setOutput('disk_id', String(disk.id)); core.setOutput('tree_ref', treeRef); core.info(`Resolved ${tag}: tree '${treeRef}', disk asset ${disk.id}`); e2e: name: E2E ${{ inputs.tag }} (full suite) needs: resolve - # The sandbox boots three 8-vCPU / 24-GiB QEMU guests. This runner leaves - # enough host headroom for QEMU, networking, containerd, and the runner - # agent while the full platform installs across all three guests. + # The sandbox runs three 8-vCPU / 24-GiB Talos containers. This runner + # leaves enough host headroom for networking, containerd, and the runner + # agent while the full platform installs across all three nodes. runs-on: oracle-vm-32cpu-128gb-x86-64 - # Sized above what the tenant-Kubernetes pair can spend on a failing run, and - # held to one figure across every lane that runs the suite. - timeout-minutes: 215 + # Covers a green full suite. It does not cover a tenant-Kubernetes suite + # running into its node-join deadline, so a red there can end as a + # cancelled job. Held to one figure across every lane that runs the suite. + timeout-minutes: 265 permissions: contents: read checks: write # Breakpoint action updates its dedicated "Breakpoint Open" Check Run. @@ -150,45 +151,74 @@ jobs: fetch-depth: 1 persist-credentials: false - - name: Download disk asset from release - env: - DISK_ID: ${{ needs.resolve.outputs.disk_id }} - GH_TOKEN: ${{ github.token }} - run: | - mkdir -p _out/assets - curl --fail-with-body --silent --show-error --location \ - -H "Authorization: Bearer ${GH_TOKEN}" \ - -H "Accept: application/octet-stream" \ - -o _out/assets/nocloud-amd64.raw.xz \ - "https://api.github.com/repos/${GITHUB_REPOSITORY}/releases/assets/${DISK_ID}" - - name: Set sandbox ID env: TAG: ${{ inputs.tag }} run: echo "SANDBOX_NAME=cozy-e2e-sandbox-$(echo "${GITHUB_REPOSITORY}:${GITHUB_WORKFLOW}:${TAG}" | sha256sum | cut -c1-10)" >> "$GITHUB_ENV" + # tags.yaml calls the e2e-tag.yaml from the tag's own commit, so this can + # only fire on a dispatch from a newer ref against an older tag. + - name: Require a container-lane tree + env: + TAG: ${{ inputs.tag }} + run: | + if [ ! -f hack/e2e-compose.yaml ]; then + echo "::error title=e2e-tag::${TAG} predates the container lane; dispatch e2e-tag.yaml with --ref ${TAG} to run it on the lane it shipped with" + exit 1 + fi + - name: Prepare workspace run: | rm -rf "/tmp/$SANDBOX_NAME" cp -r "${{ github.workspace }}" "/tmp/$SANDBOX_NAME" - # This is the only retried stage: Talos image unpacking, QEMU startup, and - # sandbox networking are pure runner infrastructure, not product logic. + # Talos cannot load kernel modules in container mode, so the nodes get + # exactly what this host has loaded. Why each module, and why failing + # here is better than an hour later: the same step in pull-requests.yaml. + - name: Prepare container-lane host + run: | + set -eu + for m in openvswitch zfs; do + grep -q "^${m} " /proc/modules && continue + if [ "${m}" = zfs ]; then + sudo apt-get update -qq + sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq zfsutils-linux + fi + sudo modprobe "${m}" || echo "${m}: modprobe failed" + done + missing='' + for m in openvswitch zfs; do + grep -q "^${m} " /proc/modules || missing="${missing} ${m}" + done + if [ -n "${missing}" ]; then + echo "::error title=container-lane host::kernel module(s) could not be loaded:${missing}" + exit 1 + fi + + # This is the only retried stage: Talos container startup and sandbox + # networking are pure runner infrastructure, not product logic. - name: Prepare environment run: | cd "/tmp/$SANDBOX_NAME" attempt=0 - until make SANDBOX_NAME=$SANDBOX_NAME prepare-env; do + until make SANDBOX_NAME="$SANDBOX_NAME" prepare-env-container; do attempt=$((attempt + 1)) if [ $attempt -ge 3 ]; then echo "Attempt $attempt failed, exiting..." exit 1 fi echo "Attempt $attempt failed, retrying..." + make -C packages/core/testing SANDBOX_NAME="$SANDBOX_NAME" delete-cluster-container || true done echo "Prepare environment completed after $((attempt + 1)) attempts" - name: Install Cozystack into sandbox + env: + # No ARP VIP in container mode: .11 is a plain control-plane node. + COZY_APISERVER_ENDPOINT: https://192.168.123.11:6443 + # The nodes share the runner kernel and cannot load DRBD. + COZY_LINSTOR_DRBD_ENABLED: "false" + COZY_E2E_STORAGE_CLASS: local run: | cd "/tmp/$SANDBOX_NAME" if ! make -C packages/core/testing SANDBOX_NAME=$SANDBOX_NAME install-cozystack; then @@ -218,10 +248,12 @@ jobs: # CHAINSAW_SUITES is the testing Makefile's full-suite mode. - name: Run E2E tests (full suite) id: e2e_tests + env: + COZY_E2E_STORAGE_CLASS: local run: | cd "/tmp/$SANDBOX_NAME" if ! make -C packages/core/testing SANDBOX_NAME=$SANDBOX_NAME test-chainsaw CHAINSAW_SUITES=""; then - echo "❌ Chainsaw E2E failed (see the assertion diffs above and diagnostics below)" + echo "❌ Chainsaw E2E failed (see the assertion diffs or LEAKED-PODS lines above and diagnostics below)" echo "::group::Diagnostics: HelmRelease status" docker exec "$SANDBOX_NAME" sh -c 'kubectl get hr -A -o wide 2>&1 | tail -50' || true echo "::endgroup::" @@ -260,7 +292,7 @@ jobs: # collect-report packages cozyreport plus per-failed-test crust-gather # snapshots captured before Chainsaw cleanup. # - # A ceiling of its own, not the job's 215 minutes. `Upload cozyreport.tgz` + # A ceiling of its own, not the job's 265 minutes. `Upload cozyreport.tgz` # is the next step and the collector writes its tarball at the very end of # its run, so a read that never returns spends what is left of the job # budget, the job is cancelled, and the upload never runs -- the artifact @@ -307,12 +339,56 @@ jobs: cd "/tmp/$SANDBOX_NAME" make -C packages/core/testing SANDBOX_NAME=$SANDBOX_NAME collect-images || true + # Every image the nodes pulled, read from their image stores rather than + # from the pods still running, since the tests delete what they create. + # That covers chart defaults and operator-launched images the static gate + # in tags.yaml never sees, because the tree does not pin them by digest. + # A pre-release fails on a single-arch image, on a ref that cannot be + # read or is still rate-limited after the retries, or on a list the + # collection could not produce; a stable tag only warns, since it ships + # its rc's images unchanged. Before teardown, which runs whatever this + # step does. + - name: Audit pulled images are multi-arch + if: always() + env: + TAG: ${{ inputs.tag }} + run: | + set -o pipefail + cd "/tmp/$SANDBOX_NAME" + # A tag cut before the audit existed has neither the script nor the + # image list, and its e2e must still be re-runnable from main. + if [ ! -f hack/verify-multiarch.sh ]; then + echo "::warning title=multi-arch audit::the tree under test predates the multi-arch audit; skipped" + exit 0 + fi + mkdir -p _out + { command -v skopeo && command -v jq; } >/dev/null \ + || { sudo apt-get update -qq && sudo apt-get install -y -qq skopeo jq; } + status=0 + hack/verify-multiarch.sh --refs-file _out/image-refs.txt 2>&1 | tee _out/multiarch-audit.txt \ + || status=${PIPESTATUS[0]} + if [ "$status" -ne 0 ]; then + case "$TAG" in + *-*) exit 1 ;; + esac + # 1: the audit ran and flagged refs (single-arch, unreadable or + # rate-limited); anything else: it did not run. + if [ "$status" -eq 1 ]; then + echo "::warning title=multi-arch audit::some images pulled by e2e are not amd64+arm64 indexes or could not be checked; see multiarch-audit.txt" + else + echo "::warning title=multi-arch audit::the multi-arch audit did not run; see multiarch-audit.txt" + fi + fi + - name: Upload image list if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 with: name: image-list-${{ inputs.tag }} - path: /tmp/${{ env.SANDBOX_NAME }}/_out/images.txt + path: | + /tmp/${{ env.SANDBOX_NAME }}/_out/images.txt + /tmp/${{ env.SANDBOX_NAME }}/_out/image-refs.txt + /tmp/${{ env.SANDBOX_NAME }}/_out/multiarch-audit.txt # ▸ Open an SSH breakpoint to the failing sandbox so maintainers can attach, # inspect Talos/Cozystack state and resume with `breakpoint resume`. @@ -360,13 +436,17 @@ jobs: Resume from inside: `breakpoint resume`. Otherwise the breakpoint exits 10 minutes after the last SSH session disconnects. + # The compose project owns the nodes and the zpools outlive it, so both + # halves go, in this order. - name: Tear down sandbox if: always() - run: make -C packages/core/testing SANDBOX_NAME=$SANDBOX_NAME delete || true + run: | + make -C packages/core/testing SANDBOX_NAME="$SANDBOX_NAME" delete-cluster-container || true + make -C packages/core/testing SANDBOX_NAME="$SANDBOX_NAME" delete || true - name: Remove workspace if: always() - run: rm -rf "/tmp/$SANDBOX_NAME" + run: rm -rf "/tmp/${SANDBOX_NAME:?}" - name: Summarize outcome if: always() diff --git a/.github/workflows/nightly.yaml b/.github/workflows/nightly.yaml index ab6192ab8..57cce6790 100644 --- a/.github/workflows/nightly.yaml +++ b/.github/workflows/nightly.yaml @@ -10,7 +10,8 @@ name: Nightly # cozy-installer chart are re-published on GHCR so the whole install closure is # self-contained there. The only thing genuinely built is the Talos nocloud disk # (assembled from upstream profiles, independent of the registry), published as a -# GHCR OCI artifact so a nightly is installable on real hardware, not just e2e. +# GHCR OCI artifact so a nightly is installable on real hardware. The nightly +# e2e does not boot it. # # No GitHub release and no api/apps/v1alpha1 Go-module tag are created — a # nightly is an installable artifact set on GHCR, nothing more. retention.yaml @@ -52,11 +53,24 @@ jobs: packages_ref: ${{ steps.resolve.outputs.packages_ref }} packages_digest: ${{ steps.publish.outputs.packages_digest }} steps: - - name: Set up toolchain (skopeo, flux, yq, helm) + - name: Set up flux + uses: fluxcd/flux2/action@04acaec6161ac4fb1a82ffafa88901c03271d34f # v2.8.6 + with: + version: "2.8.6" + - name: Set up toolchain (skopeo, yq, helm) + env: + YQ_VERSION: "4.53.3" + YQ_SHA256: "fa52a4e758c63d38299163fbdd1edfb4c4963247918bf9c1c5d31d84789eded4" run: | command -v skopeo >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq skopeo; } - command -v flux >/dev/null || curl -fsSL https://fluxcd.io/install.sh | sudo bash - command -v yq >/dev/null || { sudo curl -sSL -o /usr/local/bin/yq https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 && sudo chmod +x /usr/local/bin/yq; } + if ! yq --version 2>/dev/null | grep -q "mikefarah.* version v${YQ_VERSION}\$"; then + yq_bin="$(mktemp)" + curl -fsSL -o "$yq_bin" \ + "https://github.com/mikefarah/yq/releases/download/v${YQ_VERSION}/yq_linux_amd64" + printf '%s %s\n' "$YQ_SHA256" "$yq_bin" | sha256sum -c - + sudo install -m 0755 "$yq_bin" /usr/local/bin/yq + rm -f "$yq_bin" + fi command -v helm >/dev/null || curl -fsSL https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash - name: Login to registries @@ -201,6 +215,9 @@ jobs: # rebuild of any cozystack image. - name: Build nocloud disk run: make -C packages/core/talos talos-nocloud + env: + # The e2e sandbox boots amd64 only. + PLATFORM: linux/amd64 - name: Publish disk to GHCR env: VERSION: ${{ needs.mirror.outputs.version }} @@ -217,19 +234,23 @@ jobs: oras tag "${DST_REGISTRY}/cozystack-nocloud:${VERSION}" nightly echo "Published cozystack-nocloud:${VERSION} (+ :nightly) to GHCR." - # ── Full e2e against the published GHCR closure (chart + images + disk). + # ── Full e2e against the published GHCR closure (chart + images), on the + # same Talos-container substrate as the PR lanes. The nodes boot the + # upstream Talos image, so the nocloud disk built above is published but + # not exercised here, and e2e does not wait for it. e2e: name: E2E (full suite) - needs: [mirror, build-disk] - # Same sandbox as the other e2e lanes: three QEMU guests at `-smp 8` commit - # 24 vCPU for the whole run, so the runner class has to be strictly larger, - # leaving the host its own cycles for QEMU's emulation and IO threads, + needs: [mirror] + # Same sandbox as the other e2e lanes: three nodes at 8 vCPU / 24 GiB each + # (hack/e2e-compose.yaml) commit 24 vCPU for the whole run, so the runner + # class has to be strictly larger, leaving the host its own cycles for # containerd and the runner agent. Enforced by # hack/sandbox-runner-headroom.bats. runs-on: oracle-vm-32cpu-128gb-x86-64 - # Sized above what the tenant-Kubernetes pair can spend on a failing run, and - # held to one figure across every lane that runs the suite. - timeout-minutes: 215 + # Covers a green full suite. It does not cover a tenant-Kubernetes suite + # running into its node-join deadline, so a red there can end as a + # cancelled job. Held to one figure across every lane that runs the suite. + timeout-minutes: 265 permissions: contents: read packages: read @@ -240,17 +261,16 @@ jobs: ref: ${{ needs.mirror.outputs.sha }} fetch-depth: 1 persist-credentials: false - - name: Set up toolchain (flux, oras) - run: | - command -v flux >/dev/null || curl -fsSL https://fluxcd.io/install.sh | sudo bash - command -v oras >/dev/null || { curl -fsSL https://github.com/oras-project/oras/releases/download/v1.2.0/oras_1.2.0_linux_amd64.tar.gz | sudo tar -xz -C /usr/local/bin oras; } + - name: Set up flux + uses: fluxcd/flux2/action@04acaec6161ac4fb1a82ffafa88901c03271d34f # v2.8.6 + with: + version: "2.8.6" - name: Login to GHCR env: GHCR_USER: ${{ github.actor }} GHCR_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | echo "$GHCR_TOKEN" | docker login "${DST_REGISTRY%%/*}" -u "$GHCR_USER" --password-stdin - echo "$GHCR_TOKEN" | oras login "${DST_REGISTRY%%/*}" -u "$GHCR_USER" --password-stdin # Overlay the GHCR-rewritten tree (operator image, .e2e.image and every # component now point at GHCR), then pin the installer chart to the GHCR @@ -269,27 +289,49 @@ jobs: yq -i ".cozystackOperator.platformSourceUrl = \"oci://${DST_REGISTRY}/cozystack-packages\"" packages/core/installer/values.yaml yq -i ".cozystackOperator.platformSourceRef = \"digest=${PACKAGES_DIGEST}\"" packages/core/installer/values.yaml - - name: Fetch nocloud disk from GHCR - env: - VERSION: ${{ needs.mirror.outputs.version }} - run: | - set -eu - mkdir -p _out/assets - oras pull "${DST_REGISTRY}/cozystack-nocloud:${VERSION}" --output _out/assets - - name: Set sandbox ID run: echo "SANDBOX_NAME=cozy-e2e-sandbox-$(echo "${GITHUB_REPOSITORY}:${GITHUB_WORKFLOW}:${GITHUB_REF}" | sha256sum | cut -c1-10)" >> "$GITHUB_ENV" + # Talos cannot load kernel modules in container mode, so the nodes get + # exactly what this host has loaded. Why each module, and why failing + # here is better than an hour later: the same step in pull-requests.yaml. + - name: Prepare container-lane host + run: | + set -eu + for m in openvswitch zfs; do + grep -q "^${m} " /proc/modules && continue + if [ "${m}" = zfs ]; then + sudo apt-get update -qq + sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq zfsutils-linux + fi + sudo modprobe "${m}" || echo "${m}: modprobe failed" + done + missing='' + for m in openvswitch zfs; do + grep -q "^${m} " /proc/modules || missing="${missing} ${m}" + done + if [ -n "${missing}" ]; then + echo "::error title=container-lane host::kernel module(s) could not be loaded:${missing}" + exit 1 + fi + - name: Prepare environment run: | attempt=0 - until make SANDBOX_NAME=$SANDBOX_NAME prepare-env; do + until make SANDBOX_NAME="$SANDBOX_NAME" prepare-env-container; do attempt=$((attempt + 1)) if [ $attempt -ge 3 ]; then echo "Attempt $attempt failed, exiting..."; exit 1; fi echo "Attempt $attempt failed, retrying..." + make -C packages/core/testing SANDBOX_NAME="$SANDBOX_NAME" delete-cluster-container || true done - name: Install Cozystack into sandbox + env: + # No ARP VIP in container mode: .11 is a plain control-plane node. + COZY_APISERVER_ENDPOINT: https://192.168.123.11:6443 + # The nodes share the runner kernel and cannot load DRBD. + COZY_LINSTOR_DRBD_ENABLED: "false" + COZY_E2E_STORAGE_CLASS: local run: | if ! make -C packages/core/testing SANDBOX_NAME=$SANDBOX_NAME install-cozystack; then echo "❌ Install failed (no retry — diagnostics below)" @@ -313,9 +355,11 @@ jobs: # Always the FULL app suite — a nightly has no diff to scope against, so # Test Impact Analysis does not apply (empty CHAINSAW_SUITES = whole suite). - name: Run E2E tests (full suite) + env: + COZY_E2E_STORAGE_CLASS: local run: | if ! make -C packages/core/testing SANDBOX_NAME=$SANDBOX_NAME test-chainsaw CHAINSAW_SUITES=""; then - echo "❌ Chainsaw E2E failed (see the assertion diffs above and diagnostics below)" + echo "❌ Chainsaw E2E failed (see the assertion diffs or LEAKED-PODS lines above and diagnostics below)" echo "::group::Diagnostics: HelmRelease status" docker exec "$SANDBOX_NAME" sh -c 'kubectl get hr -A -o wide 2>&1 | tail -50' || true echo "::endgroup::" @@ -341,7 +385,7 @@ jobs: path: _out/chainsaw-report.xml if-no-files-found: ignore - # A ceiling of its own, not the job's 215 minutes. `Upload cozyreport.tgz` + # A ceiling of its own, not the job's 265 minutes. `Upload cozyreport.tgz` # is the next step and the collector writes its tarball at the very end of # its run, so a read that never returns spends what is left of the job # budget, the job is cancelled, and the upload never runs -- the artifact @@ -380,6 +424,10 @@ jobs: path: _out/cozyreport.tgz if-no-files-found: warn + # The compose project owns the nodes and the zpools outlive it, so both + # halves go, in this order. - name: Tear down sandbox if: always() - run: make -C packages/core/testing SANDBOX_NAME=$SANDBOX_NAME delete || true + run: | + make -C packages/core/testing SANDBOX_NAME="$SANDBOX_NAME" delete-cluster-container || true + make -C packages/core/testing SANDBOX_NAME="$SANDBOX_NAME" delete || true diff --git a/.github/workflows/pr-labeler.yaml b/.github/workflows/pr-labeler.yaml index 45b559230..7aca218f7 100644 --- a/.github/workflows/pr-labeler.yaml +++ b/.github/workflows/pr-labeler.yaml @@ -24,7 +24,7 @@ jobs: with: script: | // Conventional Commits types accepted by Cozystack (per docs/agents/contributing.md): - // feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert + // feat, fix, security, docs, style, refactor, perf, test, build, ci, chore, revert // Mapping below maps a subset to kind/* — types not listed do not produce a kind/*. const typeToKind = { feat: 'kind/feature', @@ -32,7 +32,7 @@ jobs: docs: 'kind/documentation', chore: 'kind/cleanup', refactor: 'kind/cleanup', - // style, perf, test, build, ci, revert — no kind mapping + // security, style, perf, test, build, ci, revert — no kind mapping }; // scope -> area/* mapping. Keys are the scopes observed in cozystack issues @@ -41,6 +41,7 @@ jobs: // area/api 'api': 'area/api', 'cozystack-api': 'area/api', + 'registry': 'area/api', // area/ai 'agents': 'area/ai', @@ -51,14 +52,24 @@ jobs: // area/ci 'ci': 'area/ci', + 'workflows': 'area/ci', + 'labeler': 'area/ci', // area/dependencies — Renovate uses scope `deps` (see .github/renovate.json) 'deps': 'area/dependencies', + 'dependencies': 'area/dependencies', + 'renovate': 'area/dependencies', + + // area/dx — developer tooling: hack/, package Makefiles, cozypkg + 'dx': 'area/dx', + 'hack': 'area/dx', + 'cozypkg': 'area/dx', // area/dashboard 'dashboard': 'area/dashboard', 'cozystack-ui': 'area/dashboard', 'console': 'area/dashboard', + 'dashboard-controller': 'area/dashboard', // area/database 'postgres': 'area/database', @@ -75,6 +86,10 @@ jobs: 'nats': 'area/database', 'qdrant': 'area/database', 'foundationdb': 'area/database', + 'database': 'area/database', + 'etcd-operator': 'area/database', + 'opensearch': 'area/database', + 'opensearch-operator': 'area/database', // area/extra 'extra': 'area/extra', @@ -84,6 +99,7 @@ jobs: // area/keycloak 'keycloak': 'area/keycloak', + 'keycloak-configure': 'area/keycloak', // area/kubernetes 'kubernetes': 'area/kubernetes', @@ -97,6 +113,7 @@ jobs: 'vmstack': 'area/monitoring', 'grafana': 'area/monitoring', 'workloadmonitor': 'area/monitoring', + 'monitoring-agents': 'area/monitoring', // area/networking 'ingress': 'area/networking', @@ -110,10 +127,20 @@ jobs: 'tcp-balancer': 'area/networking', 'securitygroups': 'area/networking', 'cozy-proxy': 'area/networking', + 'networking': 'area/networking', + 'kubeovn': 'area/networking', + 'multus': 'area/networking', + 'kilo': 'area/networking', + 'hetzner-robotlb': 'area/networking', + 'ouroboros': 'area/networking', // area/cilium 'cilium': 'area/cilium', + // area/openbao + 'openbao': 'area/openbao', + 'openbao-central': 'area/openbao', + // area/platform 'platform': 'area/platform', 'cert-manager': 'area/platform', @@ -127,10 +154,24 @@ jobs: 'cozyctl': 'area/platform', 'cozystack-engine': 'area/platform', 'cozy-lib': 'area/platform', + 'operator': 'area/platform', + 'cozystack-operator': 'area/platform', + 'controller': 'area/platform', + 'cozystack-controller': 'area/platform', + 'cozystack-basics': 'area/platform', + 'flux-shard-operator': 'area/platform', + 'lineage': 'area/platform', + 'migrations': 'area/platform', + 'scheduler': 'area/platform', + 'cozystack-scheduler': 'area/platform', + 'reloader': 'area/platform', + 'bootbox': 'area/platform', // area/release 'backport': 'area/release', 'release': 'area/release', + 'changelog': 'area/release', + 'changelogs': 'area/release', // area/storage 'seaweedfs': 'area/storage', @@ -142,6 +183,10 @@ jobs: 'harbor': 'area/storage', 'backups': 'area/storage', 'csi': 'area/storage', + 'storage': 'area/storage', + 'piraeus-operator': 'area/storage', + 'backupstrategy-controller': 'area/storage', + 'local-storage': 'area/storage', // area/tenant 'tenant': 'area/tenant', @@ -149,6 +194,7 @@ jobs: // area/testing 'tests': 'area/testing', 'e2e': 'area/testing', + 'testing': 'area/testing', // area/virtualization 'kubevirt': 'area/virtualization', @@ -161,6 +207,11 @@ jobs: 'virtual-machine': 'area/virtualization', 'hami': 'area/virtualization', 'gpu-operator': 'area/virtualization', + 'virtualization': 'area/virtualization', + 'vm': 'area/virtualization', + 'kubevirt-operator': 'area/virtualization', + 'kubevirt-cdi': 'area/virtualization', + 'kubevirt-instancetypes': 'area/virtualization', }; const pr = context.payload.pull_request; @@ -169,10 +220,10 @@ jobs: const existing = new Set((pr.labels || []).map(l => l.name)); const toAdd = new Set(); - // 1. Strip "[Backport release-1.x]" prefix if present. - const backportMatch = title.match(/^\[Backport ([^\]]+)\]\s+(.+)$/); - const cleanTitle = backportMatch ? backportMatch[2] : title; - if (backportMatch) { + // 1. Strip every leading "[Backport release-1.x]" prefix: a backport of + // a backport carries two, and a leftover one would be parsed as the scope. + const cleanTitle = title.replace(/^(?:\[Backport [^\]]+\]\s+)+/, ''); + if (cleanTitle !== title) { toAdd.add('area/release'); } @@ -198,7 +249,9 @@ jobs: // 5. Apply kind/* from type. if (type) { - if (typeToKind[type]) { + // Object.hasOwn: a title typed or scoped `constructor` would otherwise + // resolve to an Object.prototype member instead of to nothing. + if (Object.hasOwn(typeToKind, type)) { toAdd.add(typeToKind[type]); } else { core.warning(`type "${type}" has no kind/* mapping — typo or new type? See .github/workflows/pr-labeler.yaml typeToKind`); @@ -211,7 +264,7 @@ jobs: .map(s => s.trim()) .filter(Boolean); for (const s of scopes) { - if (scopeToArea[s]) { + if (Object.hasOwn(scopeToArea, s)) { toAdd.add(scopeToArea[s]); } else { core.warning(`scope "${s}" has no area/* mapping — consider extending scopeToArea in .github/workflows/pr-labeler.yaml if it recurs`); @@ -243,3 +296,82 @@ jobs: labels: newLabels, }); core.info(`Applied labels: ${newLabels.join(', ')}`); + + # Backports are automatic (docs/release/backports.md), so a pull request + # against a release branch from outside the team is closed with a pointer to + # the policy. Only when it is opened: a maintainer keeps a fix that exists + # only on a release line by reopening it. + # + # pull_request_target hands a write token to a fork's pull request, so this + # job never touches the head: actions/checkout takes the event's own ref, + # which is the base repository, the script reads only the event JSON and the + # author's permission on the repository, and no `${{ }}` expression reaches + # the shell. The permission read needs repository metadata read access, which + # a GITHUB_TOKEN always carries and `permissions:` has no key for. + close-manual-backport: + if: >- + github.event.action == 'opened' && + startsWith(github.event.pull_request.base.ref, 'release-') + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: read # check out hack/ from the base repository + pull-requests: write # close the pull request with a comment + steps: + - name: Check out the base repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + sparse-checkout: hack + - name: Close a backport opened by hand from outside the team + env: + GH_TOKEN: ${{ github.token }} + run: hack/close-manual-backport.sh "$GITHUB_EVENT_PATH" + + # A batch pull request carries each original in the shape cmd/backport-batch + # gives it. fold checks one resolution, and only when whoever resolved the + # conflict runs it; this checks every original on the batch on each push. + # + # pull_request_target takes the workflow from main for a pull request into + # any branch, so the check reaches release-* lines, which do not carry it; a + # pull_request job would run the line's own workflows. The tool is built from + # main, since the lines do not carry it either. Nothing from the pull request + # is checked out or run: its head is fetched as data and read with git, and + # no `${{ }}` expression reaches the shell. Only a branch of this repository + # named like a batch is checked. + backport-batch-verify: + name: Backport batch shape + if: >- + startsWith(github.event.pull_request.base.ref, 'release-') && + startsWith(github.event.pull_request.head.ref, 'backport-batch/') && + github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + env: + # The pipe falls back to direct on any proxy error (hack/common-envs.mk). + GOPROXY: "https://proxy.golang.org|direct" + steps: + - name: Check out main + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + ref: main + fetch-depth: 0 + persist-credentials: false + - name: Set up Go + uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5 + with: + go-version-file: go.mod + cache: false + - name: Build backport-batch from main + run: go build -o "$RUNNER_TEMP/backport-batch" ./cmd/backport-batch + - name: Fetch the batch head as data + env: + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: git fetch --no-tags --quiet origin "$HEAD_SHA" + - name: Verify every original on the batch + env: + BASE_REF: ${{ github.event.pull_request.base.ref }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: '"$RUNNER_TEMP/backport-batch" verify --line "$BASE_REF" --head "$HEAD_SHA"' diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml index a3f315500..c2e98276d 100644 --- a/.github/workflows/pre-commit.yml +++ b/.github/workflows/pre-commit.yml @@ -16,6 +16,9 @@ permissions: jobs: pre-commit: runs-on: ubuntu-22.04 + env: + # The pipe falls back to direct on any proxy error (hack/common-envs.mk). + GOPROXY: "https://proxy.golang.org|direct" permissions: contents: read steps: @@ -57,6 +60,9 @@ jobs: curl -sSL https://github.com/cozystack/cozyvalues-gen/releases/download/v1.7.0/cozyvalues-gen-linux-amd64.tar.gz | tar -xzvf- -C /usr/local/bin/ cozyvalues-gen - name: Run pre-commit hooks + # The complete Bats pass is a manual local hook and is therefore outside + # this changed-file lint run. pull-requests.yaml's checks job runs the + # full unit path for code and the Bats contracts for docs-only changes. run: | git fetch origin main || git fetch origin master base_commit=$(git rev-parse --verify origin/main || git rev-parse --verify origin/master || echo "") @@ -83,16 +89,14 @@ jobs: runs-on: ubuntu-22.04 permissions: contents: read - # A backport PR is the one shape whose author cannot fix a finding: the - # backport action cherry-picks merged commits verbatim, so their messages + # A backport batch is the one shape whose author cannot fix a finding: + # cmd/backport-batch cherry-picks merged commits verbatim, so their messages # are history, and roughly a quarter of the commits on main predate the - # rule. Matched on the branch name the action generates, - # backport--to-, rather than on the prefix alone; the label that - # asks for a backport sits on the original PR, not on the generated one, so - # a branch name is the only signal a pull_request event carries. That makes - # the exemption a convention rather than something enforced: anyone can name - # a branch this way. Every other PR, fork included, is checked. - if: ${{ !(startsWith(github.head_ref, 'backport-') && contains(github.head_ref, '-to-')) }} + # rule. Matched on the branch name the batch uses, + # backport-batch/-, and only from a branch of this repository, + # which takes write access to push: a fork can name a branch the same way. + # Every other PR, fork included, is checked. + if: ${{ !(startsWith(github.head_ref, 'backport-batch/') && github.event.pull_request.head.repo.full_name == github.repository) }} steps: - name: Checkout head uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 diff --git a/.github/workflows/promote-rc.yaml b/.github/workflows/promote-rc.yaml index c723d9cf6..d0567018a 100644 --- a/.github/workflows/promote-rc.yaml +++ b/.github/workflows/promote-rc.yaml @@ -251,10 +251,14 @@ jobs: needs: parse runs-on: [oracle-vm-4cpu-16gb-x86-64] timeout-minutes: 45 + env: + # The pipe falls back to direct on any proxy error (hack/common-envs.mk). + GOPROXY: "https://proxy.golang.org|direct" permissions: contents: write # push the release-X.Y.Z staging branch, stage the draft release packages: write # publish the temporary stable-candidate packages artifact pull-requests: write # reserved for parity; the PR is opened in open-pr + id-token: write # keyless signing of the release checksums in hack/upload-assets.sh # open-pr reads these from `promote`, which passes the parse job's validated # outputs straight through. @@ -323,9 +327,12 @@ jobs: // A maintenance branch created before the candidate pipeline landed // would execute its old pull_request workflows after merge. Refuse // before the first registry write unless the actual target base has - // both trusted verification gates and their helpers. Backport this - // change to an existing release-X.Y line before promoting its next - // patch; the rc-derived head does not need to carry the tooling. + // both trusted verification gates and their helpers. An existing + // release-X.Y line gets them before its next patch is promoted, + // through the backport batch with backport/include on the pull + // request that brought them to main, or through a maintainer's pull + // request against the line; the rc-derived head does not need to + // carry the tooling. // // Every file the base-checked-out verifier reaches for belongs in // the list below, its own sourced libraries included: those are @@ -359,7 +366,7 @@ jobs: }); } catch (e) { if (e.status === 404) { - core.setFailed(`Target base '${baseBranch}' lacks '${path}'. Backport the candidate-aware promotion pipeline before dispatch.`); + core.setFailed(`Target base '${baseBranch}' lacks '${path}'. Bring the candidate-aware promotion pipeline to it before dispatch: backport/include on the pull request that added it to main, or a maintainer pull request against the line.`); return; } throw e; @@ -370,7 +377,7 @@ jobs: } const content = Buffer.from(file.data.content, 'base64').toString('utf8'); if (!content.includes(marker)) { - core.setFailed(`Target base '${baseBranch}' has an old '${path}'. Backport the candidate-aware promotion pipeline before dispatch.`); + core.setFailed(`Target base '${baseBranch}' has an old '${path}'. Bring the candidate-aware promotion pipeline to it before dispatch: backport/include on the pull request that added it to main, or a maintainer pull request against the line.`); return; } } @@ -400,15 +407,15 @@ jobs: # Promotion publishes one non-consumer-visible packages candidate. Stable # image/chart tags are still deferred to post-merge finalize. # - # Both tools are version-pinned. This step arms the only registry write + # Both tools are version-pinned. These steps arm the only registry write # the dispatch performs, so what performs it has to be a fixed input: # `latest/download` resolves to whatever mikefarah shipped this morning, # and a yq that changed how it emits or compares a value would rewrite # installer values differently between two promotions of the same rc. The # version tracks packages/core/testing/images/e2e-sandbox/Dockerfile. # - # yq is additionally pinned BY CONTENT, which nothing else in this repo - # does. It earns the exception by being the one downloaded binary with + # yq is additionally pinned BY CONTENT (syft further down is too, for + # another reason). It earns that by being the one downloaded binary with # write authority over what a release contains: it is what stamps the # candidate digest into installer values. skopeo, helm and oras only move # bytes that are already digest-addressed, so a substituted one is caught @@ -418,26 +425,19 @@ jobs: # chosen (against this release's own published checksums list) and makes # any later substitution loud. Bump the version and this together. # - # The Flux installer is deliberately NOT pinned by content. It verifies - # the flux binary it fetches against flux_${FLUX_VERSION}_checksums.txt - # from the pinned release, so the binary is not the exposure — the ~6 KB - # bootstrap script from fluxcd.io is, and it is mutable by design and - # fetched the same way in ten other workflows here. Pinning its bytes in - # this file alone would break on the next regeneration of a script the - # project does not control, while leaving the identical fetch unpinned - # everywhere else. Named rather than half-fixed. - - name: Set up toolchain (flux, yq) + # flux comes from the upstream setup action, pinned by commit and given + # an explicit version. It checks the release tarball against that + # release's checksums file and runs no script fetched at run time, the + # way fluxcd.io/install.sh did as root. + - name: Set up flux + uses: fluxcd/flux2/action@04acaec6161ac4fb1a82ffafa88901c03271d34f # v2.8.6 + with: + version: "2.8.6" + - name: Set up toolchain (yq) env: - FLUX_VERSION: "2.8.6" YQ_VERSION: "4.53.3" YQ_SHA256: "fa52a4e758c63d38299163fbdd1edfb4c4963247918bf9c1c5d31d84789eded4" run: | - if ! flux version --client 2>/dev/null | grep -qx "flux: v${FLUX_VERSION}"; then - install_script="$(mktemp)" - curl -fsSL https://fluxcd.io/install.sh -o "$install_script" - sudo env "FLUX_VERSION=$FLUX_VERSION" bash "$install_script" - rm -f "$install_script" - fi if ! yq --version 2>/dev/null | grep -q "mikefarah.* version v${YQ_VERSION}\$"; then yq_bin="$(mktemp)" curl -fsSL -o "$yq_bin" \ @@ -580,6 +580,42 @@ jobs: run: | make manifests assets-cozypkg openapi-json COZYSTACK_VERSION="${STABLE_VERSION}" + # The rc tree's hack/upload-assets.sh writes a fresh SBOM with syft and + # signs the stable checksums with cosign, keylessly, as this job. An rc + # tagged from a tree without hack/sign-release-assets.sh uploads neither, + # and the two tools go unused. + # + # syft is pinned by content, like yq above. This job holds the app token, + # the GHCR login and an OIDC token for the identity users are told to + # trust, and anchore/sbom-action/download-syft, though pinned by commit, + # runs syft's install.sh fetched from a tag at run time. SYFT_SHA256 is the + # release's own checksums entry, whose keyless signature by anchore/syft's + # release workflow was checked when the version was chosen. Bump both + # together, here and in tags.yaml; hack/ci-tool-installs-contract.bats + # holds them equal. + - name: Set up syft + env: + SYFT_VERSION: "1.54.1" + SYFT_SHA256: "c069905b391cc4c20a5ba65ad5c10be2a7ba074f8ea6ad203e24d14e303dad47" + run: | + syft_dir="${RUNNER_TEMP}/syft" + mkdir -p "$syft_dir" + curl -fsSL -o "$syft_dir/syft.tar.gz" \ + "https://github.com/anchore/syft/releases/download/v${SYFT_VERSION}/syft_${SYFT_VERSION}_linux_amd64.tar.gz" + printf '%s %s\n' "$SYFT_SHA256" "$syft_dir/syft.tar.gz" | sha256sum -c - + tar -xzf "$syft_dir/syft.tar.gz" -C "$syft_dir" syft + rm -f "$syft_dir/syft.tar.gz" + echo "$syft_dir" >> "$GITHUB_PATH" + # cosign is the version docs/release/signatures-and-sbom.md asks users + # for, so the job checks its own signature the way they will. The action + # verifies that binary against cosign's keyless and KMS bundles with its + # digest-pinned bootstrap cosign. Bump with tags.yaml; the contract test + # holds them equal. + - name: Set up cosign + uses: sigstore/cosign-installer@6f9f17788090df1f26f669e9d70d6ae9567deba6 # v4.1.2 + with: + cosign-release: v3.1.3 + - name: Create draft stable release and upload assets env: GH_TOKEN: ${{ steps.app-token.outputs.token }} @@ -1012,9 +1048,10 @@ jobs: PR_STATE="$(gh pr view "${STABLE_BRANCH}" --json state --jq .state 2>/dev/null || echo "")" if [ "${PR_STATE}" = "OPEN" ]; then # Refresh only while the body is still the one this workflow wrote. - # docs/release.md tells reviewers to paste upstream breaking-change - # notes into this body before merge; a re-dispatch that overwrites it - # would destroy that with no trace and no way to recover it. + # docs/release/pre-release-checklist.md tells reviewers to paste + # upstream breaking-change notes into this body before merge; a + # re-dispatch that overwrites it would destroy that with no trace + # and no way to recover it. CURRENT="$(gh pr view "${STABLE_BRANCH}" --json body --jq .body 2>/dev/null || echo "")" if [ "${CURRENT}" = "${BODY}" ]; then echo "PR already open for ${STABLE_BRANCH} with an identical body; nothing to do." diff --git a/.github/workflows/pull-requests-release.yaml b/.github/workflows/pull-requests-release.yaml index 5182fb6cf..9874544c1 100644 --- a/.github/workflows/pull-requests-release.yaml +++ b/.github/workflows/pull-requests-release.yaml @@ -115,22 +115,20 @@ jobs: # this morning. The version tracks # packages/core/testing/images/e2e-sandbox/Dockerfile. yq is additionally # pinned by content — it stamps the chart's platformVersion, and this step - # is the last one before write-once names exist. The Flux installer is not, - # because it checksums the binary it fetches and the mutable part is its - # own bootstrap script. promote-rc.yaml's copy carries the full reasoning. - - name: Set up promotion toolchain (flux, skopeo, yq, helm) + # is the last one before write-once names exist. flux comes from the + # commit-pinned upstream setup action, which checksums the release + # tarball. promote-rc.yaml's copy carries the full reasoning. + - name: Set up flux + if: ${{ !contains(steps.get_tag.outputs.tag, '-') }} + uses: fluxcd/flux2/action@04acaec6161ac4fb1a82ffafa88901c03271d34f # v2.8.6 + with: + version: "2.8.6" + - name: Set up promotion toolchain (skopeo, yq, helm) if: ${{ !contains(steps.get_tag.outputs.tag, '-') }} env: - FLUX_VERSION: "2.8.6" YQ_VERSION: "4.53.3" YQ_SHA256: "fa52a4e758c63d38299163fbdd1edfb4c4963247918bf9c1c5d31d84789eded4" run: | - if ! flux version --client 2>/dev/null | grep -qx "flux: v${FLUX_VERSION}"; then - install_script="$(mktemp)" - curl -fsSL https://fluxcd.io/install.sh -o "$install_script" - sudo env "FLUX_VERSION=$FLUX_VERSION" bash "$install_script" - rm -f "$install_script" - fi if ! yq --version 2>/dev/null | grep -q "mikefarah.* version v${YQ_VERSION}\$"; then yq_bin="$(mktemp)" curl -fsSL -o "$yq_bin" \ @@ -421,24 +419,51 @@ jobs: // Reading the file here is both race-free and branch-agnostic; // update-releasenotes.yaml remains for later maintainer edits and // manual re-syncs. + // + // docs/releasenotes/${tag}.md, a short hand-written summary for a + // release whose changelog is too long to read on the release page, + // is the body when it has content; the changelog otherwise. + // + // The tags above already exist, so a body GitHub refuses would + // strand a half-promoted release. GitHub's web UI cut the + // v1.7.0-rc.2 changelog at about 125000 characters. MAX_BODY_BYTES + // counts bytes, which are never fewer than characters, and sits 25 + // percent under that figure, so neither the difference nor an + // imprecise limit matters, and GitHub's answer to an oversized + // body is never relied on. update-releasenotes.yaml uses the same + // constant. const fs = require('fs'); + const MAX_BODY_BYTES = 100000; const changelogPath = `docs/changelogs/${tag}.md`; - let body; - if (fs.existsSync(changelogPath)) { - const raw = fs.readFileSync(changelogPath, 'utf8'); + let sourcePath; + let raw; + for (const candidate of [`docs/releasenotes/${tag}.md`, changelogPath]) { + if (!fs.existsSync(candidate)) continue; + raw = fs.readFileSync(candidate, 'utf8'); // Last line of defence before the body becomes public and // immutable-by-convention. promote-rc.yaml validates the changelog // structurally, but it can also arrive by hand-commit, and an // empty or whitespace-only file here would blank the release notes // more thoroughly than publishing the draft's body would. if (raw.trim().length === 0) { - console.log(`::warning::${changelogPath} is empty or whitespace-only — refusing to use it as the release body for ${tag}. Publishing with the draft's existing body instead.`); + console.log(`::warning::${candidate} is empty or whitespace-only — not using it as the release body for ${tag}.`); + continue; + } + sourcePath = candidate; + break; + } + let body; + if (!sourcePath) { + console.log(`::warning::No usable docs/releasenotes/${tag}.md or ${changelogPath} in the merge commit — publishing ${tag} with the draft's existing body. Add the changelog and re-run 'Update Release Notes' to backfill it.`); + } else { + const bytes = Buffer.byteLength(raw, 'utf8'); + if (bytes > MAX_BODY_BYTES) { + body = `The release notes for ${tag} are too long for a GitHub release description; the full changelog is [${changelogPath}](https://github.com/${context.repo.owner}/${context.repo.repo}/blob/${tag}/${changelogPath}).`; + console.log(`::warning::${sourcePath} is ${bytes} bytes, over MAX_BODY_BYTES (${MAX_BODY_BYTES}) — publishing ${tag} with a link to ${changelogPath} instead.`); } else { body = raw; - console.log(`📝 Release body from ${changelogPath} (${body.length} bytes)`); + console.log(`📝 Release body from ${sourcePath} (${bytes} bytes)`); } - } else { - console.log(`::warning::${changelogPath} not found in the merge commit — publishing ${tag} with the draft's existing body. Add the changelog and re-run 'Update Release Notes' to backfill it.`); } // Publish the release diff --git a/.github/workflows/pull-requests.yaml b/.github/workflows/pull-requests.yaml index caa5cb6d8..92379083c 100644 --- a/.github/workflows/pull-requests.yaml +++ b/.github/workflows/pull-requests.yaml @@ -75,7 +75,8 @@ jobs: statuses: write outputs: code: ${{ steps.p.outputs.code }} - trigger_map: ${{ steps.p.outputs.trigger_map }} + docs: ${{ steps.p.outputs.docs }} + backport_batch: ${{ steps.p.outputs.backport_batch }} matrix: ${{ steps.p.outputs.matrix }} any: ${{ steps.p.outputs.any }} touched: ${{ steps.p.outputs.touched }} @@ -131,6 +132,16 @@ jobs: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: fetch-depth: 0 + # e2e-fork.yaml pushes a fork's images only under names the base tree + # already exports, so an image the PR adds is refused there after the + # whole build. Refuse it here instead, before anything builds. The push + # check stays the boundary; a fork can edit this step away. + - name: Refuse images the base branch does not build (fork PR) + if: ${{ github.event.pull_request.head.repo.fork }} + run: | + bt="$(mktemp -d)/basetree" + git worktree add --quiet --detach "$bt" HEAD^1 + hack/fork-new-images.sh "$bt" . - name: Compute changed files and build matrix id: p env: @@ -158,28 +169,27 @@ jobs: # alone here rather than widened by a side effect. git diff --name-only --no-renames "origin/${BASE_REF}...HEAD" > /tmp/changed_norenames.txt echo "Changed files:"; sed 's/^/ /' /tmp/changed_norenames.txt - if grep -qvE '^docs/' /tmp/changed_norenames.txt; then + # `code` is false when every path is under docs/ or in a CI-only Go + # tool that no image builds (cmd/backport-batch, cmd/api-gate): there + # is nothing to build and nothing for e2e to install. e2e-fork.yaml + # answers the same question from the PR file list with the same + # prefixes, and hack/gate-concurrency-contract.bats holds the two lists + # equal. + if grep -qvE '^(docs/|cmd/backport-batch/|cmd/api-gate/)' /tmp/changed_norenames.txt; then echo "code=true" >> "$GITHUB_OUTPUT" else echo "code=false" >> "$GITHUB_OUTPUT" fi - # docs/agents/contributing.md carries the downstream trigger map, which - # hack/downstream-trigger-map.bats asserts against: every path the map - # cites still exists, and its repository list still matches the PR - # template. Editing the map alone is a docs-only PR, which would skip the - # unit tests and exempt the map from its own guard. This flag lets the - # unit-test job opt back in, and only that job: it deliberately does not - # feed `code`, so a docs PR still builds nothing. - # - # Detect the map by its old path too, which is why this reads the - # rename-blind list above: a PR that moves the map would otherwise skip - # the very test that pins the literal below to it, and break for - # whoever pushes next. - if grep -qxF 'docs/agents/contributing.md' /tmp/changed_norenames.txt; then - echo "trigger_map=true" >> "$GITHUB_OUTPUT" + # The Bats contracts read docs, so a docs change runs them even when + # `code` is false; a change confined to the CI-only tools does not. + if grep -qE '^docs/' /tmp/changed_norenames.txt; then + echo "docs=true" >> "$GITHUB_OUTPUT" else - echo "trigger_map=false" >> "$GITHUB_OUTPUT" + echo "docs=false" >> "$GITHUB_OUTPUT" fi + backport_batch="$(hack/backport-batch-tests-needed.sh /tmp/changed_norenames.txt)" + echo "backport-batch tests needed: $backport_batch" + echo "backport_batch=$backport_batch" >> "$GITHUB_OUTPUT" matrix="$(hack/build-matrix.sh /tmp/changed.txt)" echo "Build matrix: $matrix" echo "matrix=$matrix" >> "$GITHUB_OUTPUT" @@ -249,22 +259,18 @@ jobs: # resolves to whatever mikefarah shipped this morning, and a yq that changed # how it emits or compares a value turns a release gate into a moving one. # The version tracks packages/core/testing/images/e2e-sandbox/Dockerfile. - # yq is additionally pinned by content; the Flux installer is not, because - # it checksums the binary it fetches and the mutable part is its own - # bootstrap script. promote-rc.yaml's copy of this step carries the full - # reasoning for both. - - name: Set up promotion toolchain (flux, yq) + # yq is additionally pinned by content; flux comes from the commit-pinned + # upstream setup action, which checksums the release tarball. + # promote-rc.yaml's copy of this step carries the full reasoning for both. + - name: Set up flux + uses: fluxcd/flux2/action@04acaec6161ac4fb1a82ffafa88901c03271d34f # v2.8.6 + with: + version: "2.8.6" + - name: Set up promotion toolchain (yq) env: - FLUX_VERSION: "2.8.6" YQ_VERSION: "4.53.3" YQ_SHA256: "fa52a4e758c63d38299163fbdd1edfb4c4963247918bf9c1c5d31d84789eded4" run: | - if ! flux version --client 2>/dev/null | grep -qx "flux: v${FLUX_VERSION}"; then - install_script="$(mktemp)" - curl -fsSL https://fluxcd.io/install.sh -o "$install_script" - sudo env "FLUX_VERSION=$FLUX_VERSION" bash "$install_script" - rm -f "$install_script" - fi if ! yq --version 2>/dev/null | grep -q "mikefarah.* version v${YQ_VERSION}\$"; then yq_bin="$(mktemp)" curl -fsSL -o "$yq_bin" \ @@ -298,32 +304,119 @@ jobs: name: Unit & controller tests runs-on: oracle-vm-4cpu-16gb-x86-64 timeout-minutes: 30 + env: + # The pipe falls back to direct on any proxy error (hack/common-envs.mk). + GOPROXY: "https://proxy.golang.org|direct" permissions: contents: read needs: ["plan"] - # trigger_map opts a docs-only PR back in when it edits the downstream trigger - # map, so hack/downstream-trigger-map.bats still guards it. No other job reads - # that flag: a docs PR runs the unit tests and nothing heavier. + # Unit contracts read both code and documentation. Run this job for every + # non-release PR: code changes take the complete unit path, docs changes run + # the Bats lane that owns those cross-tree contracts, and the backport-batch + # tests run whenever one of their inputs changed and at no other time. A + # change confined to the CI-only tools runs no other lane. Builds and E2E + # remain gated on `code` below. if: | - (needs.plan.outputs.code == 'true' || needs.plan.outputs.trigger_map == 'true') - && !contains(github.event.pull_request.labels.*.name, 'release') + !contains(github.event.pull_request.labels.*.name, 'release') steps: - name: Checkout code uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: fetch-depth: 0 - # Ephemeral runners don't carry the helm-unittest plugin the persistent - # self-hosted runner accreted. Install if absent (idempotent). - - name: Set up test toolchain + # The module cache is restored from the key build-main.yaml writes on + # main, which every PR run can read, so a PR's first run starts warm. The + # download fetches whatever the cache lacks, the whole set on a miss. The + # Go steps are for code changes and the backport-batch tests only: a + # docs-only run is the Bats lane alone. + - name: Locate Go module cache + if: needs.plan.outputs.code == 'true' || needs.plan.outputs.backport_batch == 'true' + id: gomodcache + run: echo "dir=$(go env GOMODCACHE)" >> "$GITHUB_OUTPUT" + - name: Cache Go modules + if: needs.plan.outputs.code == 'true' || needs.plan.outputs.backport_batch == 'true' + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ steps.gomodcache.outputs.dir }} + key: go-mod-${{ runner.os }}-${{ hashFiles('**/go.sum') }} + restore-keys: go-mod-${{ runner.os }}- + - name: Download Go modules + if: needs.plan.outputs.code == 'true' || needs.plan.outputs.backport_batch == 'true' run: | - helm plugin list 2>/dev/null | grep -q unittest \ - || helm plugin install https://github.com/helm-unittest/helm-unittest - # One make process owns all four runner CPUs. Each BATS file is a separate - # prerequisite, so the long tail no longer runs as one nine-minute shell - # loop; Helm and Go targets share the same bounded pool. Output stays - # grouped by target instead of four test logs interleaving. + for mod in $(git ls-files go.mod '*/go.mod' | xargs -n1 dirname); do + (cd "$mod" && "$GITHUB_WORKSPACE/hack/go-mod-download.sh") + done + # Ephemeral runners don't carry the helm-unittest plugin the persistent + # self-hosted runner accreted. The plugin embeds its own Helm, so its + # version is pinned: a plugin release must not change test results. Bats is + # installed whenever a Bats lane runs, docs-only ones included. + - name: Set up test toolchain + if: needs.plan.outputs.code == 'true' || needs.plan.outputs.docs == 'true' + env: + CODE_CHANGED: ${{ needs.plan.outputs.code }} + HELM_UNITTEST_VERSION: "1.1.2" + BATS_VERSION: "1.14.0" + BATS_COMMIT: eb7f42f8d608ac693d7a4b67474f6714ea68cfc5 + run: | + set -euo pipefail + if [ "$CODE_CHANGED" = true ]; then + installed="$(helm plugin list 2>/dev/null | awk '$1 == "unittest" { print $2 }' || true)" + if [ "$installed" != "$HELM_UNITTEST_VERSION" ]; then + [ -z "$installed" ] || helm plugin uninstall unittest + helm plugin install https://github.com/helm-unittest/helm-unittest --version "v${HELM_UNITTEST_VERSION}" + fi + fi + # Source archive bytes can change; verify the tag's commit before install. + if ! bats --version 2>/dev/null | grep -qx "Bats $BATS_VERSION"; then + bats_parent=$(mktemp -d "$RUNNER_TEMP/bats-core.XXXXXX") + bats_source="$bats_parent/source" + git clone --quiet --depth=1 --branch "v$BATS_VERSION" \ + https://github.com/bats-core/bats-core.git "$bats_source" + test "$(git -C "$bats_source" rev-parse HEAD)" = "$BATS_COMMIT" + sudo "$bats_source/install.sh" /usr/local + fi + bats --version | grep -qx "Bats $BATS_VERSION" + # setup-envtest and the kube-apiserver and etcd it fetches, so a pull + # request downloads them only when the versions pinned in the Makefile + # change, and an outage at their sources cannot fail unrelated changes. + # The envtest target runs the controller suites a fake client cannot + # stand in for. + - name: Cache envtest binaries + if: needs.plan.outputs.code == 'true' + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: _out/envtest + key: envtest-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('Makefile') }} + # -k is required, not cosmetic: unit-tests and test-controllers are two + # independent goals on the same command line, and without -k make stops + # handing out new work the moment any unit-tests prerequisite fails — + # test-controllers then never starts and reports nothing, so a red BATS + # file hides the entire Go controller suite. -k lets already-schedulable + # goals keep running; the job still fails overall on any red target. - name: Run unit and controller tests - run: make unit-tests test-controllers -j4 --output-sync=target + if: needs.plan.outputs.code == 'true' + run: make unit-tests test-controllers test-controllers-envtest -j4 -k --output-sync=target + - name: Run Bats unit tests for docs-only changes + if: needs.plan.outputs.code == 'false' && needs.plan.outputs.docs == 'true' + run: make bats-unit-tests + # Not part of `make unit-tests`: hack/backport-batch-tests-needed.sh + # decides from cmd/backport-batch/test-inputs.txt, whatever `code` is. + # `!cancelled()` for the reason the unit lane runs with -k: a red step + # above must not hide this suite's own result. + - name: Run backport-batch tests + if: ${{ !cancelled() && needs.plan.outputs.backport_batch == 'true' }} + run: make test-backport-batch + - name: Check new Helm document indices + if: ${{ !cancelled() }} + env: + BASE_REF: ${{ github.event.pull_request.base.ref }} + run: python3 hack/check-helm-document-indices.py "$(git merge-base HEAD "origin/$BASE_REF")" + - name: Upload unit test report + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: bats-unit-report + path: _out/test-reports/ + if-no-files-found: ignore # One image (package) per job, fanned out across the ephemeral pool. Each job # gets its own buildx (docker-container driver) so the shared-buildkit @@ -341,7 +434,6 @@ jobs: timeout-minutes: 30 permissions: contents: read - packages: write strategy: fail-fast: false matrix: @@ -353,15 +445,11 @@ jobs: fetch-depth: 0 fetch-tags: true # installer is built in finalize, but some package image targets shell out - # to flux; install it if absent (idempotent, cheap). - - name: Set up build toolchain - run: | - if ! command -v flux >/dev/null; then - install_script="$(mktemp)" - curl -fsSL https://fluxcd.io/install.sh -o "$install_script" - sudo bash "$install_script" - rm -f "$install_script" - fi + # to flux. + - name: Set up flux + uses: fluxcd/flux2/action@04acaec6161ac4fb1a82ffafa88901c03271d34f # v2.8.6 + with: + version: "2.8.6" - name: Set up Docker config run: | if [ -d ~/.docker ]; then @@ -405,6 +493,10 @@ jobs: # pulls go through the docker.io mirror (BUILDX_ARGS adds # --builder=$(BUILDER)). BUILDER: ${{ steps.buildx.outputs.name }} + # common-envs.mk defaults to amd64+arm64. Nothing here sets up QEMU, + # and on this x86-64 runner the arm64 half would be emulated anyway; + # CI builds amd64 until arm64 has a native leg of its own. + PLATFORM: linux/amd64 # Unique per (PR, commit) so concurrent PR builds never push the same # tag. PR images are consumed by digest; :latest belongs to releases. IMAGE_TAG: pr-${{ github.event.pull_request.number }}-${{ github.event.pull_request.head.sha }} @@ -479,7 +571,6 @@ jobs: timeout-minutes: 40 permissions: contents: read - packages: write steps: - name: Checkout code uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 @@ -518,6 +609,10 @@ jobs: env: DOCKER_CONFIG: ${{ runner.temp }}/.docker BUILDER: ${{ steps.buildx.outputs.name }} + # amd64 only, as in the build job. The arm64 installer needs no QEMU, + # but nothing a PR runs boots it. matchbox still gets the arm64 kernel + # and initramfs. + PLATFORM: linux/amd64 IMAGE_TAG: pr-${{ github.event.pull_request.number }}-${{ github.event.pull_request.head.sha }} PUBLISH_VERSIONED: '0' PUBLISH_FLOATING: '0' @@ -566,21 +661,16 @@ jobs: timeout-minutes: 30 permissions: contents: read - packages: write steps: - name: Checkout code uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: fetch-depth: 0 fetch-tags: true - - name: Set up build toolchain - run: | - if ! command -v flux >/dev/null; then - install_script="$(mktemp)" - curl -fsSL https://fluxcd.io/install.sh -o "$install_script" - sudo bash "$install_script" - rm -f "$install_script" - fi + - name: Set up flux + uses: fluxcd/flux2/action@04acaec6161ac4fb1a82ffafa88901c03271d34f # v2.8.6 + with: + version: "2.8.6" - name: Download patch fragments uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 with: @@ -642,9 +732,13 @@ jobs: # A base that is neither main nor a line (a stacked PR's feature branch) has # no artifact, and a `/` in it is not even a valid OCI tag. It reads the # artifact of whichever of main and the lines it has the fewest commits on - # top of. A tie goes to main, so a stack on a line keeps that line's - # generation only once the line has a commit of its own: a line fresh off - # main is topologically the same as main at that commit. + # top of. A tie goes to main. A line with no commit of its own yet is, in + # the graph, main at the cut commit, so a stack on it ties and reads the + # artifact built from main's tip. That artifact carries newer images than + # the line once main moves past the cut. The stack keeps reading it until + # it contains a commit of the line's own. Breaking the tie towards the + # line instead would misroute the far more common branch forked from main + # before the cut, which ties the same way. # # A missing artifact stays a no-op (packages keep their committed refs), which # also covers a line whose first build-release run has not landed yet. @@ -749,6 +843,8 @@ jobs: env: DOCKER_CONFIG: ${{ runner.temp }}/.docker BUILDER: ${{ steps.buildx.outputs.name }} + # amd64 only, as in the build job. + PLATFORM: linux/amd64 IMAGE_TAG: pr-${{ github.event.pull_request.number }}-${{ github.event.pull_request.head.sha }} PUBLISH_VERSIONED: '0' PUBLISH_FLOATING: '0' @@ -832,7 +928,7 @@ jobs: # nocloud disk asset and export its id; the container lane boots no disk, # so nothing in this workflow reads that id any more and resolving it only # added a way to fail a release PR over an asset it does not use. The - # asset is still resolved where it is still consumed, in e2e-tag.yaml. + # asset's presence is still checked in e2e-tag.yaml and promote-rc.yaml. - name: Verify draft release exists (release PR) if: contains(github.event.pull_request.labels.*.name, 'release') uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7 @@ -852,15 +948,11 @@ jobs: } - # In-tree e2e for SAME-REPO PRs, on Talos nodes running as CONTAINERS. The - # QEMU substrate this lane used to boot is off the per-PR path only: it is - # still wired into nightly.yaml and e2e-tag.yaml, both of which run `make - # prepare-env` -> `make -C packages/core/testing prepare-cluster`. That target - # and hack/e2e-prepare-cluster.bats are therefore live code, not leftovers, - # and deleting them takes nightly and every release-candidate run with them. - # They carry the coverage containers cannot: DRBD, and with it the - # `replicated` StorageClass, its Immediate binding mode and the tenant - # StorageClass propagation that only applies to remotely-accessible classes. + # In-tree e2e for SAME-REPO PRs, on Talos nodes running as CONTAINERS, like + # every other e2e lane. What containers cannot carry has no lane at all: + # DRBD, and with it the `replicated` StorageClass, its Immediate binding mode + # and the tenant StorageClass propagation that only applies to + # remotely-accessible classes. # # Deliberately NOT named "E2E Tests": the # required "E2E Tests" context is a commit status posted by the `e2e-report` @@ -892,9 +984,10 @@ jobs: # scheduler and not what a pod reads from /proc, so a workload that sizes # itself from /proc/cpuinfo or /proc/meminfo is configured for the whole host. runs-on: oracle-vm-32cpu-128gb-x86-64 - # Sized above what the tenant-Kubernetes pair can spend on a failing run, and - # held to one figure across every lane that runs the suite. - timeout-minutes: 215 + # Covers a green full suite. It does not cover a tenant-Kubernetes suite + # running into its node-join deadline, so a red there can end as a + # cancelled job. Held to one figure across every lane that runs the suite. + timeout-minutes: 265 permissions: contents: read packages: read @@ -1012,38 +1105,6 @@ jobs: done echo "Prepare environment completed after $((attempt + 1)) attempts" - # ▸ Install Cozystack - - name: Install Cozystack into sandbox - env: - # This lane has no ARP VIP: .11 is a plain control-plane node standing - # in for the QEMU lane's 192.168.123.10. - COZY_APISERVER_ENDPOINT: https://192.168.123.11:6443 - # Talos containers share the runner kernel and cannot load DRBD, so the - # harness suppresses DRBD-dependent chart content, registers the host's - # pre-created zpools and keeps LINSTOR's local ZFS path. - COZY_LINSTOR_DRBD_ENABLED: "false" - # Root monitoring is the one install-time workload whose chart selects - # `replicated` explicitly instead of inheriting the default class. - COZY_E2E_STORAGE_CLASS: local - run: | - if ! make -C packages/core/testing SANDBOX_NAME=$SANDBOX_NAME install-cozystack; then - echo "❌ Install failed (no retry — see diagnostics below)" - echo "::group::Diagnostics: HelmRelease status" - docker exec "$SANDBOX_NAME" sh -c 'kubectl get hr -A -o wide 2>&1 | tail -100' || true - echo "::endgroup::" - echo "::group::Diagnostics: not-Ready HelmReleases (describe)" - docker exec "$SANDBOX_NAME" sh -c 'kubectl get hr -A --no-headers 2>/dev/null | awk "\$4 != \"True\" {print \$1\" \"\$2}"' \ - | while read -r ns name; do - echo "--- $ns/$name ---" - docker exec "$SANDBOX_NAME" sh -c "kubectl describe hr '$name' -n '$ns' 2>&1 | tail -50" || true - done - echo "::endgroup::" - echo "::group::Diagnostics: recent events" - docker exec "$SANDBOX_NAME" sh -c 'kubectl get events -A --sort-by=.lastTimestamp 2>&1 | tail -50' || true - echo "::endgroup::" - exit 1 - fi - # Test Impact Analysis (TIA): walk the PackageSource graph for the PR # diff and select only the Chainsaw suites affected. Runs by default; opt # out via the `full-e2e` label to run the full suite. @@ -1074,6 +1135,51 @@ jobs: else echo "skip=false" >> $GITHUB_OUTPUT fi + # The complement of what the selected suites need, for a reduced + # install. An empty selection installs everything as before. + disabled="" + if [ -n "${apps}" ]; then + disabled="$(./hack/select-install.sh --disabled "${apps}")" + fi + echo "Disabled packages: ${disabled:-}" + echo "disabled=${disabled}" >> $GITHUB_OUTPUT + + # ▸ Install Cozystack + - name: Install Cozystack into sandbox + env: + # This lane has no ARP VIP: .11 is a plain control-plane node standing + # in for the QEMU lane's 192.168.123.10. + COZY_APISERVER_ENDPOINT: https://192.168.123.11:6443 + # Talos containers share the runner kernel and cannot load DRBD, so the + # harness suppresses DRBD-dependent chart content, registers the host's + # pre-created zpools and keeps LINSTOR's local ZFS path. + COZY_LINSTOR_DRBD_ENABLED: "false" + # Root monitoring is the one root-tenant workload whose chart selects + # `replicated` explicitly instead of inheriting the default class. The + # install leaves it off but still seeds its local-storage override, so + # a run that turns it on does not create a replicated PVC. + COZY_E2E_STORAGE_CLASS: local + # Empty on the full-e2e label and on an empty selection, which keeps + # the full install. + COZY_DISABLED_PACKAGES: ${{ steps.select.outputs.disabled }} + run: | + if ! make -C packages/core/testing SANDBOX_NAME=$SANDBOX_NAME install-cozystack; then + echo "❌ Install failed (no retry — see diagnostics below)" + echo "::group::Diagnostics: HelmRelease status" + docker exec "$SANDBOX_NAME" sh -c 'kubectl get hr -A -o wide 2>&1 | tail -100' || true + echo "::endgroup::" + echo "::group::Diagnostics: not-Ready HelmReleases (describe)" + docker exec "$SANDBOX_NAME" sh -c 'kubectl get hr -A --no-headers 2>/dev/null | awk "\$4 != \"True\" {print \$1\" \"\$2}"' \ + | while read -r ns name; do + echo "--- $ns/$name ---" + docker exec "$SANDBOX_NAME" sh -c "kubectl describe hr '$name' -n '$ns' 2>&1 | tail -50" || true + done + echo "::endgroup::" + echo "::group::Diagnostics: recent events" + docker exec "$SANDBOX_NAME" sh -c 'kubectl get events -A --sort-by=.lastTimestamp 2>&1 | tail -50' || true + echo "::endgroup::" + exit 1 + fi - name: Run OpenAPI tests run: | @@ -1113,7 +1219,7 @@ jobs: echo "Running selected chainsaw suites: $suites" fi if ! make -C packages/core/testing SANDBOX_NAME=$SANDBOX_NAME test-chainsaw CHAINSAW_SUITES="$suites"; then - echo "❌ Chainsaw E2E failed (see the assertion diffs above and diagnostics below)" + echo "❌ Chainsaw E2E failed (see the assertion diffs or LEAKED-PODS lines above and diagnostics below)" echo "::group::Diagnostics: HelmRelease status" docker exec "$SANDBOX_NAME" sh -c 'kubectl get hr -A -o wide 2>&1 | tail -50' || true echo "::endgroup::" @@ -1152,7 +1258,7 @@ jobs: # ▸ Collect debug information (always runs) # - # A ceiling of its own, not the job's 215 minutes. `Upload + # A ceiling of its own, not the job's 265 minutes. `Upload # cozyreport.tgz` is the next step and the collector writes its tarball # at the very end of its run, so a read that never returns spends what # is left of the job budget, the job is cancelled, and the upload never @@ -1163,7 +1269,7 @@ jobs: # 30 minutes is measured against the step: it takes 3-42s across sampled # runs, on failed e2e jobs as well as green ones. It RESERVES nothing -- # `timeout-minutes` caps a step, it does not carve budget out of the job, - # so a suite that has already burned 210 of the 215 leaves this step five + # so a suite that has already burned 260 of the 265 leaves this step five # minutes and the upload is cancelled with everything else. What the cap # buys is that a hung read cannot be the reason. # `continue-on-error` because the ceiling must not change what the job @@ -1276,28 +1382,6 @@ jobs: Resume from inside: `breakpoint resume`. Otherwise the breakpoint exits 10 minutes after the last SSH session disconnects. - # ▸ Tear down environment (always runs) - # - # Both halves, and in this order: the compose project owns the nodes and - # the zpools outlive it. A leftover pool makes the next run on a reused - # host adopt storage that already carries a dead cluster's volumes. - - name: Tear down sandbox - if: always() - run: | - # Loud, but never the job's verdict. A failed teardown means a dirty - # host, and this runner is discarded after the job, so there is no next - # run to protect -- while failing the job here posts the required - # "E2E Tests" status as a failure that no reader can tell apart from a - # real one. The annotation is what a reused host (a developer machine) - # needs; `delete-cluster-container` returning non-zero is not evidence - # about the product. - cleanup_rc=0 - make -C packages/core/testing SANDBOX_NAME=$SANDBOX_NAME delete-cluster-container || cleanup_rc=$? - make -C packages/core/testing SANDBOX_NAME=$SANDBOX_NAME delete || true - if [ "$cleanup_rc" -ne 0 ]; then - echo "::error title=sandbox teardown::teardown exited $cleanup_rc; the host may hold a stale compose project or zpool" - fi - # Report the required "E2E Tests" gate as a commit status rather than relying # on a job named "E2E Tests". A required *job* that is skipped counts # as PASSED by branch protection — desired for docs-only PRs, but the exact @@ -1377,7 +1461,7 @@ jobs: description = `release packages candidate did not verify (result: ${CANDIDATE_RESULT})`; } else if (CODE !== 'true') { state = 'success'; - description = 'docs-only PR — e2e not required'; + description = 'docs or CI-only tools — e2e not required'; } else if (IS_RELEASE === 'true' && IS_FULL_E2E !== 'true') { // Release promotion PRs deliberately do not repeat e2e: the rc was // already verified against the immutable candidate whose digests diff --git a/.github/workflows/retention.yaml b/.github/workflows/retention.yaml index e5b56a492..23aba46bb 100644 --- a/.github/workflows/retention.yaml +++ b/.github/workflows/retention.yaml @@ -1,11 +1,11 @@ name: Artifact Retention # Prune old nightly artifacts from GHCR: keep the newest KEEP dated versions of -# each cozystack package, delete older ones. Nightlies are GHCR OCI tags -# (0.0.0-nightly... on every component image plus -# cozystack-packages, cozy-installer and cozystack-nocloud) — not git tags or -# releases — so this prunes container-package versions via the GitHub Packages -# API. +# each cozystack package the current nightly publishes, delete older ones. +# Nightlies are GHCR OCI tags (0.0.0-nightly... on every +# component image plus cozystack-packages, cozy-installer and cozystack-nocloud) +# — not git tags or releases — so this prunes container-package versions via +# the GitHub Packages API. # # Strictly scoped: only versions whose tags are ALL of the form # 0.0.0-nightly... are eligible. A version that also @@ -18,15 +18,19 @@ name: Artifact Retention # tag, so a retry never moves one and leaves an untagged manifest behind. A # successful promotion adds a stable tag to the same manifest, which makes it # ineligible below. A candidate stays protected while an open bot-authored -# release PR pins its digest; otherwise it becomes eligible after -# PROMOTION_TTL_DAYS only when ALL its tags are still temporary. +# release PR, or the tip of main or a release-X.Y branch, pins its digest; +# otherwise it becomes eligible after PROMOTION_TTL_DAYS only when ALL its tags +# are still temporary. # # Dry-run by default; flip the input or the RETENTION_APPLY repo variable to # actually delete. Deletion is irreversible. # -# NOTE (admin): deleting org container-package versions requires the -# cozystack-ci app installation to carry the `packages: write` permission. If -# the delete step 403s, grant it there — this workflow cannot. +# NOTE (admin): the cozystack-ci app installation token cannot delete here: it +# lists package versions, yet DELETE of a listed version answered "404 Package +# not found". This repository's GITHUB_TOKEN, with the job's packages: write +# and no change to package settings, deleted the same version from a package +# linked to this repository, so deletes use it. A package linked to another +# repository is skipped with a warning. on: schedule: @@ -60,6 +64,16 @@ jobs: packages: write pull-requests: read steps: + - name: Checkout + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + + - name: Set up flux + uses: fluxcd/flux2/action@04acaec6161ac4fb1a82ffafa88901c03271d34f # v2.8.6 + with: + version: "2.8.6" + - name: Generate GitHub App token id: app-token uses: actions/create-github-app-token@d72941d797fd3113feb6b93fd0dec494b13a2547 # v1 @@ -73,6 +87,8 @@ jobs: GH_TOKEN: ${{ steps.app-token.outputs.token }} # workflow_dispatch input wins; otherwise the repo variable; else dry-run. APPLY: ${{ github.event.inputs.apply || vars.RETENTION_APPLY || 'false' }} + # See the admin NOTE above for why deletes do not use the app token. + DELETE_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | set -euo pipefail if [ "$APPLY" = "true" ]; then echo "MODE: APPLY (deleting)"; else echo "MODE: dry-run"; fi @@ -187,42 +203,57 @@ jobs: protected_count="$(printf '%s\n' "$protected_promotion_digests" | awk '{print NF}')" echo "Protecting ${protected_count} promotion candidate digest(s) named by an open release PR or a base-branch tip." - # All container packages under the org that live in the cozystack/ - # registry namespace (ghcr.io/cozystack/cozystack/). + # The cozystack/* packages to sweep. GitHub refuses to list org + # container packages to an app installation token (400 Invalid + # argument), so the names come from the published nightly tree; see + # hack/retention-packages.sh for why that tree and what it covers. # - # Listed and filtered as two statements, because one `|| true` cannot - # mean two things. `grep` legitimately exits 1 when the org has no - # cozystack/* package, and a failed listing produces the same empty - # output, so a trailing `|| true` covering both turned an API failure - # into "no packages found" — which exits 0 BELOW the nightly sweep and - # ABOVE the deferred guard, so an unresolvable protection set ended in - # a green run that swept nothing. That bypasses the guard rather than - # varying it. - all_pkgs="$(gh api --paginate "/orgs/${ORG}/packages?package_type=container" \ - --jq '.[].name')" || { - echo "::error::Could not list ${ORG} container packages; refusing retention of promotion candidates." - promotion_retention_blocked=1 - all_pkgs="" + # An empty list is never "nothing to do": the nightly publishes into + # these packages every day, so empty means the names could not be + # resolved. That skips the nightly sweep and fails the run, but not + # before the promotion sweep below: it reads one fixed package, and + # what keeps a candidate safe is the protected set, which no part of + # this list feeds. + # + # A package whose versions cannot be read, or a version that cannot + # be deleted, is likewise reported and skipped so the rest is still + # swept, then fails the run at the end. The loop is fed by a + # here-string rather than a pipe so the flag survives it. + sweep_failed=0 + unlinked="" + linked_count=0 + gh_err="$(mktemp)" + tree="$(mktemp -d)" + pkgs="$(flux pull artifact "oci://ghcr.io/${ORG}/cozystack/cozystack-packages:nightly" --output "$tree" >/dev/null \ + && ./hack/retention-packages.sh "$tree")" || { + echo "::error::Could not resolve the ${ORG} container packages to sweep." + pkgs="" } - # grep's exit 1 now means only what it says: nothing matched. - pkgs="$(printf '%s\n' "$all_pkgs" | grep '^cozystack/' || true)" if [ -z "$pkgs" ]; then - # Fail-closed before the early exit. The flag set here means this - # listing or a protection source above went unresolved, and there is - # no sweep left to run that could carry the run to the guard below — - # so this is the last place the flag can still be honoured. - [ "$promotion_retention_blocked" -eq 0 ] || { - echo "::error::candidate protection could not be resolved and nothing was swept; refusing to report success." - exit 1 - } - echo "No cozystack/* container packages found." - exit 0 + echo "::error::No package names resolved; skipping the nightly sweep." + sweep_failed=1 + else + echo "Sweeping $(printf '%s\n' "$pkgs" | wc -l | tr -d ' ') package(s):" + printf '%s\n' "$pkgs" | sed 's/^/ /' fi - - printf '%s\n' "$pkgs" | while IFS= read -r pkg; do + while IFS= read -r pkg; do [ -n "$pkg" ] || continue enc="$(jq -rn --arg p "$pkg" '$p|@uri')" + # DELETE_TOKEN was shown to delete from a package linked to this + # repository; one linked elsewhere is not attempted, only named in + # a warning, so it cannot fail every apply run. + linked="$(gh api "/orgs/${ORG}/packages/container/${enc}" --jq '.repository.full_name // ""' 2>"$gh_err")" || { + echo "::error::Could not read ${pkg}; not swept: $(cat "$gh_err")" + sweep_failed=1 + continue + } + if [ "$linked" != "$GITHUB_REPOSITORY" ]; then + unlinked="${unlinked:+${unlinked} }${pkg}" + continue + fi + linked_count=$((linked_count + 1)) + # Version ids whose tags are non-empty AND every tag is a dated # nightly (so the floating `nightly` tag and any release tag exclude # the version). API returns versions newest-first, so the dated @@ -231,28 +262,29 @@ jobs: # array per page, so length/slicing break once a package spans # multiple pages. Slurp the raw pages and merge with `jq -s add` # first, then count and slice the combined array. - ids="$(gh api --paginate "/orgs/${ORG}/packages/container/${enc}/versions" \ + ids="$(gh api --paginate "/orgs/${ORG}/packages/container/${enc}/versions" 2>"$gh_err" \ | jq -s '[add[] | select((.metadata.container.tags | length) > 0) | select(.metadata.container.tags | all(test("^0\\.0\\.0-nightly\\.[0-9]{8}(\\.[0-9]+)*$"))) - | .id]')" + | .id]')" || { + echo "::error::Could not read ${pkg} versions; not swept: $(cat "$gh_err")" + sweep_failed=1 + continue + } total="$(printf '%s' "$ids" | jq 'length')" [ "$total" -gt "$KEEP" ] || { echo "── ${pkg}: ${total} nightlies (<= ${KEEP}); nothing to prune"; continue; } drop_ids="$(printf '%s' "$ids" | jq -r ".[${KEEP}:][]")" echo "── ${pkg}: ${total} nightlies, keep ${KEEP}, drop $((total - KEEP))" - printf '%s\n' "$drop_ids" | while IFS= read -r id; do - [ -n "$id" ] || continue - if [ "$APPLY" = "true" ]; then - echo " ✗ deleting ${pkg} version ${id}" - gh api -X DELETE "/orgs/${ORG}/packages/container/${enc}/versions/${id}" >/dev/null \ - || echo "::warning::failed to delete ${pkg} version ${id} (permissions?)" - else - echo " • would delete ${pkg} version ${id}" - fi - done - done + printf '%s\n' "$drop_ids" | xargs ./hack/retention-delete.sh "$pkg" version || sweep_failed=1 + done <<< "$pkgs" + [ -z "$unlinked" ] || echo "::warning::not linked to ${GITHUB_REPOSITORY}, skipped: ${unlinked}" + # One unlinked package is expected; all of them means nothing was swept. + if [ -n "$pkgs" ] && [ "$linked_count" -eq 0 ]; then + echo "::error::None of the resolved packages is linked to ${GITHUB_REPOSITORY}; the nightly sweep pruned nothing." + sweep_failed=1 + fi # Anything unresolved above means the protected set is incomplete, so # no candidate can be called abandoned. Skip this sweep entirely and @@ -273,24 +305,24 @@ jobs: pkg='cozystack/cozystack-packages' enc="$(jq -rn --arg p "$pkg" '$p|@uri')" cutoff="$(date -u -d "${PROMOTION_TTL_DAYS} days ago" '+%Y-%m-%dT%H:%M:%SZ')" - promotion_ids="$(gh api --paginate "/orgs/${ORG}/packages/container/${enc}/versions" \ + promotion_ids="$(gh api --paginate "/orgs/${ORG}/packages/container/${enc}/versions" 2>"$gh_err" \ | jq -s --arg cutoff "$cutoff" --arg protected "$protected_promotion_digests" '[add[] | .name as $digest | select((.metadata.container.tags | length) > 0) | select(.metadata.container.tags | all(test("^promotion-v[0-9]+\\.[0-9]+\\.[0-9]+-from-v[0-9]+\\.[0-9]+\\.[0-9]+-rc\\.[0-9]+-run-[0-9]+-[0-9]+$"))) | select(.updated_at < $cutoff) | select(($protected | split(" ") | index($digest)) == null) - | .id]')" + | .id]')" || { + echo "::error::Could not read ${pkg} versions; promotion candidates not swept: $(cat "$gh_err")" + sweep_failed=1 + promotion_ids='[]' + } promotion_total="$(printf '%s' "$promotion_ids" | jq 'length')" echo "── ${pkg}: ${promotion_total} abandoned promotion candidate(s) older than ${PROMOTION_TTL_DAYS} days" - printf '%s' "$promotion_ids" | jq -r '.[]' | while IFS= read -r id; do - [ -n "$id" ] || continue - if [ "$APPLY" = "true" ]; then - echo " ✗ deleting ${pkg} promotion candidate version ${id}" - gh api -X DELETE "/orgs/${ORG}/packages/container/${enc}/versions/${id}" >/dev/null \ - || echo "::warning::failed to delete ${pkg} version ${id} (permissions?)" - else - echo " • would delete ${pkg} promotion candidate version ${id}" - fi - done + printf '%s' "$promotion_ids" | jq -r '.[]' \ + | xargs ./hack/retention-delete.sh "$pkg" "promotion candidate version" || sweep_failed=1 + if [ "$sweep_failed" -eq 1 ]; then + echo "::error::some versions could not be read or deleted; see the errors above." + exit 1 + fi echo "Done." diff --git a/.github/workflows/stale.yaml b/.github/workflows/stale.yaml index 96e495abc..d8b40aadc 100644 --- a/.github/workflows/stale.yaml +++ b/.github/workflows/stale.yaml @@ -39,8 +39,7 @@ jobs: security/triage-needed,security/in-progress, triage/accepted,kind/regression exempt-pr-labels: >- - lifecycle/frozen,do-not-merge/hold, - kind/backport,kind/backport-previous + lifecycle/frozen,do-not-merge/hold days-before-stale: 60 days-before-close: 14 operations-per-run: 100 diff --git a/.github/workflows/tags.yaml b/.github/workflows/tags.yaml index af2705022..f35ca8265 100644 --- a/.github/workflows/tags.yaml +++ b/.github/workflows/tags.yaml @@ -18,34 +18,153 @@ permissions: contents: read jobs: - prepare-release: - name: Prepare Release + # The pre-release's images built natively for arm64 and pushed as + # -arm64, beside build-amd64, for prepare-release to stitch the two. A + # stable tag is never built (promotion copies the rc's indexes), so it skips + # this job. The packages artifact and the installer chart carry no + # architecture, so this job builds neither; build-amd64 pushes them pinned + # on amd64 digests and prepare-release republishes them repinned. The talos + # installer and matchbox are built for both arches in build-amd64, and the + # e2e sandbox is amd64 only, so none of them has an arm64 half here. + build-arm64: + name: Build arm64 images + if: contains(github.ref_name, '-') + runs-on: oracle-vm-24cpu-96gb-arm64 + # Starts from build-amd64's budget; re-measure after the first runs. + timeout-minutes: 120 + permissions: + contents: read + packages: write + + steps: + # The same no-op build-amd64 makes on a re-run of an rc whose release + # already exists, so the re-run does not rebuild arm64 for nothing. This + # token cannot see a draft, but an rc's release is published by the time + # it has been prepared; a draft left by a run that failed before that is + # rebuilt, which is the safe direction. + - name: Check if release already exists + id: check_release + uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7 + with: + script: | + const tag = context.ref.replace('refs/tags/', ''); + const releases = await github.paginate(github.rest.repos.listReleases, { + owner: context.repo.owner, + repo: context.repo.repo, + per_page: 100 + }); + const exists = releases.some(r => r.tag_name === tag); + core.setOutput('release_exists', exists); + console.log(exists ? `Release ${tag} already exists, nothing to build` : `No release ${tag} yet`); + + - name: Checkout code + if: steps.check_release.outputs.release_exists == 'false' + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + fetch-depth: 0 + fetch-tags: true + persist-credentials: false + + - name: Set up build toolchain + if: steps.check_release.outputs.release_exists == 'false' + run: | + command -V docker jq yq + yq --version | grep -q mikefarah + + - name: Login to GHCR + if: steps.check_release.outputs.release_exists == 'false' + uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3 + with: + username: ${{ github.repository_owner }} + password: ${{ secrets.GITHUB_TOKEN }} + registry: ghcr.io + env: + DOCKER_CONFIG: ${{ runner.temp }}/.docker + + - name: Login to OCIR (build cache) + if: steps.check_release.outputs.release_exists == 'false' + uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3 + with: + username: ${{ secrets.OCIR_USER }} + password: ${{ secrets.OCIR_TOKEN }} + registry: iad.ocir.io + env: + DOCKER_CONFIG: ${{ runner.temp }}/.docker + + # docker.io pulls go through the mirror in hack/buildkitd.toml, as the + # PR builds' do: anonymous Docker Hub pulls from these runners are rate + # limited. + - name: Set up Buildx (docker-container driver, docker.io mirror) + if: steps.check_release.outputs.release_exists == 'false' + id: buildx + uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3 + with: + driver: docker-container + buildkitd-config: hack/buildkitd.toml + env: + DOCKER_CONFIG: ${{ runner.temp }}/.docker + + - name: Build arm64 images + if: steps.check_release.outputs.release_exists == 'false' + run: | + set -euo pipefail + # Assigned and checked before the loop: a build-matrix.sh failure + # inside `for unit in $(...)` would run no iteration and leave a + # green job that built nothing. + units="$(MATRIX_ARCH=arm64 hack/build-matrix.sh | jq -r '.[]')" + [ -n "$units" ] + for unit in $units; do + make -C "$unit" image + done + make -C packages/core/installer image-operator + env: + DOCKER_CONFIG: ${{ runner.temp }}/.docker + BUILDER: ${{ steps.buildx.outputs.name }} + SBOM: '1' + PLATFORM: linux/arm64 + CACHE_REGISTRY: iad.ocir.io/idyksih5sir9/cozystack + # Read the arm64 cache build-arm64-nightly.yaml keeps warm; a release + # build never writes one. + CACHE_TAG: buildcache-arm64 + WRITE_CACHE: '0' + IMAGE_TAG: ${{ github.ref_name }}-arm64 + PUBLISH_VERSIONED: '0' + PUBLISH_FLOATING: '0' + + # The amd64 half of a pre-release build, run beside build-arm64 rather than + # after it: the images, the stamped tree and the release assets. Its make + # build also pushes the packages artifact and the installer chart pinned on + # amd64 digests. The stitch, the gate, the republish of both and the release + # itself happen in prepare-release once both halves are built, so the tree, + # the log of pushed tags and the assets travel there as artifacts. + # It runs for every tag, since the release-exists no-op and the rejection of + # a hand-pushed stable tag live here. + build-amd64: + name: Build amd64 images and assets # Ephemeral pool, not the dedicated self-hosted runner (#2937 decommission). # Serial `make build` + `make assets` is CPU-bound, so use the large shape — # same as the main cache warmer (build-main.yaml). runs-on: oracle-vm-24cpu-96gb-x86-64 + # The budget prepare-release had while it also built; the stitch and the + # uploads it no longer runs moved to prepare-release with their own. timeout-minutes: 120 + env: + # The pipe falls back to direct on any proxy error (hack/common-envs.mk). + GOPROXY: "https://proxy.golang.org|direct" outputs: # A release (draft or published) already exists for this tag, so the # build/draft/branch/PR steps are no-ops. Downstream jobs that still need # to run on an existing release (changelog, website docs) must NOT gate on # this — it means "skip the rebuild", not "skip everything". release_exists: ${{ steps.check_release.outputs.release_exists }} + tag: ${{ steps.tag.outputs.tag }} + is_rc: ${{ steps.tag.outputs.is_rc }} permissions: + # contents: write only so the release listing includes drafts. contents: write packages: write - pull-requests: write - actions: write steps: - - name: Generate GitHub App token - id: app-token - uses: actions/create-github-app-token@d72941d797fd3113feb6b93fd0dec494b13a2547 # v1 - with: - app-id: ${{ secrets.COZYSTACK_CI_APP_ID }} - private-key: ${{ secrets.COZYSTACK_CI_PRIVATE_KEY }} - owner: cozystack - # Skip the build when a release (draft OR published) already exists for # this tag: # - re-runs of the same rc/nightly tag become idempotent no-ops; @@ -132,21 +251,21 @@ jobs: } core.setOutput('branch', branch); - # Checkout & login once - name: Checkout code if: steps.check_release.outputs.release_exists == 'false' uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: fetch-depth: 0 fetch-tags: true + persist-credentials: false # Ephemeral runners lack the flux CLI the installer's image-packages step - # shells out to; install if absent (idempotent). - - name: Set up build toolchain + # shells out to. + - name: Set up flux if: steps.check_release.outputs.release_exists == 'false' - run: | - command -v flux >/dev/null \ - || curl -fsSL https://fluxcd.io/install.sh | sudo bash + uses: fluxcd/flux2/action@04acaec6161ac4fb1a82ffafa88901c03271d34f # v2.8.6 + with: + version: "2.8.6" - name: Login to GHCR if: steps.check_release.outputs.release_exists == 'false' @@ -172,16 +291,45 @@ jobs: env: DOCKER_CONFIG: ${{ runner.temp }}/.docker + # Every image carries an SBOM attestation, which the default docker driver + # cannot attach, and the matchbox index below needs this driver too. + # docker.io pulls go through the mirror in hack/buildkitd.toml, as the + # arm64 leg's do. `use: false` keeps plain `docker build` on the default + # driver; the builds name this one with BUILDER. + - name: Set up Buildx (docker-container driver, docker.io mirror) + if: steps.check_release.outputs.release_exists == 'false' + id: buildx + uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3 + with: + driver: docker-container + buildkitd-config: hack/buildkitd.toml + use: false + env: + DOCKER_CONFIG: ${{ runner.temp }}/.docker + # Build project artifacts - name: Build if: steps.check_release.outputs.release_exists == 'false' - run: make build + run: | + mkdir -p "${PUSHED_TAGS_LOG%/*}" + make build + # The arm64 assets published below install this image, and building + # its arm64 half needs no QEMU, so it is pushed again as both arches. + make -C packages/core/talos image-talos PLATFORM=linux/amd64,linux/arm64 + # The arm64 leg skips the talos package, so matchbox gets no arm64 + # half to stitch. Its Dockerfile only copies files, so both arches + # build here without QEMU and the stamped ref pins the index. + make -C packages/core/talos image-matchbox PLATFORM=linux/amd64,linux/arm64 env: DOCKER_CONFIG: ${{ runner.temp }}/.docker + BUILDER: ${{ steps.buildx.outputs.name }} + SBOM: '1' # Cache manifests are registry-portable (oci-mediatypes=true) — read # them from OCIR while pushing images to GHCR. A missing :buildcache # ref 404s harmlessly into a cold build. CACHE_REGISTRY: iad.ocir.io/idyksih5sir9/cozystack + # amd64 here; build-arm64 builds arm64 natively. + PLATFORM: linux/amd64 # Push the release tag as :IMAGE_TAG (vX.Y.Z-rc.N) and the component # versions as :. Deliberately NO PUBLISH_FLOATING: this # job only ever runs for a prerelease (a stable tag is rejected or @@ -190,10 +338,153 @@ jobs: # promotion, which moves it only for the newest stable (finalize). IMAGE_TAG: ${{ github.ref_name }} PUBLISH_VERSIONED: '1' + # Every tag the build pushes, for the stitch to move onto the + # multi-arch indexes. + PUSHED_TAGS_LOG: ${{ runner.temp }}/release-tree/pushed-tags + + # Built here rather than in prepare-release: the Talos assets reuse the + # kernel, initramfs and installer make build already produced for the + # images, and they build while the arm64 half is still running. + - name: Build assets + if: steps.check_release.outputs.release_exists == 'false' + run: make assets + + # --cached after adding everything, so a file the build created travels + # too, not only the ones it changed. + - name: Capture the stamped tree + if: steps.check_release.outputs.release_exists == 'false' + run: | + git add --all + git diff --cached --binary HEAD >"${{ runner.temp }}/release-tree/stamped-tree.patch" + + - name: Upload the stamped tree and the pushed tags + if: steps.check_release.outputs.release_exists == 'false' + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: release-tree + path: ${{ runner.temp }}/release-tree/ + if-no-files-found: error + # The same window as release-assets: a re-run of prepare-release + # needs both. + retention-days: 7 + + # The installer tarballs, one per arch, are what the build pushed as the + # talos image and are not release assets. + - name: Upload the assets + if: steps.check_release.outputs.release_exists == 'false' + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: release-assets + path: | + _out/assets/ + !_out/assets/installer-*.tar + if-no-files-found: error + # Long enough to re-run failed jobs; the assets are several GB. + retention-days: 7 + + prepare-release: + name: Prepare Release + needs: [build-amd64, build-arm64] + # build-arm64 is skipped only for a stable tag, which never builds. On a + # pre-release, either half failing or being cancelled leaves this job + # skipped and the run red: an rc ships multi-arch or not at all. + if: ${{ !cancelled() && needs.build-amd64.result == 'success' && (needs.build-arm64.result == 'success' || needs.build-arm64.result == 'skipped') }} + runs-on: oracle-vm-24cpu-96gb-x86-64 + # The stitch reads and writes every first-party image once, then the + # packages artifact, the chart and the assets are pushed; start there and + # re-measure after the first runs. + timeout-minutes: 60 + outputs: + release_exists: ${{ needs.build-amd64.outputs.release_exists }} + permissions: + contents: write + packages: write + pull-requests: write + actions: write + id-token: write # keyless signing of the release checksums in hack/upload-assets.sh + + steps: + - name: Generate GitHub App token + if: needs.build-amd64.outputs.release_exists == 'false' + id: app-token + uses: actions/create-github-app-token@d72941d797fd3113feb6b93fd0dec494b13a2547 # v1 + with: + app-id: ${{ secrets.COZYSTACK_CI_APP_ID }} + private-key: ${{ secrets.COZYSTACK_CI_PRIVATE_KEY }} + owner: cozystack + + - name: Checkout code + if: needs.build-amd64.outputs.release_exists == 'false' + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + fetch-depth: 0 + fetch-tags: true + + # The stitch and the multi-arch gate read the registry with skopeo and + # the tree with mikefarah yq; the republish needs flux and helm. + - name: Set up flux + if: needs.build-amd64.outputs.release_exists == 'false' + uses: fluxcd/flux2/action@04acaec6161ac4fb1a82ffafa88901c03271d34f # v2.8.6 + with: + version: "2.8.6" + - name: Set up build toolchain + if: needs.build-amd64.outputs.release_exists == 'false' + run: | + command -v skopeo >/dev/null \ + || { sudo apt-get update -qq && sudo apt-get install -y -qq skopeo; } + command -V skopeo jq yq helm + yq --version | grep -q mikefarah + + - name: Login to GHCR + if: needs.build-amd64.outputs.release_exists == 'false' + uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3 + with: + username: ${{ github.repository_owner }} + password: ${{ secrets.GITHUB_TOKEN }} + registry: ghcr.io + env: + DOCKER_CONFIG: ${{ runner.temp }}/.docker + + - name: Download the amd64 build + if: needs.build-amd64.outputs.release_exists == 'false' + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: release-tree + path: ${{ runner.temp }}/release-tree + + - name: Download the assets + if: needs.build-amd64.outputs.release_exists == 'false' + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: release-assets + path: _out/assets + + - name: Apply the stamped tree + if: needs.build-amd64.outputs.release_exists == 'false' + run: git apply --binary "${{ runner.temp }}/release-tree/stamped-tree.patch" + + # Join each image with its arm64 twin, moving every tag the amd64 build + # pushed for it, and gate on the result, then republish the packages + # artifact and the installer chart from the repinned tree: the amd64 + # build pushed both pinned on amd64-only digests, and the chart's values + # pin the operator image and the artifact digest. + - name: Stitch multi-arch indexes and republish + if: needs.build-amd64.outputs.release_exists == 'false' + run: | + set -eu + hack/stitch-multiarch.sh packages "$REGISTRY" "$IMAGE_TAG" + hack/verify-multiarch.sh packages + make -C packages/core/installer image-packages chart + env: + DOCKER_CONFIG: ${{ runner.temp }}/.docker + REGISTRY_AUTH_FILE: ${{ runner.temp }}/.docker/config.json + REGISTRY: ghcr.io/cozystack/cozystack + IMAGE_TAG: ${{ github.ref_name }} + PUSHED_TAGS_LOG: ${{ runner.temp }}/release-tree/pushed-tags # Commit built artifacts - name: Commit release artifacts - if: steps.check_release.outputs.release_exists == 'false' + if: needs.build-amd64.outputs.release_exists == 'false' env: APP_TOKEN: ${{ steps.app-token.outputs.token }} run: | @@ -213,13 +504,13 @@ jobs: # Create or reuse draft release - name: Create / reuse draft release - if: steps.check_release.outputs.release_exists == 'false' + if: needs.build-amd64.outputs.release_exists == 'false' id: release uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7 with: script: | - const tag = '${{ steps.tag.outputs.tag }}'; - const isRc = ${{ steps.tag.outputs.is_rc }}; + const tag = '${{ needs.build-amd64.outputs.tag }}'; + const isRc = ${{ needs.build-amd64.outputs.is_rc }}; // Paginate: the default page is 30, and promote-created stable drafts // plus accreting rc releases can push an in-flight draft off it. const releases = await github.paginate(github.rest.repos.listReleases, { @@ -245,12 +536,39 @@ jobs: core.setOutput('upload_url', rel.upload_url); - # Build + upload assets (optional) - - name: Build & upload assets - if: steps.check_release.outputs.release_exists == 'false' + # hack/upload-assets.sh writes the release SBOM with syft and signs the + # checksums of every asset with cosign, keylessly, as this job. syft is + # the release tarball checked against a committed SHA-256, for the reason + # given at the same step in promote-rc.yaml: this job holds the app token, + # the GHCR login and an OIDC token for the signing identity, so it runs no + # install script fetched at run time. Bump with promote-rc.yaml. + - name: Set up syft + if: needs.build-amd64.outputs.release_exists == 'false' + env: + SYFT_VERSION: "1.54.1" + SYFT_SHA256: "c069905b391cc4c20a5ba65ad5c10be2a7ba074f8ea6ad203e24d14e303dad47" run: | - make assets - make upload_assets VERSION=${{ steps.tag.outputs.tag }} + syft_dir="${RUNNER_TEMP}/syft" + mkdir -p "$syft_dir" + curl -fsSL -o "$syft_dir/syft.tar.gz" \ + "https://github.com/anchore/syft/releases/download/v${SYFT_VERSION}/syft_${SYFT_VERSION}_linux_amd64.tar.gz" + printf '%s %s\n' "$SYFT_SHA256" "$syft_dir/syft.tar.gz" | sha256sum -c - + tar -xzf "$syft_dir/syft.tar.gz" -C "$syft_dir" syft + rm -f "$syft_dir/syft.tar.gz" + echo "$syft_dir" >> "$GITHUB_PATH" + # cosign is the version docs/release/signatures-and-sbom.md asks users + # for, as in promote-rc.yaml. Bump with it. + - name: Set up cosign + if: needs.build-amd64.outputs.release_exists == 'false' + uses: sigstore/cosign-installer@6f9f17788090df1f26f669e9d70d6ae9567deba6 # v4.1.2 + with: + cosign-release: v3.1.3 + + # The assets were built by build-amd64; the operator manifests are + # rendered here, from the tree pinned on the index digests. + - name: Upload assets + if: needs.build-amd64.outputs.release_exists == 'false' + run: make upload_assets VERSION=${{ needs.build-amd64.outputs.tag }} env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -261,12 +579,12 @@ jobs: # validate it. rc tags are write-once, so there is nothing to protect with # draft status. prerelease:true keeps it off the "Latest release" pointer. - name: Publish rc release - if: steps.check_release.outputs.release_exists == 'false' && steps.tag.outputs.is_rc == 'true' + if: needs.build-amd64.outputs.release_exists == 'false' && needs.build-amd64.outputs.is_rc == 'true' uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7 with: github-token: ${{ steps.app-token.outputs.token }} script: | - const tag = '${{ steps.tag.outputs.tag }}'; + const tag = '${{ needs.build-amd64.outputs.tag }}'; const releases = await github.paginate(github.rest.repos.listReleases, { owner: context.repo.owner, repo: context.repo.repo, per_page: 100 }); @@ -287,7 +605,7 @@ jobs: # the push when nothing changed; force-update (and log it) only when the # branch genuinely moves. Unlike the tags above, force here is legitimate. - name: Create release branch - if: steps.check_release.outputs.release_exists == 'false' + if: needs.build-amd64.outputs.release_exists == 'false' env: APP_TOKEN: ${{ steps.app-token.outputs.token }} run: | @@ -322,7 +640,10 @@ jobs: rc-e2e: name: E2E Release Candidate needs: prepare-release - if: needs.prepare-release.result == 'success' && contains(github.ref_name, '-rc.') + # !cancelled(): every job below build-arm64 carries a status function, + # since a stable tag skips build-arm64. This one only runs for an rc, + # where build-arm64 always runs, so here it just follows that rule. + if: ${{ !cancelled() && needs.prepare-release.result == 'success' && contains(github.ref_name, '-rc.') }} # A caller's permissions are the ceiling for every job in the called # workflow, and GitHub validates that ceiling STATICALLY, when it creates the # run — before this job's `if:` is evaluated, let alone before a step runs. @@ -377,7 +698,9 @@ jobs: # firing on every rc would open a changelog-vX.Y.Z-rc.N PR that never merges # (no docs/changelogs/v*-rc*.md is a real file). Cumulative rc notes are # finalized at the stable release, so the changelog is generated then. - if: needs.prepare-release.result == 'success' && !contains(github.ref_name, '-') + # !cancelled(): this job runs on stable tags only, which skip build-arm64, + # and a skipped ancestor makes the implicit success() false. + if: ${{ !cancelled() && needs.prepare-release.result == 'success' && !contains(github.ref_name, '-') }} # Non-blocking: this is a best-effort backfill of an already-published # release, never a gate on one. continue-on-error: true diff --git a/.github/workflows/ui-test.yaml b/.github/workflows/ui-test.yaml index 8f3d0d118..84e39bd76 100644 --- a/.github/workflows/ui-test.yaml +++ b/.github/workflows/ui-test.yaml @@ -1,6 +1,6 @@ name: UI Test -# Typecheck + unit tests for the in-tree console SPA +# Typecheck, lint and unit tests for the in-tree console SPA # (packages/system/dashboard/images/console, vendored from cozystack-ui). # The container image itself is built by `make build` in the main build job. @@ -18,7 +18,7 @@ defaults: run: working-directory: packages/system/dashboard/images/console -# Read-only token; this workflow only checks out code and runs typecheck/tests. +# Read-only token; this workflow only checks out code and runs typecheck/lint/tests. permissions: contents: read @@ -54,5 +54,8 @@ jobs: - name: Typecheck run: pnpm typecheck + - name: Lint + run: pnpm lint + - name: Test run: pnpm test diff --git a/.github/workflows/update-releasenotes.yaml b/.github/workflows/update-releasenotes.yaml index d52cd8dbf..697b3995d 100644 --- a/.github/workflows/update-releasenotes.yaml +++ b/.github/workflows/update-releasenotes.yaml @@ -9,9 +9,12 @@ on: # (tags.yaml generate-changelog) merges or when a maintainer edits an # existing changelog. The v* glob deliberately skips template.md / # patch-template.md in the same directory. Every other main push left this - # job scanning the latest 30 releases for nothing. + # job scanning the latest 30 releases for nothing. A docs/releasenotes/v*.md + # file, when it has content, is the body in place of its changelog, so it + # triggers the sync too. paths: - 'docs/changelogs/v*.md' + - 'docs/releasenotes/v*.md' # Manual re-sync hatch: re-run the changelog -> release-body sync without # touching a changelog file (e.g. if a release body drifted out of sync). workflow_dispatch: @@ -47,6 +50,8 @@ jobs: const path = require('path'); const changelogDir = 'docs/changelogs'; + // Same limit and reason as MAX_BODY_BYTES in pull-requests-release.yaml. + const MAX_BODY_BYTES = 100000; // Get releases from first page const releases = await github.rest.repos.listReleases({ @@ -61,7 +66,12 @@ jobs: for (const release of releases.data) { const tag = release.tag_name; const changelogFile = `${tag}.md`; - const changelogPath = path.join(changelogDir, changelogFile); + // docs/releasenotes/.md is the body when it has content, as + // in finalize; the changelog otherwise. + const notesPath = path.join('docs/releasenotes', changelogFile); + const changelogPath = fs.existsSync(notesPath) && fs.readFileSync(notesPath, 'utf8').trim() + ? notesPath + : path.join(changelogDir, changelogFile); console.log(`\nProcessing release: ${tag}`); @@ -85,6 +95,16 @@ jobs: continue; } + // Finalize publishes a link in place of a body this long. Never + // here: a changelog that reaches main without its release notes + // (the tags.yaml backstop ports only the changelog) would replace + // a good published body with it. + const bytes = Buffer.byteLength(changelogContent, 'utf8'); + if (bytes > MAX_BODY_BYTES) { + console.log(`::warning::${changelogPath} is ${bytes} bytes, over MAX_BODY_BYTES (${MAX_BODY_BYTES}); leaving the body of release ${tag} as it is.`); + continue; + } + // Check if content is already up to date const currentBody = release.body || ''; if (currentBody.trim() === changelogContent.trim()) { diff --git a/.gitignore b/.gitignore index ee2c2332a..f1b99efdb 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ _repos # root-level binary waiting to happen — each ~80 MB, and nothing else here # matched them, leaving `git add .` one keystroke from committing one. /api-gate +/backport-batch /backup-controller /backupstrategy-controller /check-readiness @@ -22,6 +23,7 @@ _repos /flux-shard-operator /kubeovn-plunger /lineage-controller-webhook +/observability-proxy /securitygroup-controller # User-specific stuff diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 3fae5b4d7..fa3ec818f 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -13,19 +13,25 @@ repos: files: ^(api/|pkg/apis/|pkg/generated/|internal/crdinstall/manifests/|packages/system/cozystack-controller/definitions/|packages/system/application-definition-crd/definition/|packages/system/backup-controller/definitions/|packages/system/backupstrategy-controller/definitions/|hack/update-codegen\.sh$|hack/boilerplate\.go\.txt$|Makefile$) pass_filenames: false - id: run-make-generate - name: Run 'make generate' in all app directories + name: Run 'make generate' in all package directories entry: | sh -c 'exec flock -x "$(git rev-parse --git-common-dir)/pre-commit.lock" "$@"' -- sh -c ' - for dir in ./packages/apps/*/ ./packages/extra/*/; do - if [ -d "$dir" ]; then - echo "Running make generate in $dir" - make generate -C "$dir" || exit $? - fi - done + hack/pre-commit-generate-packages.sh || exit $? git diff --color=always | cat ' language: system files: ^.*$ + # The complete hack/*.bats and POSIX-compatibility pass is intentionally a + # manual local hook because it requires bats-core and has substantial wall + # time even with GNU parallel. Run it before pushing with: + # pre-commit run bats-unit-tests --hook-stage manual --all-files + # Pull-request CI remains the unconditional gate. + - id: bats-unit-tests + name: Run hack/*.bats unit tests + entry: make bats-unit-tests bats-posix-compat-tests + language: system + stages: [manual] + pass_filenames: false # Lints changed GitHub Actions workflows for unpinned actions and excessive token # permissions (audit scope is set in .github/zizmor.yml). Runs offline so it needs # no GitHub token locally. The same gate runs tree-wide in .github/workflows/zizmor.yml. diff --git a/ADOPTERS.md b/ADOPTERS.md index d6cacdc55..936bfe296 100644 --- a/ADOPTERS.md +++ b/ADOPTERS.md @@ -33,3 +33,4 @@ This list is sorted in chronological order, based on the submission date. | [Hidora](https://hikube.cloud) | @matthieu-robin | 2025-09-17 | Hidora is a Swiss cloud provider delivering managed services and infrastructure solutions through datacenters located in Switzerland, ensuring data sovereignty and reliability. Its sovereign cloud platform, Hikube, is designed to run workloads with high availability across multiple datacenters, providing enterprises with a secure and scalable foundation for their applications based on Cozystack. | | [QOSI](https://qosi.kz) | @tabu-a | 2025-10-04 | QOSI is a non-profit organization driving open-source adoption and digital sovereignty across Kazakhstan and Central Asia. We use Cozystack as a platform for deploying sovereign, GPU-enabled clouds and educational environments under the National AI Program. Our goal is to accelerate the region’s transition toward open, self-hosted cloud-native technologies | | [Cloupard](https://cloupard.kz/) | @serjiott | 2025-12-18 | Cloupard is a public cloud provider offering IaaS and PaaS services via datacenters in Kazakhstan and Uzbekistan. Uses CozyStack on bare metal to extend its managed PaaS offerings. | +| [CageForge](https://cageforge.com/) | @themoriarti | 2026-11-03 | CageForge is a short-cycle R&D company providing independent expertise in cloud native, Cozystack and security for customers in finance, telecom, hosting and cloud providers. We run Cozystack both as a bare-metal installation and on Proxmox VE through the Proxmox integration, and contribute the Proxmox-related work back upstream. | diff --git a/AGENTS.md b/AGENTS.md index 97e3e1a42..3e74ff133 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,23 +16,27 @@ This file provides structured guidance for AI coding assistants and agents worki - **Release creation** (e.g., "create release", "prepare release", "tag release", "make a release") - Read: [`releasing.md`](./docs/agents/releasing.md) - - Action: Read the file and follow the referenced release process in `docs/release.md` + - Action: Read the file and follow the referenced release process: [`docs/release.md`](./docs/release.md) indexes one page per topic under `docs/release/` + +- **Backports, patch content** (e.g., "backport this fix", "will this reach 1.6", "what goes into the next patch", "open a PR against release-X.Y") + - Read: [`backports.md`](./docs/release/backports.md) + - Action: Read the entire file. Backports are automatic: a fix merged to `main` with a `fix` title, or a `security` one for a fix that comes through a security advisory, reaches the release lines the batch runs for, the newest released lines and any line in its rc window, so never open a backport PR by hand. A pull request against `release-*` from outside the team is closed automatically when it is opened; a maintainer keeps a fix with no counterpart on `main` by reopening it - **Image references, tags and digests** (e.g., "why is this image tagged rc", "add an image to a package", "change how an image is stamped", "promotion/nightly missed an image", "where do image refs live") - Read: [`image-refs.md`](./docs/agents/image-refs.md) - - Action: Read the entire file. Image refs live in three storage shapes and carry three classes of tag; a tool that knows only one shape skips images silently rather than failing. `hack/lib/image-refs.sh` is the enumeration shared by the promote, retag, mirror and candidate-verify tooling — extend it there rather than teaching an individual script a new path. The one exception is `hack/overlay-main-images.sh`, which reads refs but walks the tree itself, so a newly declared file does not reach it; `hack/promote-packages-artifact.sh` sources nothing because it publishes the whole tree and consumes no refs at all — the doc carries both cases + - Action: Read the entire file. Image refs live in three storage shapes and carry three classes of tag; a tool that knows only one shape skips images silently rather than failing. `hack/lib/image-refs.sh` is the enumeration shared by the promote, retag, mirror, candidate-verify, multi-arch stitch and verify, and retention tooling — extend it there rather than teaching an individual script a new path. The one exception is `hack/overlay-main-images.sh`, which reads refs but walks the tree itself, so a newly declared file does not reach it; `hack/promote-packages-artifact.sh` sources nothing because it publishes the whole tree and consumes no refs at all — the doc carries both cases - **Retiring an application** (e.g., "remove the X app", "deprecate X", "drop X from the catalog", "what happens to instances people already created") - Read: [`deprecating-applications.md`](./docs/deprecating-applications.md) - Action: Read the entire file before touching the tree. Deleting a chart is not a deletion: pruning its PackageSource garbage-collects the ArtifactGenerator and both ExternalArtifacts, which are the `chartRef` targets of the rd release and of every tenant release, so surviving instances sit `Ready=False` for good and `HelmReleaseNotReady` fires on every cluster carrying the bundle. An application with a successor migrates onto it; one without is frozen, per cluster, on the artifact that cluster already renders from, with the digest read off the live OCIRepository at hook time rather than written into the migration. The tenant RBAC grant comes out of the chart and is re-applied by the migration on the clusters that froze -- **Project structure, conventions, code layout** (e.g., "where should I put X", "what's the convention for Y", "how is the project organized") +- **Go code, Helm charts, build and test commands, project structure** (e.g., "add a field to this CRD", "fix this controller", "add a value to the postgres chart", "regenerate the values schema", "how do I build/test this", "where should I put X", "what's the convention for Y", "how is the project organized") - Read: [`overview.md`](./docs/agents/overview.md) - - Action: Read relevant sections to understand project structure and conventions + - Action: Read the section that matches — `Go Code` (controller-runtime patterns, kubebuilder markers), `Helm Charts` (umbrella pattern, vendored upstream charts, which `lookup` is allowed), `Values schema generation`, `Build and Development Commands`, `Testing`, `Package Structure` - **E2E tests and E2E CI** (e.g., "write/fix an e2e test", "stabilize a flaky test", "add a bats test", "change the e2e workflow", "why did e2e fail") - Read: [`e2e-testing.md`](./docs/agents/e2e-testing.md) - - Action: Read the entire file and follow the conventions exactly — no new retries on deterministic steps, event-driven backstops before every `kubectl wait`, no test-level `EXIT`/`RETURN` traps (a self-contained one inside a Chainsaw `script` step or an explicit subshell is fine — see the doc), fail-fast on HelmRelease readiness + - Action: Read the entire file and follow the conventions exactly — no new retries on deterministic steps, event-driven backstops before every `kubectl wait`, no test-level `EXIT`/`RETURN` traps (a self-contained one inside a Chainsaw `script` step or an explicit subshell is fine — see the doc), no assertion beginning with `!` (errexit exempts an inverted status, so it can be silently ignored — write `if cmd; then echo "FAIL: …"; false; fi`), fail-fast on HelmRelease readiness - **General questions about contributing** - Read: [`contributing.md`](./docs/agents/contributing.md) @@ -47,13 +51,21 @@ This file provides structured guidance for AI coding assistants and agents worki - PR titles: a Conventional Commits header (`type(scope): description`, types from [`contributing.md`](./docs/agents/contributing.md)) auto-applies `kind/*` and `area/*` via `.github/workflows/pr-labeler.yaml`. Append `!` (or add a `BREAKING CHANGE:` footer) to apply `kind/breaking-change` **Important rules:** -- ✅ **ONLY read the file if the task matches the documented process scope** - do not read files for tasks that don't match their purpose -- ✅ **ALWAYS read the file FIRST** before starting the task (when applicable) -- ✅ **Follow instructions EXACTLY** as written in the documentation -- ✅ **Do NOT skip mandatory steps** (especially in changelog.md) -- ✅ **Do NOT assume** you know the process - always check the documentation when the task matches -- ❌ **Do NOT read files** for tasks that are outside their documented scope -- 📖 **Note**: [`overview.md`](./docs/agents/overview.md) can be useful as a reference to understand project structure and conventions, even when not explicitly required by the task + +- **Match scope, then read first.** Load a process file only when the task genuinely falls in its scope, and load it before starting work — not midway through. Tasks outside a file's scope should not pull it into context. +- **Follow it exactly.** Do not assume you already know the process, and do not skip steps (`changelog.md` especially). Where the documentation and your instinct disagree, the documentation wins. +- **[`overview.md`](./docs/agents/overview.md) is the standing reference** for structure and conventions, useful even when no route above points at it. + +## Working Principles + +These hold for every task, whichever document the routes above point at. + +- **A causal claim needs a mechanism.** A failure that appeared after a commit, a bump or a rerun was not thereby caused by it, and matching symptoms prove nothing either: unrelated faults often look identical from outside. Back a root cause with a log line, a reproducer, a bisect, or a ruled-out alternative; without one, name at least two hypotheses and what would tell them apart. Before tying a problem to a change, check whether it predates the change (an older run, a condition's `lastTransitionTime`, `git blame`). Close a hypothesis when evidence rules it out. Missing evidence means inconclusive, not coincidence: record that limit, stop treating the hypothesis as a cause, and revisit it only with new evidence or a concrete discriminating check. +- **Verify, do not recall.** Versions, CLI flags, API fields and defaults drift faster than a model's training data. Check the upstream source, the documentation at the pinned version, or `--help` before writing code or advice that depends on them. When a problem is not solved after two attempts, stop and research it instead of trying a third variation. +- **Long flag names.** New and changed commands in docs, scripts, CI and PR text spell options out (`--namespace`, `--output`, `--filename`, `--message`), so that a reader does not need to know what `-f` means to this particular tool. An option with no long form is the only exception. +- **Name the cluster.** Management and tenant clusters are different targets. Every `kubectl` call, including reads, carries `--context`; cluster-facing Helm commands carry `--kube-context`. Use the human-approved target and the task's kubeconfig where one was supplied, not the ambient current context. Before running wrappers or cluster-facing tests, verify that they propagate the chosen target. Tests that need no cluster must not inherit live cluster credentials. +- **Respect the reader's time.** Lead with the answer or decision; prefer direct wording over formalities, filler and repeated conclusions. Put necessary detail after a short summary or in a linked document. +- **Public text.** Everything that reaches GitHub (commits, PR and issue bodies, review comments, code comments) is in English. It names no private infrastructure (cluster, customer or internal namespace names) and none of an agent's private tooling (custom skills, slash commands). Nothing is published on someone's behalf without their approval, unless they have delegated it. ## Project Overview @@ -62,6 +74,7 @@ This file provides structured guidance for AI coding assistants and agents worki ## Quick Reference ### Code Structure + - `packages/core/` - Core platform charts (installer, platform) - `packages/system/` - System components (CSI, CNI, operators) - `packages/apps/` - User-facing applications in catalog @@ -70,6 +83,7 @@ This file provides structured guidance for AI coding assistants and agents worki - `api/` - Kubernetes CRDs ### Conventions + - **Helm Charts**: Umbrella pattern, vendored upstream charts in `charts/` - **Go Code**: Controller-runtime patterns, kubebuilder style - **Git Commits**: Conventional Commits (`type(scope): description`) with `--signoff`; an agent-assisted commit adds one `Assisted-by: LLM` trailer @@ -77,6 +91,7 @@ This file provides structured guidance for AI coding assistants and agents worki - **Prose**: One continuous line per paragraph — see [Prose Formatting](#prose-formatting) ### What NOT to Do + - ❌ Edit `/vendor/`, `zz_generated.*.go`, upstream charts directly - ❌ Modify `go.mod`/`go.sum` manually (use `go get`) - ❌ Force push to main/master diff --git a/GENERAL_TECHNICAL_REVIEW.md b/GENERAL_TECHNICAL_REVIEW.md index 9e7818b55..81b83fb8a 100644 --- a/GENERAL_TECHNICAL_REVIEW.md +++ b/GENERAL_TECHNICAL_REVIEW.md @@ -88,7 +88,7 @@ ### Rollout, Upgrade and Rollback Planning -* **Compatibility with Kubernetes & frequency.** Cozystack ships a curated, tested Kubernetes version per release; tenant clusters are Certified Kubernetes following upstream skew/support. Platform upgrades are delivered as new Cozystack releases. The authoritative list of what has shipped is the [GitHub Releases page](https://github.com/cozystack/cozystack/releases); which release lines are still receiving security fixes is defined as a rolling rule in [SECURITY.md](https://github.com/cozystack/cozystack/blob/main/SECURITY.md): the latest stable minor and the two preceding minors are supported, older `1.x` minors receive critical and upgrade-blocking fixes at maintainer discretion, `v0.41.x` is end of life and anything earlier is unsupported. Specific version numbers are deliberately not restated here, because they drift with every release. Note that being in a supported line does not entail receiving every fix: the project has no documented rule for which supported lines a given fix is backported to, and that is recorded in `SECURITY.md` rather than presented as a policy. +* **Compatibility with Kubernetes & frequency.** Cozystack ships a curated, tested Kubernetes version per release; tenant clusters are Certified Kubernetes following upstream skew/support. Platform upgrades are delivered as new Cozystack releases. The authoritative list of what has shipped is the [GitHub Releases page](https://github.com/cozystack/cozystack/releases); which release lines are still receiving security fixes is defined as a rolling rule in [SECURITY.md](https://github.com/cozystack/cozystack/blob/main/SECURITY.md): the two latest minor releases are supported, older `1.x` minors receive critical and upgrade-blocking fixes at maintainer discretion, `v0.41.x` is end of life and anything earlier is unsupported. Specific version numbers are deliberately not restated here, because they drift with every release. Note that being in a supported line does not entail receiving every fix: which fixes reach a supported line is the [backport policy](https://github.com/cozystack/cozystack/blob/main/docs/release/backports.md), which keeps breaking changes, platform migrations and the like for the next minor. * **Upgrade procedure** ([upgrade docs](https://cozystack.io/docs/v1.6/operations/cluster/upgrade/)): run the troubleshooting/health checklist; annotate the `cozy-system` namespace and `cozystack-version` ConfigMap with `helm.sh/resource-policy=keep`; `helm upgrade cozystack oci://ghcr.io/cozystack/cozystack/cozy-installer --version X.Y.Z` (**do not** use `--reuse-values` — the chart pins OCI repo/package versions); verify pods and `kubectl get hr -A`. * **Rollback.** GitOps/Helm-managed with versioned releases; roll back by targeting the previous release (previous HelmRelease revisions) via the same mechanism. Stateful data (databases, VM disks) persists on replicated storage across control-plane rollbacks. **No dedicated rollback runbook is published**, and version-skip constraints for downgrades are not documented; the [upgrade docs](https://cozystack.io/docs/v1.6/operations/cluster/upgrade/) currently cover the forward path only. * **How a rollout/rollback can fail & impact.** Risks: incompatible CRD schema change, storage/CNI component upgrades requiring node reboots (on the Talos path), or a database-operator major bump. Impact is scoped to the component; running tenant workloads generally continue, though storage/CNI upgrades can transiently affect networking or volume attachment during node rolls. `[maintainers: confirm whether upgrades trigger Talos node reboots]` diff --git a/GOVERNANCE.md b/GOVERNANCE.md index 62e4361c6..db3419991 100644 --- a/GOVERNANCE.md +++ b/GOVERNANCE.md @@ -29,15 +29,13 @@ The Cozystack maintainers are maintainers of every sub-project by default (see [ **Project infrastructure** carries no shipped code: [website](https://github.com/cozystack/website), [community](https://github.com/cozystack/community) (design proposals and meeting notes), [external-apps-example](https://github.com/cozystack/external-apps-example) (the reference third-party application catalogues are built from), [ccp](https://github.com/cozystack/ccp), [.github](https://github.com/cozystack/.github) and [.project](https://github.com/cozystack/.project) (CNCF project metadata). -**Forks of upstream projects** are held for contributing changes back, or were held for that purpose and have since been archived. One is load-bearing and is called out below; the rest are not built into the distribution, which takes those components from their upstreams directly. +**Forks of upstream projects** are held for contributing changes back, or were held for that purpose and have since been archived. None is built into the distribution, which takes those components from their upstreams directly. -Three things about this organisation are worth stating plainly rather than leaving to be discovered. - -**One fork is compiled into the product.** [cozystack/apimachinery](https://github.com/cozystack/apimachinery) is a fork of `kubernetes/apimachinery` carrying a single 34-line patch to `pkg/runtime/scheme.go` on top of the released `v0.35.0` tree, applied through a `replace` directive in `go.mod`. The same fix is proposed upstream as [kubernetes/kubernetes#135537](https://github.com/kubernetes/kubernetes/pull/135537); the fork exists only until that merges, and is pinned to a branch tracking the upstream release rather than to the fork's own trunk. +Two things about this organisation are worth stating plainly rather than leaving to be discovered. **Four repositories are private**, and none of them contributes to the distribution: `security-scanner` (automated CVE monitoring, private because it holds pre-disclosure vulnerability state), `infrastructure` (the organisation's own CI infrastructure-as-code, private because it holds cloud credentials and account topology), one GitHub-created security-advisory workspace, and `talos-preboot-iso`, an archived prototype. Nothing an adopter installs is built from a repository they cannot read. -**Telemetry is received by a component adopters do not install.** [cozystack-telemetry-server](https://github.com/cozystack/cozystack-telemetry-server) runs as project infrastructure, but clusters report to it by default, so it is named here rather than omitted as out-of-scope. What is collected, why, and how to turn it off is documented on the [Telemetry](https://cozystack.io/docs/operations/configuration/telemetry/) page. +**Telemetry is received by a component adopters do not install.** [cozystack-telemetry-server](https://github.com/cozystack/cozystack-telemetry-server) runs as project infrastructure, but clusters report to it by default, so it is named here rather than omitted as out-of-scope. What is collected, why, and how to turn it off is documented on the [Telemetry](https://cozystack.io/docs/v1.6/operations/configuration/telemetry/) page. ## Third-party Dependencies @@ -86,11 +84,22 @@ Cozystack maintainers are expected to: and CNCF Slack workspaces, Telegram groups, and help out when possible. * Rapidly respond to any time-sensitive security release processes. * Attend Cozystack community meetings. +* Be familiar with the Linux Foundation guidance on [OFAC sanctions and open source](https://bestpractices.linuxfoundation.org/regulatory/ofac/) and raise any related questions privately with the other maintainers. If a maintainer is no longer interested in or cannot perform the duties listed above, they should move themselves to emeritus status. If necessary, this can also occur through the decision-making process outlined below. +### Welcoming new contributors + +A first contribution is often the moment someone decides whether to stay. When a new contributor opens an issue or a pull request: + +* Aim to respond within two working days, even if only to say who will review it and when. +* Point to the contributing guide and help with the mechanics. If the DCO check fails, explain how to fix it: `git commit --amend --signoff` for the last commit, or `git rebase --signoff main` for several. +* Before approving a CI run for an external contributor, read the diff and make sure it does not touch workflows, secrets or release tooling in a way that could run untrusted code with project credentials. This applies to every approval, not only the first one. +* Review against the same standards as any other change, and explain the reason behind each requested change. If the change is not going to be accepted, say so early and say why, rather than leaving it open. +* Suggest a good next step: a `good first issue`, a related bug, or a documentation gap. + ### Becoming a Maintainer Anyone can become a Cozystack maintainer. Maintainers should be extremely diff --git a/Makefile b/Makefile index 69381abdf..aac1d6617 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: manifests assets prepare-env prepare-env-container unit-tests helm-unit-tests bats-unit-tests bats-unit-files-check rd-presets-check migrations-target-check test test-controllers preflight +.PHONY: manifests assets prepare-env prepare-env-container unit-tests helm-unit-tests bats-unit-tests bats-unit-files-check bats-posix-compat-tests print-bats-unit-files print-bats-posix-compat-files print-bats-jobs rd-presets-check migrations-target-check test test-controllers test-controllers-envtest test-backport-batch preflight include hack/common-envs.mk @@ -13,18 +13,23 @@ build: build-deps make -C packages/apps/mariadb image make -C packages/apps/clickhouse image make -C packages/apps/kubernetes image + make -C packages/apps/vpn image make -C packages/system/cozystack-api image make -C packages/system/cozystack-controller image make -C packages/system/backup-controller image + make -C packages/system/observability-proxy image make -C packages/system/backupstrategy-controller image make -C packages/system/lineage-controller-webhook image + make -C packages/system/migration-controller image make -C packages/system/flux-shard-operator image + make -C packages/system/flux-plunger image make -C packages/system/cilium image make -C packages/system/linstor image make -C packages/system/linstor-gui image make -C packages/system/kubeovn image make -C packages/system/kubeovn-webhook image make -C packages/system/kubeovn-plunger image + make -C packages/system/kilo image make -C packages/system/dashboard image make -C packages/system/metallb image make -C packages/system/talos-log-collector image @@ -33,11 +38,16 @@ build: build-deps make -C packages/system/capi-providers-infraprovider image make -C packages/system/multus image make -C packages/system/bucket image + make -C packages/system/seaweedfs image make -C packages/system/objectstorage-controller image make -C packages/system/securitygroup-controller image make -C packages/system/grafana-operator image + make -C packages/system/monitoring image make -C packages/system/redis-operator image + make -C packages/system/harbor image + make -C packages/system/velero image make -C packages/system/opensearch-operator image + make -C packages/system/keycloak-operator image make -C packages/core/testing image make -C packages/core/talos image make -C packages/core/platform image @@ -110,7 +120,7 @@ test: make -C packages/core/testing apply make -C packages/core/testing e2e -unit-tests: helm-unit-tests bats-unit-tests go-unit-tests go-module-tests rd-presets-check test-check-readiness migrations-target-check +unit-tests: helm-unit-tests bats-unit-tests bats-posix-compat-tests go-unit-tests go-module-tests rd-presets-check test-check-readiness migrations-target-check helm-unit-tests: hack/helm-unit-tests.sh @@ -129,13 +139,14 @@ rd-presets-check: migrations-target-check: hack/check-migrations-target.sh -# Scoped go test over the cozystack-api surface that this repo owns. Kept -# narrow intentionally - running `go test ./...` pulls in generated code -# round-trip suites whose behavior depends on tool versions outside this -# repo's control (kubebuilder, openapi-gen, etc.) and is better exercised -# from their generator workflows. +# Go tests of the cozystack-api surface and of the standalone packages and +# commands listed here, whose tests need no cluster. Kept narrow +# intentionally - running `go test ./...` pulls in generated code round-trip +# suites whose behavior depends on tool versions outside this repo's control +# (kubebuilder, openapi-gen, etc.) and is better exercised from their +# generator workflows. go-unit-tests: - go test ./pkg/registry/... ./pkg/config/... ./pkg/cmd/server/... + go test ./pkg/registry/... ./pkg/config/... ./pkg/cmd/server/... ./pkg/lineage/... ./pkg/ovnstatus/... ./pkg/reservation/... ./cmd/cozypkg/... ./cmd/check-readiness/... # The nested Go modules (image sources and the published API types) are # outside ./... of the root module, so no other target reaches their tests. @@ -148,13 +159,34 @@ go-module-tests: done # Go tests for the controllers and supporting packages under ./internal. -# Excludes ./pkg/... and ./cmd/... — those are run separately by -# go-unit-tests above (pkg subset) and skipped (cmd) until their tests -# stabilise. CI schedules this target in the same four-slot make invocation as +# CI schedules this target in the same four-slot make invocation as # unit-tests; locally invoke it directly or chain the two targets. test-controllers: go test ./internal/... -count=1 +# Controller suites that need a real apiserver (build tag `envtest`): server-side +# apply ownership, apply preconditions and finalizer handling, which a fake client +# does not implement. setup-envtest fetches the kube-apiserver and etcd release +# pinned by ENVTEST_K8S_VERSION into _out/envtest; the HelmRelease CRD comes from +# the in-tree Flux manifests (envtest skips their non-CRD objects). CI runs it +# next to test-controllers. Only the packages listed below are compiled, so a +# package that gains an envtest suite has to be added here. +# +# setup-envtest itself is built into _out/envtest too, and binaries already there +# are used without asking the release index, so a warm _out/envtest (CI caches +# it) needs no network at all. +ENVTEST_K8S_VERSION ?= 1.35.0 +SETUP_ENVTEST_VERSION ?= v0.0.0-20260305142021-f9589b9f2b9d +ENVTEST_DIR = $(CURDIR)/_out/envtest +SETUP_ENVTEST = $(ENVTEST_DIR)/bin/setup-envtest-$(SETUP_ENVTEST_VERSION) +$(SETUP_ENVTEST): + GOBIN=$(ENVTEST_DIR)/bin go install sigs.k8s.io/controller-runtime/tools/setup-envtest@$(SETUP_ENVTEST_VERSION) + mv $(ENVTEST_DIR)/bin/setup-envtest $@ +test-controllers-envtest: $(SETUP_ENVTEST) + KUBEBUILDER_ASSETS="$$($(SETUP_ENVTEST) use $(ENVTEST_K8S_VERSION) --installed-only --bin-dir $(ENVTEST_DIR) --print path 2>/dev/null || $(SETUP_ENVTEST) use $(ENVTEST_K8S_VERSION) --bin-dir $(ENVTEST_DIR) --print path)" \ + HELMRELEASE_CRD_DIR=$(CURDIR)/internal/fluxinstall/manifests \ + go test -tags envtest -run '^TestEnvtest' ./internal/controller/fluxplunger/... -count=1 + # Black-box golden test for cmd/check-readiness. Builds the binary and runs it # against a mock kubectl (fixtures under test/check-readiness/testdata), # diffing stdout/stderr/exit against golden files. Regenerate goldens with: @@ -162,11 +194,16 @@ test-controllers: test-check-readiness: go test ./test/check-readiness/ -count=1 -# Discover every hack/*.bats file that is NOT an e2e test and run it -# through cozytest.sh. This glob is one level deep: live-cluster suites under -# hack/e2e-* or in subdirectories need an invocation in packages/core/testing. -# hack/bats-runner-coverage.bats reports files that neither runner selects. -# Park a suite with the .bats.disabled suffix to exclude it from the audit. +# The batch tool's suite drives real git repositories for minutes, so it is +# kept out of go-unit-tests in a target of its own. It is not a prerequisite +# of unit-tests: the checks job in pull-requests.yaml runs it only when the +# diff touches a path listed in cmd/backport-batch/test-inputs.txt. +test-backport-batch: + go test ./cmd/backport-batch/... -count=1 + +# Unit discovery is one level deep. Live-cluster files need an invocation in +# packages/core/testing; hack/bats-runner-coverage.bats checks that boundary. +# Bats supplies TAP and JUnit output; the live-cluster runner keeps its tracing. # # Caveat: $(wildcard ...) returns space-separated names, so a filename # containing a literal space would split into multiple tokens here. All @@ -174,36 +211,95 @@ test-check-readiness: # introduces whitespace-bearing filenames this recipe must be rewritten # (e.g. to use `find ... -print0 | xargs -0`). BATS_UNIT_FILES := $(filter-out hack/e2e-%.bats,$(wildcard hack/*.bats)) -BATS_UNIT_TARGETS := $(patsubst hack/%.bats,bats-unit-%,$(BATS_UNIT_FILES)) -# Quiet by default: cozytest.sh streams every test's xtrace live, which over -# this many suites buried the one failing assertion under ~240k lines of -# trace in CI. COZYTEST_TRACE=0 keeps the per-test start/end lines and still dumps -# the full trace of whichever test FAILS -- but not of one that is killed -# instead, a hang reaped by the job timeout among them, since the dump runs -# after the test returns. See the COZYTEST_TRACE comment in hack/cozytest.sh. -# Override to watch a run line by -# line: `COZYTEST_TRACE=1 make bats-unit-tests`, or invoke the runner -# directly (`hack/cozytest.sh hack/foo.bats [pattern]`), which stays verbose. -# The e2e call sites in packages/core/testing/Makefile are untouched and keep -# the live stream -- see the COZYTEST_TRACE comment in hack/cozytest.sh. -COZYTEST_TRACE ?= 0 +# The same list, one file per line, for hack/bats-strict-setup.bats. Every unit +# file has to load hack/test_helper.bash to get `set -u` back, and that audit is +# only worth anything if the set it walks is the set that actually runs -- so it +# asks here rather than keeping a second copy of the filter above. +print-bats-unit-files: + @printf '%s\n' $(BATS_UNIT_FILES) -bats-unit-tests: bats-unit-files-check $(BATS_UNIT_TARGETS) +# `bats -j` needs GNU parallel and exits non-zero rather than degrading when it +# is missing. moreutils also ships a command named parallel, so identify the GNU +# implementation from its version output before enabling concurrency. Resolve +# the probe once per make process; `?=` would keep the `$(shell ...)` recursive +# and rerun it at every expansion. +ifndef BATS_JOBS +BATS_JOBS := $(shell parallel --version 2>/dev/null | grep -q '^GNU parallel ' && nproc 2>/dev/null || echo 1) +endif + +print-bats-jobs: + @printf '%s\n' "$(BATS_JOBS)" + +# JUnit XML is preserved as a CI artifact for inspection. _out is gitignored. +BATS_REPORT_DIR ?= _out/test-reports bats-unit-files-check: @if [ -z "$(BATS_UNIT_FILES)" ]; then \ echo "ERROR: no hack/*.bats unit test files found"; \ exit 1; \ fi +bats-unit-tests: bats-unit-files-check + @command -v bats >/dev/null 2>&1 || { \ + echo "ERROR: bats not found. Install bats-core >= 1.5 — https://bats-core.readthedocs.io"; \ + exit 1; \ + } + @mkdir -p "$(BATS_REPORT_DIR)" + bats -j $(BATS_JOBS) --report-formatter junit -o "$(BATS_REPORT_DIR)" $(BATS_UNIT_FILES) -# Each file is its own prerequisite so `make -jN` can schedule them, and the -# trace switch main added for the serial loop rides along per target rather than -# being lost with it. -.PHONY: $(BATS_UNIT_TARGETS) -$(BATS_UNIT_TARGETS): bats-unit-%: hack/%.bats - @echo "--- running $< ---" - @COZYTEST_TRACE=$(COZYTEST_TRACE) hack/cozytest.sh "$<" +# Real Bats is authoritative. Unit files that source production code whose +# contract is POSIX sh retain a compatibility pass through cozytest.sh's +# /bin/sh translator. Discover literal .sh dependencies wherever they live, +# including hack/lib and package migration helpers, so a new non-Chainsaw +# helper test cannot run only under Bash. The explicit entries retain reviewed +# shell-facing tests, including files whose production path is held in a +# variable and therefore cannot be identified from the source line alone. +BATS_SOURCED_SH_FILES := $(shell grep -El '^[[:space:]]*(\.|source)[[:space:]]+.*\.sh' $(BATS_UNIT_FILES)) +BATS_POSIX_COMPAT_FILES := $(sort \ + $(BATS_SOURCED_SH_FILES) \ + hack/capture-dataplane.bats \ + hack/capture-previous-logs.bats \ + hack/cilium-leak-healer_test.bats \ + hack/container-lane-capacity_test.bats \ + hack/cozyreport-talos.bats \ + hack/cozyreport.bats \ + hack/cozystack-version-stamp.bats \ + hack/nightly-mirror_test.bats \ + hack/pod-label-census_test.bats \ + hack/promote-rewrite-tags_test.bats \ + hack/runner-identity.bats \ + hack/seaweedfs-naming-audit.bats \ +) + +# CI's /bin/sh is dash. Keep the interpreter overridable so contributors can +# run the same compatibility lane explicitly on hosts whose /bin/sh differs. +BATS_POSIX_SHELL ?= /bin/sh +COZYTEST_TRACE ?= 0 + +print-bats-posix-compat-files: + @printf '%s\n' $(BATS_POSIX_COMPAT_FILES) + +bats-posix-compat-tests: + @status=0; \ + for f in $(BATS_POSIX_COMPAT_FILES); do \ + echo "--- running POSIX compatibility: $$f ---"; \ + COZYTEST_TRACE=$(COZYTEST_TRACE) "$(BATS_POSIX_SHELL)" hack/cozytest.sh "$$f" || status=1; \ + done; \ + exit $$status + +# No cluster for the unit and controller lanes. A test that misses a stub, or +# whose stub a `timeout` or `bash -c` steps past, otherwise reaches whatever +# cluster the caller's kubeconfig points at. An empty KUBERNETES_SERVICE_HOST +# is needed beside KUBECONFIG: given an empty kubeconfig, client-go falls back +# to in-cluster credentials wherever that variable and a service-account token +# are present. +# Every prerequisite of unit-tests is listed so it is guarded when run on its +# own too; hack/unit-lane-no-cluster.bats fails when one is missing. +NO_CLUSTER_TARGETS := unit-tests test-controllers helm-unit-tests bats-unit-tests \ + bats-posix-compat-tests go-unit-tests go-module-tests rd-presets-check \ + test-check-readiness test-backport-batch migrations-target-check +$(NO_CLUSTER_TARGETS): export KUBECONFIG := /dev/null +$(NO_CLUSTER_TARGETS): export KUBERNETES_SERVICE_HOST := # Operator-facing host preflight check. Warns about a standalone # containerd.service or docker.service running alongside the embedded diff --git a/README.md b/README.md index 60513bd0c..e9d46b13e 100644 --- a/README.md +++ b/README.md @@ -24,22 +24,22 @@ Use Cozystack to build your own cloud or provide a cost-effective development en ## Use-Cases -* [**Using Cozystack to build a public cloud**](https://cozystack.io/docs/guides/use-cases/public-cloud/) +* [**Using Cozystack to build a public cloud**](https://cozystack.io/docs/v1.6/guides/use-cases/public-cloud/) You can use Cozystack as a backend for a public cloud -* [**Using Cozystack to build a private cloud**](https://cozystack.io/docs/guides/use-cases/private-cloud/) +* [**Using Cozystack to build a private cloud**](https://cozystack.io/docs/v1.6/guides/use-cases/private-cloud/) You can use Cozystack as a platform to build a private cloud powered by Infrastructure-as-Code approach -* [**Using Cozystack as a Kubernetes distribution**](https://cozystack.io/docs/guides/use-cases/kubernetes-distribution/) -You can use Cozystack as a Kubernetes distribution for Bare Metal +* [**Using Cozystack to build your own platform**](https://cozystack.io/docs/v1.6/guides/use-cases/kubernetes-distribution/) +You can install only the Cozystack components you need on an existing Kubernetes cluster ## Documentation The documentation is located on the [cozystack.io](https://cozystack.io) website. -Read the [Getting Started](https://cozystack.io/docs/getting-started/) section for a quick start. +Read the [Getting Started](https://cozystack.io/docs/v1.6/getting-started/) section for a quick start. -If you encounter any difficulties, start with the [troubleshooting guide](https://cozystack.io/docs/operations/troubleshooting/) and work your way through the process that we've outlined. +If you encounter any difficulties, start with the [troubleshooting guide](https://cozystack.io/docs/v1.6/operations/troubleshooting/) and work your way through the process that we've outlined. ## Versioning diff --git a/SECURITY.md b/SECURITY.md index 8db8eb742..552ed1950 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -8,7 +8,7 @@ Cozystack integrates and ships many upstream cloud native components. If you bel ## Supported Versions -The Cozystack project maintains three release lines at a time: **the latest stable minor and the two minors preceding it.** That is a rolling rule rather than a list of version numbers, so it does not go stale between releases — read it against the GitHub Releases page to see which concrete lines it currently names: +The Cozystack project supports two release lines at a time: **the two latest minor releases**, the latest stable minor and the one before it. When a new minor ships its first stable release it becomes the latest, and the older of the two drops out. That is a rolling rule rather than a list of version numbers, so it does not go stale between releases — read it against the GitHub Releases page to see which concrete lines it currently names: @@ -16,16 +16,16 @@ Note that the rule is keyed to release lines, not to the existence of a `release | Version line | Status | Notes | | --- | --- | --- | -| Latest stable minor | Supported | Current stable release line. Security fixes land here first, and patch releases are cut from it. | -| The two minors preceding the latest | Supported | Receive security and important maintenance fixes, backported from the current line. | +| Latest stable minor | Supported | Current stable release line, the first supported line a fix reaches. Patch releases are cut from it. | +| The minor before the latest | Supported | Receives the same security and maintenance fixes, backported once the latest line carries them. | | Older `1.x` minors | Limited support | Critical and upgrade-blocking fixes may be backported at maintainer discretion. Adopters are encouraged to move to a supported line. | | `v0.41.x` | End of life | The final pre-v1 line. It received patch releases through March 2026 during the v0 to v1 transition and no longer does; no further fixes are planned. | | Everything before `v0.41` | Not supported | Long superseded. Upgrade to a `1.x` line. | | `alpha`, `beta`, `rc` releases | Not supported | Pre-release builds are for testing and evaluation only. | -Being in a supported row does not mean a line receives every fix. **The project does not have a documented rule for choosing which supported lines a given fix is backported to** — that decision is taken per fix by the maintainers, weighing severity against the risk and effort of the backport. This is stated rather than dressed up as a policy because no such policy exists; adopters who need a specific fix on a specific line should ask. +Being in a supported row does not mean a line receives every fix. Fixes reach the supported lines through the backport batch, by the rules in [`docs/release/backports.md`](docs/release/backports.md): a fix merged into `main` with a `fix` or `security` title goes onto both lines, unless the policy keeps it for the next minor, a breaking change or a platform migration for instance, and a maintainer can override that for a single fix. Adopters who need a specific fix on a specific line should ask. -Reporting a vulnerability against a line with limited support or at end of life is still welcome. We will confirm whether the issue also affects a supported line and fix it there; whether the fix is additionally backported to the older line is a per-fix maintainer decision on the same basis. +Reporting a vulnerability against a line with limited support or at end of life is still welcome. We will confirm whether the issue also affects a supported line and fix it there; whether the fix is additionally backported to the older line is a per-fix maintainer decision. ## Reporting a Vulnerability diff --git a/api/apps/v1alpha1/bucket/types.go b/api/apps/v1alpha1/bucket/types.go index 96082a67b..8a4f331d5 100644 --- a/api/apps/v1alpha1/bucket/types.go +++ b/api/apps/v1alpha1/bucket/types.go @@ -22,6 +22,12 @@ type ConfigSpec struct { // Selects a specific BucketClass by storage pool name. // +kubebuilder:default:="" StoragePool string `json:"storagePool,omitempty"` + // Deploys the web UI (s3manager) with its Service and its Ingress or HTTPRoute at `.`. Set to `false` to run the bucket without them. + // +kubebuilder:default:=true + Ui bool `json:"ui"` + // Serves the bucket's objects to anyone without credentials at `//`. Anonymous callers can read objects but cannot list the bucket or write to it. + // +kubebuilder:default:=false + PublicRead bool `json:"publicRead"` // Users configuration map. // +kubebuilder:default:={} Users map[string]User `json:"users,omitempty"` diff --git a/api/apps/v1alpha1/foundationdb/types.go b/api/apps/v1alpha1/foundationdb/types.go index fa801afbf..20c7c937c 100644 --- a/api/apps/v1alpha1/foundationdb/types.go +++ b/api/apps/v1alpha1/foundationdb/types.go @@ -17,6 +17,9 @@ type Config struct { } type ConfigSpec struct { + // FoundationDB major.minor version to deploy + // +kubebuilder:default:="v7.3" + Version Version `json:"version"` // Cluster configuration. // +kubebuilder:default:={} Cluster Cluster `json:"cluster"` @@ -98,9 +101,6 @@ type Cluster struct { // Storage engine (ssd-2, ssd-redwood-v1, ssd-rocksdb-v1, memory). // +kubebuilder:default:="ssd-2" StorageEngine string `json:"storageEngine"` - // Version of FoundationDB to use. - // +kubebuilder:default:="7.3.63" - Version string `json:"version"` } type ClusterFaultDomain struct { @@ -161,3 +161,6 @@ type ImageType string // +kubebuilder:validation:Enum="t1.nano";"t1.micro";"t1.small";"t1.medium";"t1.large";"t1.xlarge";"t1.2xlarge";"t1.4xlarge";"c1.nano";"c1.micro";"c1.small";"c1.medium";"c1.large";"c1.xlarge";"c1.2xlarge";"c1.4xlarge";"s1.nano";"s1.micro";"s1.small";"s1.medium";"s1.large";"s1.xlarge";"s1.2xlarge";"s1.4xlarge";"u1.nano";"u1.micro";"u1.small";"u1.medium";"u1.large";"u1.xlarge";"u1.2xlarge";"u1.4xlarge";"m1.nano";"m1.micro";"m1.small";"m1.medium";"m1.large";"m1.xlarge";"m1.2xlarge";"m1.4xlarge";"nano";"micro";"small";"medium";"large";"xlarge";"2xlarge" type ResourcesPreset string + +// +kubebuilder:validation:Enum="v7.4";"v7.3" +type Version string diff --git a/api/apps/v1alpha1/harbor/types.go b/api/apps/v1alpha1/harbor/types.go index 99b89dbc1..d5638214e 100644 --- a/api/apps/v1alpha1/harbor/types.go +++ b/api/apps/v1alpha1/harbor/types.go @@ -20,6 +20,9 @@ type ConfigSpec struct { // Hostname for external access to Harbor (defaults to 'harbor' subdomain for the tenant host). // +kubebuilder:default:="" Host string `json:"host,omitempty"` + // IP addresses or CIDR ranges allowed to reach the Harbor web portal and API. `/v2/` and `/service/token`, which `docker login`, image pulls and pushes use, are not restricted by this list. For the portal and API it replaces the tenant ingress `whitelist` rather than narrowing it, and it is matched against the client address the ingress controller sees, which is a proxy or a forwarded header rather than the real client when something in front of the controller rewrites it. Empty allows every address. Requires Ingress publishing; rejected when the tenant publishes through Gateway API. + // +kubebuilder:default:={} + ManagementWhitelist []string `json:"managementWhitelist,omitempty"` // StorageClass used to store the data. // +kubebuilder:default:="" // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="storageClass is immutable" diff --git a/api/apps/v1alpha1/harbor/zz_generated.deepcopy.go b/api/apps/v1alpha1/harbor/zz_generated.deepcopy.go index 3e7338ad9..8ff615ac2 100644 --- a/api/apps/v1alpha1/harbor/zz_generated.deepcopy.go +++ b/api/apps/v1alpha1/harbor/zz_generated.deepcopy.go @@ -53,6 +53,11 @@ func (in *Config) DeepCopyObject() runtime.Object { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ConfigSpec) DeepCopyInto(out *ConfigSpec) { *out = *in + if in.ManagementWhitelist != nil { + in, out := &in.ManagementWhitelist, &out.ManagementWhitelist + *out = make([]string, len(*in)) + copy(*out, *in) + } in.Core.DeepCopyInto(&out.Core) in.Registry.DeepCopyInto(&out.Registry) in.Jobservice.DeepCopyInto(&out.Jobservice) diff --git a/api/apps/v1alpha1/kafka/types.go b/api/apps/v1alpha1/kafka/types.go index a69cece1b..16e4ce04e 100644 --- a/api/apps/v1alpha1/kafka/types.go +++ b/api/apps/v1alpha1/kafka/types.go @@ -24,8 +24,8 @@ type ConfigSpec struct { // TLS configuration. Strimzi manages the cluster PKI automatically (no cert-manager is involved for this chart): the operator auto-creates `-cluster-ca-cert` and `-clients-ca-cert` secrets, both exposed for client trust setup. The internal TLS listener on 9093 is always on; this toggle only controls the external listener on 9094. // +kubebuilder:default:={} Tls TLS `json:"tls"` - // Kafka version to deploy. Upgrade-only: once a cluster's KRaft metadata is at a given version, Strimzi refuses an in-place downgrade, so lowering this on a running cluster (e.g. v3.9 back to v3.8) leaves the Kafka CR stuck in a reconcile error. Pick the target version at creation and only ever raise it. - // +kubebuilder:default:="v3.9" + // Kafka version to deploy. Upgrade-only: once a cluster's KRaft metadata is at a given version, Strimzi refuses an in-place downgrade, so lowering this on a running cluster (e.g. v4.3 back to v4.2) leaves the Kafka CR stuck in a reconcile error. Pick the target version at creation and only ever raise it. + // +kubebuilder:default:="v4.3" Version Version `json:"version"` // Topics configuration. // +kubebuilder:default:={} @@ -36,7 +36,7 @@ type ConfigSpec struct { } type Kafka struct { - // Persistent Volume size for KRaft controller metadata (used during ZK-to-KRaft migration). + // Persistent Volume size for KRaft controller metadata. // +kubebuilder:default:="5Gi" ControllerStorageSize resource.Quantity `json:"controllerStorageSize,omitempty"` // Number of Kafka replicas. @@ -83,5 +83,5 @@ type Topic struct { // +kubebuilder:validation:Enum="t1.nano";"t1.micro";"t1.small";"t1.medium";"t1.large";"t1.xlarge";"t1.2xlarge";"t1.4xlarge";"c1.nano";"c1.micro";"c1.small";"c1.medium";"c1.large";"c1.xlarge";"c1.2xlarge";"c1.4xlarge";"s1.nano";"s1.micro";"s1.small";"s1.medium";"s1.large";"s1.xlarge";"s1.2xlarge";"s1.4xlarge";"u1.nano";"u1.micro";"u1.small";"u1.medium";"u1.large";"u1.xlarge";"u1.2xlarge";"u1.4xlarge";"m1.nano";"m1.micro";"m1.small";"m1.medium";"m1.large";"m1.xlarge";"m1.2xlarge";"m1.4xlarge";"nano";"micro";"small";"medium";"large";"xlarge";"2xlarge" type ResourcesPreset string -// +kubebuilder:validation:Enum="v3.9";"v3.8" +// +kubebuilder:validation:Enum="v4.3";"v4.2" type Version string diff --git a/api/apps/v1alpha1/kubernetes/types.go b/api/apps/v1alpha1/kubernetes/types.go index f43400808..8500d70ee 100644 --- a/api/apps/v1alpha1/kubernetes/types.go +++ b/api/apps/v1alpha1/kubernetes/types.go @@ -25,10 +25,10 @@ type ConfigSpec struct { // Kubernetes major.minor version to deploy // +kubebuilder:default:="v1.35" Version Version `json:"version"` - // External hostname for Kubernetes cluster. Defaults to `.` if empty. + // External hostname for Kubernetes cluster. Defaults to `kubernetes-.` if empty. // +kubebuilder:default:="" Host string `json:"host"` - // Which infrastructure provider backs this cluster's worker VMs. `kubevirt` runs them inside this cluster; `proxmox` runs them on an external Proxmox VE cluster through capmox. The control plane is Kamaji either way — this selects the infrastructure half only. Must match the `substrate` of every KubernetesNodes pool attached to this cluster: the pools reference this cluster's infrastructure object by kind, and a mismatch leaves their Machines unreconciled. Switching an existing cluster is not supported; create a new one. + // Which infrastructure provider backs this cluster's worker VMs. `kubevirt` runs them inside this cluster; `proxmox` runs them on an external Proxmox VE cluster through capmox. The control plane is Kamaji either way — this selects the infrastructure half only. Every KubernetesNodes pool of this cluster must set the same `substrate`: a pool set to the other one refuses to render once this cluster exists. Switching an existing cluster is not supported; create a new one. // +kubebuilder:default:="kubevirt" // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="substrate is immutable" Substrate string `json:"substrate"` @@ -41,13 +41,7 @@ type ConfigSpec struct { // Kubernetes control-plane configuration. // +kubebuilder:default:={} ControlPlane ControlPlane `json:"controlPlane"` - // Optional image overrides for air-gapped or rate-limited registries. - // +kubebuilder:default:={} - Images Images `json:"images"` - // Talos worker image configuration. - // +kubebuilder:default:={} - Talos Talos `json:"talos"` - // OIDC authentication and per-user RBAC for the tenant kube-apiserver. See docs/oidc-tenant.md for the operator guide. + // OIDC authentication and per-user RBAC for the tenant kube-apiserver. See https://cozystack.io/docs/v1.6/kubernetes/oidc-authentication/ for the operator guide. // +kubebuilder:default:={} Oidc OIDC `json:"oidc"` } @@ -56,7 +50,7 @@ type APIServer struct { // Admission plugins the tenant kube-apiserver enables, passed through to KamajiControlPlane `spec.admissionControllers`, which the control plane renders as `--enable-admission-plugins`. A non-empty list replaces the control plane's default set instead of adding to it. The kube-apiserver enables these plugins in addition to its own default ones, so leaving a plugin out does not turn it off; to turn one off, name it in `--disable-admission-plugins` in `controlPlane.apiServer.extraArgs` and keep it out of this list, since the apiserver refuses to start with a plugin in both, and the control plane's default set names several. Empty by default, which keeps that default set, taken from the TenantControlPlane CRD: CertificateApproval, CertificateSigning, CertificateSubjectRestriction, DefaultIngressClass, DefaultStorageClass, DefaultTolerationSeconds, LimitRanger, MutatingAdmissionWebhook, NamespaceLifecycle, PersistentVolumeClaimResize, Priority, ResourceQuota, RuntimeClass, ServiceAccount, StorageObjectInUseProtection, TaintNodesByCondition, ValidatingAdmissionWebhook. `NodeRestriction` is not in it. // +kubebuilder:default:={} AdmissionControllers []AdmissionController `json:"admissionControllers,omitempty"` - // Extra command-line flags appended to the tenant kube-apiserver, passed through to KamajiControlPlane `spec.apiServer.extraArgs`. For OIDC use `spec.oidc.mode` — this passthrough is the escape hatch for unrelated apiserver flags. The tenant control plane sets each of the following flags itself and drops an entry naming one before the apiserver sees it. The chart moves an `--enable-admission-plugins=` entry into `controlPlane.apiServer.admissionControllers` and a `--kubelet-preferred-address-types=` entry into `controlPlane.kubelet.preferredAddressTypes` while that field is empty, and refuses any other entry naming one of them: `--advertise-address`, `--client-ca-file`, `--enable-admission-plugins`, `--service-cluster-ip-range`, `--kubelet-client-certificate`, `--kubelet-client-key`, `--kubelet-preferred-address-types`, `--proxy-client-cert-file`, `--proxy-client-key-file`, `--requestheader-allowed-names`, `--requestheader-client-ca-file`, `--secure-port`, `--service-account-key-file`, `--service-account-signing-key-file`, `--tls-cert-file`, `--tls-private-key-file`, `--etcd-servers`, `--etcd-cafile`, `--etcd-certfile`, `--etcd-keyfile`, `--etcd-prefix`, `--etcd-compaction-interval`, `--egress-selector-config-file`. When `spec.oidc.mode` is not `None` the chart also renders OIDC flags here, reads what you have written on them, and refuses some combinations outright; `docs/oidc-tenant.md` carries which flags, which combinations, and why. Do NOT add legacy `--oidc-*` flags here when `spec.oidc.mode` is not `None`; the chart injects `--authentication-config` and the apiserver refuses to boot with both. Empty by default (no change to current behavior). + // Extra command-line flags appended to the tenant kube-apiserver, passed through to KamajiControlPlane `spec.apiServer.extraArgs`. For OIDC use `spec.oidc.mode` — this passthrough is the escape hatch for unrelated apiserver flags. The tenant control plane sets each of the following flags itself and drops an entry naming one before the apiserver sees it. The chart moves an `--enable-admission-plugins=` entry into `controlPlane.apiServer.admissionControllers` and a `--kubelet-preferred-address-types=` entry into `controlPlane.kubelet.preferredAddressTypes` while that field is empty, and refuses any other entry naming one of them: `--advertise-address`, `--client-ca-file`, `--enable-admission-plugins`, `--service-cluster-ip-range`, `--kubelet-client-certificate`, `--kubelet-client-key`, `--kubelet-preferred-address-types`, `--proxy-client-cert-file`, `--proxy-client-key-file`, `--requestheader-allowed-names`, `--requestheader-client-ca-file`, `--secure-port`, `--service-account-key-file`, `--service-account-signing-key-file`, `--tls-cert-file`, `--tls-private-key-file`, `--etcd-servers`, `--etcd-cafile`, `--etcd-certfile`, `--etcd-keyfile`, `--etcd-prefix`, `--etcd-compaction-interval`, `--egress-selector-config-file`. When `spec.oidc.mode` is not `None` the chart also renders OIDC flags here, reads what you have written on them, and refuses some combinations outright; the Aggregated API servers section of the Kubernetes OIDC guide on cozystack.io carries which flags, which combinations, and why. Do NOT add legacy `--oidc-*` flags here when `spec.oidc.mode` is not `None`; the chart injects `--authentication-config` and the apiserver refuses to boot with both. Empty by default. // +kubebuilder:default:={} ExtraArgs []string `json:"extraArgs,omitempty"` // Extra volume mounts added to the tenant kube-apiserver container, passed through to KamajiControlPlane `spec.apiServer.extraVolumeMounts`. Each `name` must reference a volume declared in `extraVolumes`; the chart-managed talos secret volumes cannot be mounted. Each item is a core/v1 VolumeMount. Empty by default. @@ -77,10 +71,10 @@ type Addons struct { // Cert-manager addon. // +kubebuilder:default:={} CertManager CertManagerAddon `json:"certManager"` - // Cilium CNI plugin. + // Cilium CNI plugin. Always installed as the tenant cluster's CNI; this section only overrides its Helm values. // +kubebuilder:default:={} Cilium CiliumAddon `json:"cilium"` - // CoreDNS addon. + // CoreDNS addon. Always installed as the tenant cluster's DNS; this section only overrides its Helm values. // +kubebuilder:default:={} Coredns CoreDNSAddon `json:"coredns"` // Gateway API addon. @@ -104,7 +98,7 @@ type Addons struct { // Velero backup/restore addon. // +kubebuilder:default:={} Velero VeleroAddon `json:"velero"` - // Vertical Pod Autoscaler. + // Vertical Pod Autoscaler. Installed and removed together with addons.monitoringAgents.enabled; this section only overrides its Helm values. // +kubebuilder:default:={} VerticalPodAutoscaler VerticalPodAutoscalerAddon `json:"verticalPodAutoscaler"` } @@ -184,18 +178,6 @@ type HAMiAddon struct { ValuesOverride k8sRuntime.RawExtension `json:"valuesOverride"` } -type Images struct { - // Image used by the bootstrap-token tenant Job (kubectl). Empty falls back to images/kubectl.tag. - // +kubebuilder:default:="" - Kubectl string `json:"kubectl,omitempty"` - // Image used by the talos-csr-signer sidecar in the Kamaji control plane. Empty falls back to images/talos-csr-signer.tag. - // +kubebuilder:default:="" - TalosCsrSigner string `json:"talosCsrSigner,omitempty"` - // Image used by the wait-for-kubeconfig init container. Empty falls back to images/busybox.tag. - // +kubebuilder:default:="" - WaitForKubeconfig string `json:"waitForKubeconfig,omitempty"` -} - type IngressNginxAddon struct { // Enable the controller (requires nodes labeled `ingress-nginx`). // +kubebuilder:default:=false @@ -288,14 +270,41 @@ type Proxmox struct { // Proxmox nodes capmox may place VMs on. Empty means every node in the Proxmox cluster. // +kubebuilder:default:={} AllowedNodes []string `json:"allowedNodes,omitempty"` + // Proxmox cloud-controller-manager settings. + // +kubebuilder:default:={} + Ccm ProxmoxCCM `json:"ccm,omitempty"` + // Proxmox CSI driver settings. + // +kubebuilder:default:={} + Csi ProxmoxCSI `json:"csi,omitempty"` // Nameservers written into each worker's network config. Required by the ProxmoxCluster schema. // +kubebuilder:default:={} DnsServers []string `json:"dnsServers,omitempty"` + // Skip verification of the Proxmox API server certificate in the CCM and the CSI controller, both of which run in the management cluster. Default false: the certificate is verified unless an operator turns that off. A stock Proxmox VE install serves a self-signed one, so set true for it, or install a certificate the management cluster trusts. + // +kubebuilder:default:=false + Insecure bool `json:"insecure,omitempty"` // Address pool for workers. capmox assigns static addresses and has no DHCP mode, so this is required rather than optional. // +kubebuilder:default:={} Ipv4Config ProxmoxIPv4 `json:"ipv4Config"` } +type ProxmoxCCM struct { + // Secret in THIS namespace holding the controller's Proxmox API credentials under the keys `url`, `token_id`, `token_secret` and `region`. May name the same Secret as `csi.credentialsSecretName`; it is a separate knob so the two can hold separate tokens, since this one only reads VM inventory while the driver attaches and detaches disks. + // +kubebuilder:default:="" + CredentialsSecretName string `json:"credentialsSecretName"` +} + +type ProxmoxCSI struct { + // Secret in THIS namespace holding the driver's Proxmox API credentials under the keys `url`, `token_id`, `token_secret` and `region`. The parent chart composes them into the controller's config file here, in the management cluster; nothing reaches the tenant, and no token is written into a rendered manifest. Distinct from the capmox credentials on purpose: the driver attaches and detaches disks, which is a different blast radius from creating VMs. + // +kubebuilder:default:="" + CredentialsSecretName string `json:"credentialsSecretName"` + // Install the driver. Without it a Proxmox-backed tenant has no way to provision PersistentVolumes at all. + // +kubebuilder:default:=true + Enabled bool `json:"enabled"` + // StorageClasses to create in the tenant. + // +kubebuilder:default:={} + StorageClasses []ProxmoxStorageClass `json:"storageClasses,omitempty"` +} + type ProxmoxIPv4 struct { // Ranges or CIDRs, e.g. `["10.0.0.120-10.0.0.170"]`. capmox turns these into an InClusterIPPool, so they must not overlap any DHCP range on the same L2 or two workers will answer to one address. // +kubebuilder:default:={} @@ -308,6 +317,19 @@ type ProxmoxIPv4 struct { Prefix int `json:"prefix"` } +type ProxmoxStorageClass struct { + // Filesystem the driver formats volumes with: ext4 or xfs. + Fstype string `json:"fstype,omitempty"` + // StorageClass name inside the tenant cluster. + Name string `json:"name"` + // Delete or Retain. + ReclaimPolicy string `json:"reclaimPolicy,omitempty"` + // Mark volumes as SSD-backed, which changes the discard/cache defaults Proxmox applies. + Ssd bool `json:"ssd,omitempty"` + // Proxmox storage id the volumes are created on (as it appears in `pvesm status`). + Storage string `json:"storage"` +} + type Resources struct { // CPU available. Cpu resource.Quantity `json:"cpu,omitempty"` @@ -324,24 +346,6 @@ type Scheduler struct { ResourcesPreset ResourcesPreset `json:"resourcesPreset"` } -type Talos struct { - // Base URL of the Talos Image Factory that serves the worker OS disk image (the `openstack-amd64.raw.xz` raw artifact streamed in by CDI over HTTP). Defaults to the public factory. Point at a self-hosted Image Factory, a caching mirror, or an internal HTTP file server for air-gapped, rate-limited, or flaky-egress environments. No trailing slash. - // +kubebuilder:default:="https://factory.talos.dev" - ImageFactoryURL string `json:"imageFactoryURL"` - // OCI repository prefix for the Talos installer image used by the in-guest `talos-reconcile` upgrade Job. Resolved as `/:`. Defaults to the public factory's installer path. Override for air-gapped or mirrored registries. No trailing slash. - // +kubebuilder:default:="factory.talos.dev/installer" - InstallerRepository string `json:"installerRepository"` - // Talos `machine.registries.mirrors` passthrough for worker nodes: a map of upstream registry host to `{ endpoints: [ ... ] }`. Empty by default, so workers pull container images (the Talos `kubelet` image included) directly from the upstream registry. Point a host such as `ghcr.io` at an in-cluster pull-through mirror for air-gapped, rate-limited, or flaky-egress environments so a worker's boot does not depend on live public egress. Talos still falls back to the upstream registry unless a host also sets `skipFallback: true`, so a mirror alone does not enforce air-gap. - // +kubebuilder:default:={} - RegistryMirrors k8sRuntime.RawExtension `json:"registryMirrors"` - // Talos image-factory schematic ID. Defaults to the cozystack-tested vanilla schematic. Operators using custom schematics (system extensions, kernel args) override here. - // +kubebuilder:default:="ce4c980550dd2ab1b17bbf2b08801c7eb59418eafe8f279833297925d67c7515" - SchematicID string `json:"schematicID"` - // Talos release used for worker OS image and installer. Must satisfy the chart's Talos<->Kubernetes support matrix against the chosen `version`. - // +kubebuilder:default:="v1.13.6" - Version string `json:"version"` -} - type VeleroAddon struct { // Enable Velero. // +kubebuilder:default:=false diff --git a/api/apps/v1alpha1/kubernetes/zz_generated.deepcopy.go b/api/apps/v1alpha1/kubernetes/zz_generated.deepcopy.go index d4eacfccf..69129b193 100644 --- a/api/apps/v1alpha1/kubernetes/zz_generated.deepcopy.go +++ b/api/apps/v1alpha1/kubernetes/zz_generated.deepcopy.go @@ -154,8 +154,6 @@ func (in *ConfigSpec) DeepCopyInto(out *ConfigSpec) { in.Proxmox.DeepCopyInto(&out.Proxmox) in.Addons.DeepCopyInto(&out.Addons) in.ControlPlane.DeepCopyInto(&out.ControlPlane) - out.Images = in.Images - in.Talos.DeepCopyInto(&out.Talos) in.Oidc.DeepCopyInto(&out.Oidc) } @@ -268,21 +266,6 @@ func (in *HAMiAddon) DeepCopy() *HAMiAddon { return out } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Images) DeepCopyInto(out *Images) { - *out = *in -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Images. -func (in *Images) DeepCopy() *Images { - if in == nil { - return nil - } - out := new(Images) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *IngressNginxAddon) DeepCopyInto(out *IngressNginxAddon) { *out = *in @@ -463,6 +446,8 @@ func (in *Proxmox) DeepCopyInto(out *Proxmox) { *out = make([]string, len(*in)) copy(*out, *in) } + out.Ccm = in.Ccm + in.Csi.DeepCopyInto(&out.Csi) if in.DnsServers != nil { in, out := &in.DnsServers, &out.DnsServers *out = make([]string, len(*in)) @@ -481,6 +466,41 @@ func (in *Proxmox) DeepCopy() *Proxmox { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ProxmoxCCM) DeepCopyInto(out *ProxmoxCCM) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProxmoxCCM. +func (in *ProxmoxCCM) DeepCopy() *ProxmoxCCM { + if in == nil { + return nil + } + out := new(ProxmoxCCM) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ProxmoxCSI) DeepCopyInto(out *ProxmoxCSI) { + *out = *in + if in.StorageClasses != nil { + in, out := &in.StorageClasses, &out.StorageClasses + *out = make([]ProxmoxStorageClass, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProxmoxCSI. +func (in *ProxmoxCSI) DeepCopy() *ProxmoxCSI { + if in == nil { + return nil + } + out := new(ProxmoxCSI) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ProxmoxIPv4) DeepCopyInto(out *ProxmoxIPv4) { *out = *in @@ -501,6 +521,21 @@ func (in *ProxmoxIPv4) DeepCopy() *ProxmoxIPv4 { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ProxmoxStorageClass) DeepCopyInto(out *ProxmoxStorageClass) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProxmoxStorageClass. +func (in *ProxmoxStorageClass) DeepCopy() *ProxmoxStorageClass { + if in == nil { + return nil + } + out := new(ProxmoxStorageClass) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Resources) DeepCopyInto(out *Resources) { *out = *in @@ -534,22 +569,6 @@ func (in *Scheduler) DeepCopy() *Scheduler { return out } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Talos) DeepCopyInto(out *Talos) { - *out = *in - in.RegistryMirrors.DeepCopyInto(&out.RegistryMirrors) -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Talos. -func (in *Talos) DeepCopy() *Talos { - if in == nil { - return nil - } - out := new(Talos) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *VeleroAddon) DeepCopyInto(out *VeleroAddon) { *out = *in diff --git a/api/apps/v1alpha1/kubernetesnodes/types.go b/api/apps/v1alpha1/kubernetesnodes/types.go index a0f12049d..a8bb94b1e 100644 --- a/api/apps/v1alpha1/kubernetesnodes/types.go +++ b/api/apps/v1alpha1/kubernetesnodes/types.go @@ -18,11 +18,11 @@ type Config struct { } type ConfigSpec struct { - // Name of the parent Kubernetes cluster (the `Kubernetes` CR) in the same namespace this node pool attaches to. Required. The pool's CAPI objects are wired to the parent cluster `kubernetes-`; the KubernetesNodes CR must be named `-`. The pool name (the part after `-`) must not collide with a nodeGroup still managed by the parent kubernetes chart (e.g. the default `md0`), or the render fails on ownership conflict. + // Name of the parent Kubernetes cluster (the `Kubernetes` CR) in the same namespace this node pool attaches to. Required. The pool's CAPI objects are wired to the parent cluster `kubernetes-`; the KubernetesNodes CR must be named `-`. The pool's objects are named `kubernetes--`; when a MachineDeployment of that name already exists and belongs to another Helm release, the render fails instead of taking it over. // +kubebuilder:default:="" // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="cluster is immutable" Cluster string `json:"cluster"` - // StorageClass for the worker node system disk. When empty, the cluster default applies. Worker VMs live-migrate, so their disks need ReadWriteMany — the RWX access mode is supplied by the chosen StorageClass's CDI StorageProfile — and linstor-csi rejects RWX volumes that are not on a DRBD-backed StorageClass, so prefer a replicated/DRBD class. On an `osImage.builtin` pool this field also decides whether the pool renders at all: CDI takes the storage-layer clone path only when the worker disk and the golden share a StorageClass, and falls back to a host-assisted copy over the pod network across classes, so the chart refuses a pool whose class differs from its golden's. Leaving it empty resolves to the cluster's default StorageClass, and the same comparison is made against that. On a `builtin` pool the resolved class is then written onto the worker disk rather than left for the cluster to fill in at bind time, so a pool that has already cloned keeps binding on the class its disks are on even after an admin moves the default annotation; on the HTTP path an empty class is still left to the cluster. + // StorageClass for the worker node system disk. When empty, CDI picks the class: the one annotated `storageclass.kubevirt.io/is-default-virt-class`, else the cluster default. Worker VMs live-migrate, so their disks need ReadWriteMany — the RWX access mode is supplied by the chosen StorageClass's CDI StorageProfile — and linstor-csi rejects RWX volumes that are not on a DRBD-backed StorageClass, so prefer a replicated/DRBD class. On an `osImage.builtin` pool this field also decides whether the pool renders at all: the chart refuses a pool whose class differs from its golden's, because across classes CDI either falls back to a host-assisted copy over the pod network (different CSI drivers or volume modes) or leaves a clone into the other class to the CSI driver. Leaving it empty makes the same comparison against the class CDI would pick. On a `builtin` pool the resolved class is then written onto the worker disk rather than left for the cluster to fill in at bind time, so a pool that has already cloned keeps binding on the class its disks are on even after an admin moves the default annotation; on the HTTP path an empty class is still left to the cluster. Has no effect on `substrate: proxmox`, where the worker disk is cloned from the VM template onto the template's storage or `proxmox.storage`. // +kubebuilder:default:="replicated" // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="storageClass is immutable" StorageClass string `json:"storageClass"` @@ -32,26 +32,32 @@ type ConfigSpec struct { // Maximum number of replicas in this pool. Used as the cluster-autoscaler ceiling. // +kubebuilder:default:=10 MaxReplicas int `json:"maxReplicas"` - // Virtual machine instance type. + // KubeVirt instance type that sizes each worker VM when `resources` is not set. Ignored when `resources.cpu` and `resources.memory` are both set, and therefore on `substrate: proxmox`, which requires them. // +kubebuilder:default:="u1.medium" InstanceType string `json:"instanceType"` - // System disk size for the worker VM. Carries the Talos OS image, kubelet state, containerd image cache, and any local-path PVCs. How the OS image reaches the disk follows this pool's `osImage`: the default and `osImage.factory` stream the Image Factory raw artifact in over HTTP, while `osImage.builtin` makes the disk a storage-layer CDI clone of a shared golden image, with no HTTP fetch. A `builtin` pool must keep diskSize at or above the golden's storage size (6Gi in the shipped worker image catalog), because a CDI clone target cannot be smaller than its source -- the chart rejects a smaller value at render time rather than letting the clone stall. Sizing a `builtin` pool also has to allow for transient headroom the finished disk does not show: CDI populates a larger target by cloning the golden at the source size and then growing it, so a worker being provisioned occupies a temporary clone PVC at the golden's size on top of this diskSize, and both are multiplied by the replica count of a replicated StorageClass. The golden itself is a separate one-time cost for the whole cluster, not a per-worker one. So the peak is the golden, plus `diskSize + golden storage` for each worker cloning at that moment. A pool whose storage backend cannot spare that peak does not fail: the clone waits for space, the VM never boots, and the reason is visible only in the storage layer's own events. + // System disk size for the worker VM. Carries the Talos OS image, kubelet state, containerd image cache, and any local-path PVCs. How the OS image reaches the disk follows this pool's `osImage`: the default and `osImage.factory` stream the Image Factory raw artifact in over HTTP, while `osImage.builtin` makes the disk a storage-layer CDI clone of a shared golden image, with no HTTP fetch. A `builtin` pool must keep diskSize at or above the golden's storage size (6Gi in the shipped worker image catalog), because a CDI clone target cannot be smaller than its source -- the chart rejects a smaller value at render time rather than letting the clone stall. Sizing a `builtin` pool also has to allow for transient headroom the finished disk does not show: CDI populates a larger target by cloning the golden at the source size and then growing it, so a worker being provisioned occupies a temporary clone PVC at the golden's size on top of this diskSize, and both are multiplied by the replica count of a replicated StorageClass. The golden itself is a separate one-time cost for the whole cluster, not a per-worker one. So the peak is the golden, plus `diskSize + golden storage` for each worker cloning at that moment. A pool whose storage backend cannot spare that peak does not fail: the clone waits for space, the VM never boots, and the reason is visible only in the storage layer's own events. Has no effect on `substrate: proxmox`, where the worker disk is a clone of the VM template's disk and keeps its size. // +kubebuilder:default:="20Gi" DiskSize resource.Quantity `json:"diskSize"` // List of node roles. Each role `r` labels nodes with `node-role.kubernetes.io/`. Use `[ingress-nginx]` for a pool that hosts the tenant ingress-nginx controller. // +kubebuilder:default:={} Roles []string `json:"roles,omitempty"` - // Explicit CPU and memory for each worker node, as an alternative to `instanceType` sizing. Optional: when omitted, the node is sized by `instanceType`. When both `cpu` and `memory` are set, they take precedence and `instanceType` is ignored (the instancetype is omitted from the VM, since KubeVirt cannot override an instancetype's CPU/memory). Set both `cpu` and `memory` together or neither; setting only one is rejected at render time. + // Explicit CPU and memory for each worker node, as an alternative to `instanceType` sizing. Optional: when omitted, the node is sized by `instanceType`. When both `cpu` and `memory` are set, they take precedence and `instanceType` is ignored (the instancetype is omitted from the VM, since KubeVirt cannot override an instancetype's CPU/memory). Set both `cpu` and `memory` together or neither; setting only one is rejected at render time. On the kubevirt substrate `cpu` is written into the VM as spelled and decoded as YAML, so a leading zero is read as octal, as in any Kubernetes manifest: `"010"` is eight cores, and the autoscaler capacity counts eight. The kubelet reservations still read the value as a decimal, so `"010"` reserves what `"10"` does. // +kubebuilder:default:={} Resources Resources `json:"resources,omitempty"` - // CPU limit for the worker VM's virt-launcher `compute` container, which is the ceiling the guest vCPU threads, the QEMU emulator thread and the IO threads share. Distinct from `resources.cpu`, which sizes the guest itself. Cannot be combined with `instanceType` sizing: KubeVirt refuses a VM that references an instancetype and also sets `domain.resources.limits.cpu`, so the chart rejects that combination at render time. Sizing the pool by `resources` (both `cpu` and `memory`) is what drops the instancetype from the VM, which is where the limit is usable. When unset, KubeVirt derives the limit from the guest vCPU count in any namespace carrying a ResourceQuota that limits CPU, so a worker sized at N vCPUs runs under a ceiling of N with the emulation overhead taken out of the same N. Setting a value declares the limit on the VM directly, which is both what lands it on the container and what stops KubeVirt deriving one. It moves the CPU request with it: KubeVirt copies a declared CPU limit into the CPU request when the VM declares no request of its own, so a pool that sets only this field asks the scheduler for its whole ceiling instead of the fraction of the vCPU count it asked for before, and a ceiling the nodes cannot spare leaves the workers Pending on `Insufficient cpu`. Pair it with `podCpuRequest` to move the ceiling without moving the request. Zero means no ceiling at all rather than the tightest one, since the kubelet turns a zero CPU limit into no CFS quota while the declared key still stops KubeVirt deriving one — but it is only accepted together with `podCpuRequest: 0`, because KubeVirt keeps deriving a request from the vCPU count when the VM declares none and a request above a declared limit of zero is rejected when the worker's Pod is created. A negative value is refused at render time. Changing it rolls the pool, because the worker VM template is named by a hash of its content. Keep in sync with the parent kubernetes chart. + // CPU limit for the worker VM's virt-launcher `compute` container, which is the ceiling the guest vCPU threads, the QEMU emulator thread and the IO threads share. Distinct from `resources.cpu`, which sizes the guest itself. Cannot be combined with `instanceType` sizing: KubeVirt refuses a VM that references an instancetype and also sets `domain.resources.limits.cpu`, so the chart rejects that combination at render time. Sizing the pool by `resources` (both `cpu` and `memory`) is what drops the instancetype from the VM, which is where the limit is usable. When unset, KubeVirt derives the limit from the guest vCPU count in any namespace carrying a ResourceQuota that limits CPU, so a worker sized at N vCPUs runs under a ceiling of N with the emulation overhead taken out of the same N. Setting a value declares the limit on the VM directly, which is both what lands it on the container and what stops KubeVirt deriving one. It moves the CPU request with it: KubeVirt copies a declared CPU limit into the CPU request when the VM declares no request of its own, so a pool that sets only this field asks the scheduler for its whole ceiling instead of the fraction of the vCPU count it asked for before, and a ceiling the nodes cannot spare leaves the workers Pending on `Insufficient cpu`. Pair it with `podCpuRequest` to move the ceiling without moving the request. Zero means no ceiling at all rather than the tightest one, since the kubelet turns a zero CPU limit into no CFS quota while the declared key still stops KubeVirt deriving one — but it is only accepted together with `podCpuRequest: 0`, because KubeVirt keeps deriving a request from the vCPU count when the VM declares none and a request above a declared limit of zero is rejected when the worker's Pod is created. A negative value is refused at render time. Changing it rolls the pool, because the worker VM template is named by a hash of its content. PodCpuLimit resource.Quantity `json:"podCpuLimit,omitempty"` - // CPU request for the worker VM's virt-launcher `compute` container, which is what the scheduler reserves for a worker on its host and what weights it against neighbours on a contended one. Distinct from `resources.cpu`, which sizes the guest itself. It exists to be paired with `podCpuLimit`: KubeVirt copies a declared CPU limit into the request when the VM declares no request, so raising the ceiling alone raises what every worker in the pool asks the scheduler for, and this field is what holds the request still while the ceiling moves. Cannot be combined with `instanceType` sizing, for the same reason as `podCpuLimit`: KubeVirt refuses a VM that references an instancetype and also sets `domain.resources.requests.cpu`, so the chart rejects that combination at render time, as it does a value above `podCpuLimit`. Usable without a limit, where it only changes the scheduler's weighting: KubeVirt still derives the ceiling from the guest vCPU count in any namespace carrying a ResourceQuota that limits CPU, so keep the request at or below that count. A request above that derived ceiling is refused only when the worker's Pod is created, and deliberately not at render time: the ceiling exists only where such a ResourceQuota does, so refusing here would take away a configuration that works in a namespace without one. Zero is accepted on its own and reserves nothing, but zero beside a `podCpuLimit` is refused, because KubeVirt cannot tell an explicit zero request from an absent one and replaces both with the limit — which is the outcome this field exists to avoid, arrived at silently. A negative value is refused as well. When unset, KubeVirt computes the request from the guest vCPU count and the cluster CPU allocation ratio. Changing it rolls the pool, because the worker VM template is named by a hash of its content. Keep in sync with the parent kubernetes chart. + // CPU request for the worker VM's virt-launcher `compute` container, which is what the scheduler reserves for a worker on its host and what weights it against neighbours on a contended one. Distinct from `resources.cpu`, which sizes the guest itself. It exists to be paired with `podCpuLimit`: KubeVirt copies a declared CPU limit into the request when the VM declares no request, so raising the ceiling alone raises what every worker in the pool asks the scheduler for, and this field is what holds the request still while the ceiling moves. Cannot be combined with `instanceType` sizing, for the same reason as `podCpuLimit`: KubeVirt refuses a VM that references an instancetype and also sets `domain.resources.requests.cpu`, so the chart rejects that combination at render time, as it does a value above `podCpuLimit`. Usable without a limit, where it only changes the scheduler's weighting: KubeVirt still derives the ceiling from the guest vCPU count in any namespace carrying a ResourceQuota that limits CPU, so keep the request at or below that count. A request above that derived ceiling is refused only when the worker's Pod is created, and deliberately not at render time: the ceiling exists only where such a ResourceQuota does, so refusing here would take away a configuration that works in a namespace without one. Zero is accepted on its own and reserves nothing, but zero beside a `podCpuLimit` is refused, because KubeVirt cannot tell an explicit zero request from an absent one and replaces both with the limit — which is the outcome this field exists to avoid, arrived at silently. A negative value is refused as well. When unset, KubeVirt computes the request from the guest vCPU count and the cluster CPU allocation ratio. Changing it rolls the pool, because the worker VM template is named by a hash of its content. PodCpuRequest resource.Quantity `json:"podCpuRequest,omitempty"` // List of GPUs to attach (NVIDIA driver requires at least 4 GiB RAM). // +kubebuilder:default:={} Gpus []GPU `json:"gpus,omitempty"` - // Kubelet resource reservations for this pool. + // Workers a rollout (instance type, image or version change) may remove before their replacement is up. Unset, it is 0, so each replacement joins before an old worker is drained, and 1 on a pool with `gpus`, whose replacement may need the very GPU the old worker holds. With 0, a rollout needs room for one extra VM: a pool short of quota or capacity for it stalls, with the new Machine Pending, until room is made or `maxUnavailable` is set to 1. Set 1 on a Proxmox pool whose template passes a GPU through: the chart cannot see that GPU, and with 0 the rollout would wait for it forever. + // +kubebuilder:validation:Minimum=0 + // +kubebuilder:validation:Maximum=2.147483647e+09 + MaxUnavailable *int `json:"maxUnavailable,omitempty"` + // Kernel modules loaded on every worker in this pool, emitted as Talos `machine.kernel.modules`. A Talos system extension installs a module but does not load it, so an extension-provided driver needs its modules declared here. Leave unset to let the chart decide: a pool holding at least one `nvidia.com/*` GPU gets `nvidia` (with `NVreg_NvLinkDisable=1`, which the gpu-operator driver container applies on non-Talos workers; on Talos that container has to be turned off or it clashes with the system extension, and nothing then mounts the ConfigMap carrying the parameter), `nvidia_uvm`, `nvidia_drm`, `nvidia_modeset` (that order — Talos loads the list in sequence and the last three depend on the first), and any other pool gets nothing. Set a non-empty list to replace the chart's choice entirely, or `[]` to opt out and emit no modules even on a GPU pool. The field carries no default, and unset is not the same value as `[]`: a generated parameter table that shows `[]` in its Default column is printing what it prints for any array with no default, not the effective value — leaving the field out selects the automatic set, writing `[]` disables it. The module still has to be in the image, and which extensions the image carries is the pool's schematic: a GPU pool points `osImage.factory.schematicID` (or `osImage.builtin.schematicID`) at a schematic with the NVIDIA extensions, and on Blackwell (GB202) that must be the open-kernel-modules extension. The automatic set keys on the `nvidia.com/` resource prefix alone and nothing cross-checks it against that schematic; on Talos v1.13 a declared module the image does not ship leaves its controller retrying rather than failing the boot, so the symptom is a missing driver, not a dead node. This value is part of the worker machine config, whose content hash names the `TalosConfigTemplate`, so changing it rolls every existing worker in the pool rather than only affecting nodes created later. + KernelModules []KernelModule `json:"kernelModules,omitempty"` + // Kubelet resource reservations for this pool. An empty reservation is computed from the worker's size: `resources` when set, otherwise the `instanceType`. // +kubebuilder:default:={} Kubelet Kubelet `json:"kubelet,omitempty"` // Stream each worker VM's guest serial console into a `guest-console-log` container beside virt-launcher, readable with `kubectl logs`. The only view of a worker that stalls during boot before Talos apid answers, when neither a Node nor a certificate request exists to diagnose from. Two costs the field name does not show. Changing the value rolls the pool, because it is part of the worker VM template whose name is a hash of its content -- including the stuck VM whose console was wanted, so it buys visibility into the next boot rather than the current one. And it overrides the platform's cluster-wide `disableSerialConsoleLog`, set because that container has been seen holding virt-launcher in `PodInitializing` (kubevirt/kubevirt#15989), which would take the pool down rather than explain it -- so check that virt-launcher Pods reach Running after enabling it. @@ -60,25 +66,25 @@ type ConfigSpec struct { // Maximum number of unhealthy nodes tolerated in this pool before remediation is paused. The MachineHealthCheck admission webhook accepts either a bare integer ("0", "1", ...) or a percentage ("0%", "50%"); bare numeric strings are rejected, so the safer default is a percentage. Drop to "0%" once the pool is stable. Watch how a percentage behaves in a small group: the MachineHealthCheck controller scales it against the number of machines the check covers and rounds down, then remediates only while the unhealthy count is at or below that result. At "50%" a group of one therefore never remediates, because half of one rounds down to zero, and a group of two remediates one unhealthy machine but not two. // +kubebuilder:default:="50%" MaxUnhealthy string `json:"maxUnhealthy"` - // Maximum time a Machine is allowed to spend reaching the Ready condition before it is remediated. Raise for slow first boots (Talos image fetch from factory.talos.dev or a busy storage class on the kubevirt-csi PVC populator). The MachineHealthCheck measures it from the later of the Machine's creation and its InfrastructureReady transition, so the clock restarts when the infrastructure reports ready: a worker gets this long for the disk image import and the VM to come up, and then this long again for the guest to boot and its kubelet to register with the tenant apiserver. Either leg stretches on a host under load, and a Machine remediated here is deleted before it ever joins, so its replacement starts the same sequence from the beginning. + // Maximum time a Machine is allowed to spend reaching the Ready condition before it is remediated. Raise for slow first boots (the Talos image import from the Image Factory, or a storage class slow to provision or clone the worker disk). The MachineHealthCheck measures it from the later of the Machine's creation and its InfrastructureReady transition, so the clock restarts when the infrastructure reports ready: a worker gets this long for the disk image import and the VM to come up, and then this long again for the guest to boot and its kubelet to register with the tenant apiserver. Either leg stretches on a host under load, and a Machine remediated here is deleted before it ever joins, so its replacement starts the same sequence from the beginning. // +kubebuilder:default:="20m" NodeStartupTimeout string `json:"nodeStartupTimeout"` - // How long a worker Node may report `Ready=Unknown` before the MachineHealthCheck remediates the Machine, which for a KubeVirt worker means deleting the VM. `Ready=Unknown` is what the node lifecycle controller writes once it stops hearing from a kubelet, on a grace period of its own, so the wall clock from a guest going quiet to a deleted worker is this value plus that grace period. A guest starved of CPU stops answering long before it is dead, so a value of a few tens of seconds deletes workers that would have come back on their own. Validated at render time like maxNodeProvisionTime: the CAPI webhook does not check these timeouts, and a zero or negative value would remediate the moment the condition flips. Keep in sync with the parent kubernetes chart. + // How long a worker Node may report `Ready=Unknown` before the MachineHealthCheck remediates the Machine, which for a KubeVirt worker means deleting the VM. `Ready=Unknown` is what the node lifecycle controller writes once it stops hearing from a kubelet, on a grace period of its own, so the wall clock from a guest going quiet to a deleted worker is this value plus that grace period. A guest starved of CPU stops answering long before it is dead, so a value of a few tens of seconds deletes workers that would have come back on their own. Validated at render time like maxNodeProvisionTime: the CAPI webhook does not check these timeouts, and a zero or negative value would remediate the moment the condition flips. // +kubebuilder:default:="5m" ReadyUnknownTimeout string `json:"readyUnknownTimeout"` - // How long a worker Node may report `Ready=False` before the MachineHealthCheck remediates the Machine. A Node that has registered but has no working CNI yet reports `Ready=False`, so this value is the whole budget a first boot gets for the CNI rollout to reach that node, and a worker deleted mid-rollout takes the rollout with it while its replacement starts over. Raising it delays replacing a worker that is genuinely dead, but not rescheduling its workload: Pods leave an unreachable Node on the node lifecycle controller's taint-based eviction and the toleration that carries, not on this timer. Validated at render time like maxNodeProvisionTime: the CAPI webhook does not check these timeouts, and a zero or negative value would remediate the moment the condition flips. Keep in sync with the parent kubernetes chart. + // How long a worker Node may report `Ready=False` before the MachineHealthCheck remediates the Machine. A Node that has registered but has no working CNI yet reports `Ready=False`, so this value is the whole budget a first boot gets for the CNI rollout to reach that node, and a worker deleted mid-rollout takes the rollout with it while its replacement starts over. Raising it delays replacing a worker that is genuinely dead, but not rescheduling its workload: Pods leave an unreachable Node on the node lifecycle controller's taint-based eviction and the toleration that carries, not on this timer. Validated at render time like maxNodeProvisionTime: the CAPI webhook does not check these timeouts, and a zero or negative value would remediate the moment the condition flips. // +kubebuilder:default:="10m" ReadyFalseTimeout string `json:"readyFalseTimeout"` - // How long the cluster-autoscaler waits for a newly created worker to register as a Node before it treats that machine as long-unregistered. Rendered onto this pool's MachineDeployment as the `cluster.x-k8s.io/autoscaling-options-maxnodeprovisiontime` annotation, which overrides the autoscaler's built-in default for this pool only. Two things change when the timer fires, and both make a slow join worse rather than better: the machine stops counting towards the pool's upcoming capacity, so the autoscaler asks for a replacement for capacity that is already on its way, and the machine becomes eligible for removal. Size it above the slowest join a healthy worker can take, counting the Talos image import, the guest boot and the CNI rollout. Accepted as a whole number of seconds, minutes or hours ("30m", "1h30m"), which is narrower than Go's duration syntax on purpose: the autoscaler ignores a value it cannot parse and falls back to its own default without failing, and the narrower shape cannot express a value that overflows the parser or a fraction it rounds to zero. The canonical form a duration serializes back to ("20m0s", "1h0m0s") is accepted. Keep in sync with the parent kubernetes chart. + // How long the cluster-autoscaler waits for a newly created worker to register as a Node before it treats that machine as long-unregistered. Rendered onto this pool's MachineDeployment as the `cluster.x-k8s.io/autoscaling-options-maxnodeprovisiontime` annotation, which overrides the autoscaler's built-in default for this pool only. Two things change when the timer fires, and both make a slow join worse rather than better: the machine stops counting towards the pool's upcoming capacity, so the autoscaler asks for a replacement for capacity that is already on its way, and the machine becomes eligible for removal. Size it above the slowest join a healthy worker can take, counting the Talos image import, the guest boot and the CNI rollout. Accepted as a whole number of seconds, minutes or hours ("30m", "1h30m"), which is narrower than Go's duration syntax on purpose: the autoscaler ignores a value it cannot parse and falls back to its own default without failing, and the narrower shape cannot express a value that overflows the parser or a fraction it rounds to zero. The canonical form a duration serializes back to ("20m0s", "1h0m0s") is accepted. // +kubebuilder:default:="30m" MaxNodeProvisionTime string `json:"maxNodeProvisionTime"` - // Kubernetes major.minor version the pool joins. Must not be ahead of the parent cluster's minor (workers may not lead the apiserver); it may lag behind during a rolling upgrade -- bump the parent Kubernetes CR first, then each pool -- and must satisfy the Talos<->Kubernetes support matrix against `talos.version`. + // Kubernetes major.minor version the pool joins. Must not be ahead of the parent cluster's minor (workers may not lead the apiserver); it may lag behind during a rolling upgrade -- bump the parent Kubernetes CR first, then each pool. The render fails when it is ahead. Its pairing with the Talos release the pool resolves (`talos.version`, or the `osImage` override) is checked against the chart's Talos<->Kubernetes support matrix: for a Talos minor the matrix lists, a Kubernetes minor outside that minor's list is refused; a Talos minor the matrix does not list is not checked. // +kubebuilder:default:="v1.35" Version Version `json:"version"` // Worker OS image source for this pool. Default (omitted): import over HTTP from the `talos.*` Image Factory. Set `osImage.builtin` to clone a golden from the opt-in worker image catalog instead. Editing this on an existing pool re-images that pool. // +kubebuilder:default:={} OsImage WorkerImage `json:"osImage,omitempty"` - // Talos worker image configuration. Keep in sync with the parent cluster's `talos`. + // Talos worker image configuration for this pool. // +kubebuilder:default:={} Talos Talos `json:"talos"` // Which infrastructure provider backs this pool's worker VMs. `kubevirt` runs them inside this cluster on KubeVirt, sized by `instanceType` and booted from a Talos disk image CDI streams from the image factory. `proxmox` runs them on an external Proxmox VE cluster through capmox, sized by `resources`, and cloned from a Talos VM template that already exists on the hypervisor. The two substrates take different Talos platform images and different sizing inputs, so switching an existing pool is refused: the chart reads the live MachineDeployment's template kind and fails the render rather than rolling every worker to the other hypervisor and deleting the template the draining MachineSet still references. Create a new pool on the other substrate and scale this one down. @@ -88,9 +94,6 @@ type ConfigSpec struct { // Proxmox substrate settings. // +kubebuilder:default:={} Proxmox Proxmox `json:"proxmox"` - // Optional image overrides for air-gapped or rate-limited registries. - // +kubebuilder:default:={} - Images Images `json:"images"` } type GPU struct { @@ -98,10 +101,11 @@ type GPU struct { Name string `json:"name"` } -type Images struct { - // Image used by the talos-reconcile and pre-delete unpin Jobs (kubectl). Empty falls back to images/kubectl.tag. - // +kubebuilder:default:="" - Kubectl string `json:"kubectl,omitempty"` +type KernelModule struct { + // Module name as `modprobe` takes it, e.g. `nvidia_uvm`. + Name string `json:"name"` + // Module parameters, each as a bare `key=value` string. + Parameters []string `json:"parameters,omitempty"` } type Kubelet struct { @@ -111,13 +115,13 @@ type Kubelet struct { // Soft eviction threshold for memory (absolute like 1Gi or percentage like 10%). // +kubebuilder:default:="10%" EvictionSoftMemory string `json:"evictionSoftMemory,omitempty"` - // CPU reserved for kubelet and container runtime. Auto-computed from instanceType if empty. + // CPU reserved for kubelet and container runtime. When empty, 5% of the worker's CPU, clamped to 50m..500m. KubeReservedCpu string `json:"kubeReservedCpu,omitempty"` - // Memory reserved for kubelet and container runtime. Auto-computed from instanceType if empty. + // Memory reserved for kubelet and container runtime. When empty, 5% of the worker's memory, clamped to 256Mi..1Gi. KubeReservedMemory string `json:"kubeReservedMemory,omitempty"` - // CPU reserved for host OS. Auto-computed from instanceType if empty. + // CPU reserved for host OS. When empty, 5% of the worker's CPU, clamped to 50m..500m. SystemReservedCpu string `json:"systemReservedCpu,omitempty"` - // Memory reserved for host OS. Auto-computed from instanceType if empty. + // Memory reserved for host OS. When empty, 5% of the worker's memory, clamped to 256Mi..1Gi. SystemReservedMemory string `json:"systemReservedMemory,omitempty"` } @@ -131,10 +135,13 @@ type Proxmox struct { // NIC configuration. // +kubebuilder:default:={} Network ProxmoxNetwork `json:"network"` + // Proxmox resource pool the worker VMs are added to. Set the same pool on every node pool of a tenant cluster and grant the tenant's tokens their privileges on `/pool/`: that is the one ACL path that follows every VM capmox creates, replacements included. The pool must exist on the hypervisor; capmox does not create it. Empty adds the workers to no pool. + // +kubebuilder:default:="" + Pool string `json:"pool,omitempty"` // Proxmox storage for the cloned disk; needs `full: true`. A target storage is a full-clone parameter — a linked clone always lives on the template's storage, and Proxmox refuses the pair — so the render refuses it too. Empty keeps the template's storage. // +kubebuilder:default:="" Storage string `json:"storage,omitempty"` - // Tags identifying the Talos VM template to clone. capmox matches a template when its tag set is EQUAL to this list, not when it contains it, so every tag on the template must be listed here — a missing one yields `found 0 VM templates with tags ...` while the tags are plainly present. Required when `substrate` is `proxmox`. + // Tags identifying the Talos VM template to clone. capmox matches a template when its tag set is EQUAL to this list, not when it contains it, so every tag on the template must be listed here — a missing one yields `found 0 VM templates with tags ...` while the tags are plainly present. The template has to carry this pool's `talos.schematicID` at `talos.version` in the nocloud flavour, with the Proxmox guest agent enabled for the `qemu-guest-agent` extension of the default schematic; `hack/proxmox-talos-template.sh` builds it from these values and prints the tags to list here. Do not build it from the platform release's `nocloud-amd64.raw.xz`: that is the bare-metal node image, whose `zfs` extension keeps a VM from finishing its boot sequence and reboots it at the Talos boot timeout. Required when `substrate` is `proxmox`. // +kubebuilder:default:={} TemplateTags []string `json:"templateTags,omitempty"` } @@ -150,26 +157,32 @@ type ProxmoxNetwork struct { } type Resources struct { - // CPU available. + // Number of vCPU cores for each worker VM, as a whole number such as `2`. On the `kubevirt` substrate the value becomes the VM's integer `domain.cpu.cores`, so millicore, fractional and negative quantities, and counts above 4294967295, are rejected at render time; an unquoted `0` is treated as unset. On the `proxmox` substrate a millicore or fractional quantity is rounded up to whole cores. Cpu resource.Quantity `json:"cpu,omitempty"` // Memory (RAM) available. Memory resource.Quantity `json:"memory,omitempty"` } type Talos struct { - // Default base URL of the Talos Image Factory that serves the worker OS disk image (the `openstack-amd64.raw.xz` raw artifact streamed in by CDI over HTTP). Applies only when this pool imports over HTTP — the default and `osImage.factory`, which overrides it via `osImage.factory.imageFactoryURL`. A pool on `osImage.builtin` clones a golden image from the worker image catalog and does not use this field at all. Defaults to the public factory. Point at a self-hosted Image Factory, a caching mirror, or an internal HTTP file server for air-gapped, rate-limited, or flaky-egress environments. No trailing slash. It is interpolated into the worker DataVolume source URL, so on those HTTP paths it must be a plain `http(s)` URL and the render refuses anything else; a pool on `osImage.builtin` builds no such URL and is not held to it, so blanking this field there is legal. + // Complete PEM certificate block(s) CDI must trust when importing this pool's worker OS disk image over HTTPS — the no-osImage default and `osImage.factory` path. Empty by default, so the importer uses only its system trust store, which is what the public factory needs. Set this when the factory in use (`imageFactoryURL` or `osImage.factory.imageFactoryURL`) is a self-hosted factory or mirror served by an internal CA, which the importer otherwise rejects with `x509: certificate signed by unknown authority`. The chart renders it into a ConfigMap in the release namespace — CDI requires certConfigMap to sit alongside the DataVolume — and references that from the worker DataVolume's `source.http.certConfigMap`; CDI appends it to the system pool rather than replacing it, so a publicly-trusted endpoint verifies either way. A pool on `osImage.builtin` clones a golden image and builds no HTTP source, so this field has no effect there. On `substrate: proxmox` it has no effect on the workers either: the ConfigMap is still rendered, but nothing references it. + // +kubebuilder:default:="" + ImageFactoryCA string `json:"imageFactoryCA,omitempty"` + // Default base URL of the Talos Image Factory that serves the worker OS disk image (the `openstack-amd64.raw.xz` raw artifact streamed in by CDI over HTTP). Applies only when this pool imports over HTTP — the default and `osImage.factory`, which overrides it via `osImage.factory.imageFactoryURL`. A pool on `osImage.builtin` clones a golden image from the worker image catalog and does not use this field at all. Defaults to the public factory. Point at a self-hosted Image Factory, a caching mirror, or an internal HTTP file server for air-gapped, rate-limited, or flaky-egress environments. No trailing slash. It is interpolated into the worker DataVolume source URL, so on those HTTP paths it must be a plain `http(s)` URL and the render refuses anything else; a pool on `osImage.builtin` builds no such URL and is not held to it, so blanking this field there is legal. On `substrate: proxmox` the workers clone a VM template that already carries the OS, so this field has no effect there beyond that format check. // +kubebuilder:default:="https://factory.talos.dev" ImageFactoryURL string `json:"imageFactoryURL"` - // OCI repository prefix for the Talos installer image used by the in-guest `talos-reconcile` upgrade Job. Resolved as `/:` against whatever this pool's `osImage` pins, falling back to `talos.schematicID` and `talos.version` — so the installer matches the OS the pool actually booted. The prefix itself has no `osImage.*` override, so an air-gapped pool needs it pointed at a reachable registry as well. Defaults to the public factory's installer path. Override for air-gapped or mirrored registries. No trailing slash. + // OCI repository prefix for the Talos installer image, written into the worker machine config as `machine.install.image`. Resolved as `/:` against whatever this pool's `osImage` pins, falling back to `talos.schematicID` and `talos.version` — so the installer matches the OS the pool actually booted. The prefix itself has no `osImage.*` override, so an air-gapped pool needs it pointed at a reachable registry as well. Defaults to the public factory's installer path. Override for air-gapped or mirrored registries. No trailing slash. // +kubebuilder:default:="factory.talos.dev/installer" InstallerRepository string `json:"installerRepository"` - // Talos `machine.registries.mirrors` passthrough for worker nodes: a map of upstream registry host to `{ endpoints: [ ... ] }`. Empty by default, so workers pull container images (the Talos `kubelet` image included) directly from the upstream registry. Point a host such as `ghcr.io` at an in-cluster pull-through mirror for air-gapped, rate-limited, or flaky-egress environments so a worker's boot does not depend on live public egress. Talos still falls back to the upstream registry unless a host also sets `skipFallback: true`, so a mirror alone does not enforce air-gap. Keep in sync with the parent kubernetes chart. + // Talos `machine.registries.mirrors` passthrough for worker nodes: a map of upstream registry host to `{ endpoints: [ ... ] }`. Empty by default, so workers pull container images (the Talos `kubelet` image included) directly from the upstream registry. Point a host such as `ghcr.io` at an in-cluster pull-through mirror for air-gapped, rate-limited, or flaky-egress environments so a worker's boot does not depend on live public egress. Talos still falls back to the upstream registry unless a host also sets `skipFallback: true`, so a mirror alone does not enforce air-gap. This value is part of the worker machine config, whose content hash names the TalosConfigTemplate, so changing it rolls every existing worker in the pool rather than only affecting nodes created later. // +kubebuilder:default:={} RegistryMirrors k8sRuntime.RawExtension `json:"registryMirrors"` // Talos image-factory schematic ID. Defaults to the cozystack-tested vanilla schematic. Operators using custom schematics (system extensions, kernel args) override here. The pool can pin its own via `osImage.builtin.schematicID` or `osImage.factory.schematicID`; when `osImage` omits it, this value applies. Whichever of the two applies is interpolated into an image URL and a DataVolume name, so it must be a plain lowercase alphanumeric identifier -- the render refuses anything else. A custom schematic on `osImage.builtin` also needs its own catalog entry, since the golden is named from the schematic ID. // +kubebuilder:default:="ce4c980550dd2ab1b17bbf2b08801c7eb59418eafe8f279833297925d67c7515" SchematicID string `json:"schematicID"` - // Default Talos release for this pool's worker OS image and in-guest installer. The pool can pin its own release via `osImage.builtin.version` or `osImage.factory.version`; when `osImage` omits it, this value applies. Both ways in are checked against the chart's Talos<->Kubernetes support matrix, against whichever release the pool actually resolves to, so an override cannot slip past a check `talos.version` would have failed. The matrix rejects a pairing it lists as unsupported; it lists the Talos minors this chart ships and passes any other minor unchecked, so pointing either field at a Talos release the chart does not know about is the operator's call, not a checked one. Whichever release applies is interpolated into an image URL and a DataVolume name, so it must be a full `vMAJOR.MINOR.PATCH` release, optionally with a pre-release suffix -- the render refuses anything else, a minor-only `v1.13` included. The values schema types this as a bare string, so a malformed one is accepted by the CR and fails the pool's HelmRelease instead. + // Sysctl overrides rendered into Talos `machine.sysctls` on this pool's guest workers only. Values must be strings (quote numeric values); for example, `user.max_user_namespaces: "11255"` enables the user namespaces required by the Talos gVisor extension. An empty map preserves Talos defaults and the existing bootstrap hash. Adding, changing or removing an override changes the content-hashed TalosConfigTemplate and rolls the pool's workers. Supported names and values depend on the worker's Talos release and kernel; unsafe settings can weaken guest isolation or prevent workers from booting. This does not install gVisor or configure a RuntimeClass, and does not change the management hosts, control plane or other pools. + // +kubebuilder:default:={} + Sysctls map[string]string `json:"sysctls,omitempty"` + // Default Talos release for this pool's worker OS image and for the installer image written into the worker machine config. The pool can pin its own release via `osImage.builtin.version` or `osImage.factory.version`; when `osImage` omits it, this value applies. Both ways in are checked against the chart's Talos<->Kubernetes support matrix, against whichever release the pool actually resolves to, so an override cannot slip past a check `talos.version` would have failed. The matrix lists, for each Talos minor the chart knows, the Kubernetes minors it supports and refuses a pool `version` outside that list; a Talos minor it does not list passes unchecked, so pointing either field at a Talos release the chart does not know about is the operator's call, not a checked one. Whichever release applies is interpolated into an image URL and a DataVolume name, so it must be a full `vMAJOR.MINOR.PATCH` release, optionally with a pre-release suffix -- the render refuses anything else, a minor-only `v1.13` included. The values schema types this as a bare string, so a malformed one is accepted by the CR and fails the pool's HelmRelease instead. // +kubebuilder:default:="v1.13.6" Version string `json:"version"` } @@ -189,7 +202,7 @@ type WorkerImageBuiltin struct { } type WorkerImageFactory struct { - // Base URL of the Image Factory serving the boot raw image. Defaults to `talos.imageFactoryURL`. No trailing slash. NOTE: this redirects only the worker boot-disk import; the in-guest upgrade installer image is always sourced from `talos.installerRepository`, so an air-gapped pool must also have `talos.installerRepository` pointed at a reachable registry. + // Base URL of the Image Factory serving the boot raw image. Defaults to `talos.imageFactoryURL`. No trailing slash. This redirects only the worker boot-disk import; the installer image in the worker machine config is always sourced from `talos.installerRepository`, so an air-gapped pool must also have `talos.installerRepository` pointed at a reachable registry. ImageFactoryURL string `json:"imageFactoryURL,omitempty"` // Talos schematic ID. Defaults to `talos.schematicID`. SchematicID string `json:"schematicID,omitempty"` diff --git a/api/apps/v1alpha1/kubernetesnodes/zz_generated.deepcopy.go b/api/apps/v1alpha1/kubernetesnodes/zz_generated.deepcopy.go index 7db86c953..dcc3b3e01 100644 --- a/api/apps/v1alpha1/kubernetesnodes/zz_generated.deepcopy.go +++ b/api/apps/v1alpha1/kubernetesnodes/zz_generated.deepcopy.go @@ -67,11 +67,22 @@ func (in *ConfigSpec) DeepCopyInto(out *ConfigSpec) { *out = make([]GPU, len(*in)) copy(*out, *in) } + if in.MaxUnavailable != nil { + in, out := &in.MaxUnavailable, &out.MaxUnavailable + *out = new(int) + **out = **in + } + if in.KernelModules != nil { + in, out := &in.KernelModules, &out.KernelModules + *out = make([]KernelModule, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } out.Kubelet = in.Kubelet in.OsImage.DeepCopyInto(&out.OsImage) in.Talos.DeepCopyInto(&out.Talos) in.Proxmox.DeepCopyInto(&out.Proxmox) - out.Images = in.Images } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConfigSpec. @@ -100,16 +111,21 @@ func (in *GPU) DeepCopy() *GPU { } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Images) DeepCopyInto(out *Images) { +func (in *KernelModule) DeepCopyInto(out *KernelModule) { *out = *in + if in.Parameters != nil { + in, out := &in.Parameters, &out.Parameters + *out = make([]string, len(*in)) + copy(*out, *in) + } } -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Images. -func (in *Images) DeepCopy() *Images { +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new KernelModule. +func (in *KernelModule) DeepCopy() *KernelModule { if in == nil { return nil } - out := new(Images) + out := new(KernelModule) in.DeepCopyInto(out) return out } @@ -191,6 +207,13 @@ func (in *Resources) DeepCopy() *Resources { func (in *Talos) DeepCopyInto(out *Talos) { *out = *in in.RegistryMirrors.DeepCopyInto(&out.RegistryMirrors) + if in.Sysctls != nil { + in, out := &in.Sysctls, &out.Sysctls + *out = make(map[string]string, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Talos. diff --git a/api/apps/v1alpha1/mongodb/types.go b/api/apps/v1alpha1/mongodb/types.go index 45efe8868..1ef060b85 100644 --- a/api/apps/v1alpha1/mongodb/types.go +++ b/api/apps/v1alpha1/mongodb/types.go @@ -60,30 +60,33 @@ type ConfigSpec struct { } type Backup struct { - // Destination path for backups (e.g. s3://bucket/path/). + // Destination path for backups (e.g. s3://bucket/path/). Ignored when useSystemBucket is true (the driver injects the platform bucket). // +kubebuilder:default:="s3://bucket/path/to/folder/" DestinationPath string `json:"destinationPath,omitempty"` // Enable regular backups. // +kubebuilder:default:=false Enabled bool `json:"enabled"` - // S3 endpoint URL for uploads. + // S3 endpoint URL for uploads. Ignored when useSystemBucket is true (the strategy supplies the platform endpoint). // +kubebuilder:default:="http://minio-gateway-service:9000" EndpointURL string `json:"endpointURL,omitempty"` - // Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs). + // Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs). Ignored when useSystemBucket is true (the platform backupStorage knob applies instead). // +kubebuilder:default:=false InsecureSkipTLSVerify bool `json:"insecureSkipTLSVerify,omitempty"` - // Retention policy (e.g. "30d"). + // Retention policy (e.g. "30d"). Ignored when useSystemBucket is true (no engine-side retention on that flow). // +kubebuilder:default:="30d" RetentionPolicy string `json:"retentionPolicy,omitempty"` - // Access key for S3 authentication. + // Access key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds). // +kubebuilder:default:="" S3AccessKey string `json:"s3AccessKey,omitempty"` - // Secret key for S3 authentication. + // Secret key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds). // +kubebuilder:default:="" S3SecretKey string `json:"s3SecretKey,omitempty"` - // Cron schedule for automated backups. + // Cron schedule for automated backups. Ignored when useSystemBucket is true (scheduling moves to the BackupClass Plan). // +kubebuilder:default:="0 2 * * *" Schedule string `json:"schedule,omitempty"` + // Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling moves to a BackupClass Plan; `schedule`, `retentionPolicy` and PITR are ignored while this is on, and this flow has no retention yet (see https://cozystack.io/docs/v1/operations/services/backup-classes/). Requires `backup.enabled: true` (the pbm agents run on that flag); the chart refuses the combination with `enabled: false` at render time; the schema carries the same rule as a marker for the UI and for the day the apiserver enforces CEL on application schemas (cozystack/cozystack#2657), which it does not yet. A release that has not yet rendered this flag (its cluster still carries the chart's scheduled tasks and PITR) holds a BackupJob until it does, so the tenant's own storage is never injected over. + // +kubebuilder:default:=false + UseSystemBucket bool `json:"useSystemBucket,omitempty"` } type Bootstrap struct { diff --git a/api/apps/v1alpha1/openbao/types.go b/api/apps/v1alpha1/openbao/types.go index b98ad5fbe..2bc68693e 100644 --- a/api/apps/v1alpha1/openbao/types.go +++ b/api/apps/v1alpha1/openbao/types.go @@ -39,6 +39,9 @@ type ConfigSpec struct { // Enable the OpenBAO web UI. // +kubebuilder:default:=true Ui bool `json:"ui"` + // Seal configuration. The default is Shamir key shares. Set `type: static` for auto-unseal. + // +kubebuilder:default:={} + Seal Seal `json:"seal"` } type Resources struct { @@ -48,5 +51,35 @@ type Resources struct { Memory resource.Quantity `json:"memory,omitempty"` } +type Seal struct { + // Acknowledge a seal migration. The chart refuses to change `type` on an existing instance unless this is `true`. Set it only while running `bao operator unseal -migrate`, then remove it. + // +kubebuilder:default:=false + AllowMigration bool `json:"allowMigration,omitempty"` + // Permanent identifier of the current key. OpenBAO stores it with the data the key wraps and picks the key by it, so change it whenever the key material changes. Lowercase alphanumerics, `-`, `.` and `_`, starting and ending with an alphanumeric, because the upstream chart evaluates the server config as a template and rewrites upper case placeholders such as `HOSTNAME` in it. Required when `type` is `static`. + // +kubebuilder:default:="" + // +kubebuilder:validation:Pattern="^([a-z0-9]([-a-z0-9._]*[a-z0-9])?)?$" + KeyId string `json:"keyId"` + // Identifier of the previous key, with the same character constraints as `keyId`. Required when `previousSecretName` is set. + // +kubebuilder:default:="" + // +kubebuilder:validation:Pattern="^([a-z0-9]([-a-z0-9._]*[a-z0-9])?)?$" + PreviousKeyId string `json:"previousKeyId,omitempty"` + // Secret holding the previous key during an n-1 key rotation, with the same name constraints as `secretName`. Keep it until the pods have been replaced and the active node has logged `upgrading stored keys`, see the README. + // +kubebuilder:default:="" + // +kubebuilder:validation:MaxLength=52 + // +kubebuilder:validation:Pattern="^([a-z0-9]([-a-z0-9]*[a-z0-9])?)?$" + PreviousSecretName string `json:"previousSecretName,omitempty"` + // Existing Secret in the tenant namespace whose key `key` holds the base64 text of 32 random bytes (for example `openssl rand -base64 32`). A cluster administrator creates it, because tenant roles cannot create Secrets. Lowercase alphanumerics and hyphens, at most 52 characters, because the pod volume is named `userconfig-` and a volume name is a DNS label. Required when `type` is `static`. + // +kubebuilder:default:="" + // +kubebuilder:validation:MaxLength=52 + // +kubebuilder:validation:Pattern="^([a-z0-9]([-a-z0-9]*[a-z0-9])?)?$" + SecretName string `json:"secretName"` + // Seal type. `shamir` keeps the current behaviour, `static` enables auto-unseal from `secretName`. + // +kubebuilder:default:="shamir" + Type SealType `json:"type"` +} + // +kubebuilder:validation:Enum="t1.nano";"t1.micro";"t1.small";"t1.medium";"t1.large";"t1.xlarge";"t1.2xlarge";"t1.4xlarge";"c1.nano";"c1.micro";"c1.small";"c1.medium";"c1.large";"c1.xlarge";"c1.2xlarge";"c1.4xlarge";"s1.nano";"s1.micro";"s1.small";"s1.medium";"s1.large";"s1.xlarge";"s1.2xlarge";"s1.4xlarge";"u1.nano";"u1.micro";"u1.small";"u1.medium";"u1.large";"u1.xlarge";"u1.2xlarge";"u1.4xlarge";"m1.nano";"m1.micro";"m1.small";"m1.medium";"m1.large";"m1.xlarge";"m1.2xlarge";"m1.4xlarge";"nano";"micro";"small";"medium";"large";"xlarge";"2xlarge" type ResourcesPreset string + +// +kubebuilder:validation:Enum="shamir";"static" +type SealType string diff --git a/api/apps/v1alpha1/openbao/zz_generated.deepcopy.go b/api/apps/v1alpha1/openbao/zz_generated.deepcopy.go index baa1258b1..f14bc7eec 100644 --- a/api/apps/v1alpha1/openbao/zz_generated.deepcopy.go +++ b/api/apps/v1alpha1/openbao/zz_generated.deepcopy.go @@ -55,6 +55,7 @@ func (in *ConfigSpec) DeepCopyInto(out *ConfigSpec) { *out = *in in.Resources.DeepCopyInto(&out.Resources) out.Size = in.Size.DeepCopy() + out.Seal = in.Seal } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConfigSpec. @@ -83,3 +84,18 @@ func (in *Resources) DeepCopy() *Resources { in.DeepCopyInto(out) return out } + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Seal) DeepCopyInto(out *Seal) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Seal. +func (in *Seal) DeepCopy() *Seal { + if in == nil { + return nil + } + out := new(Seal) + in.DeepCopyInto(out) + return out +} diff --git a/api/apps/v1alpha1/opensearch/types.go b/api/apps/v1alpha1/opensearch/types.go index 9f88f3e01..0a9102e7b 100644 --- a/api/apps/v1alpha1/opensearch/types.go +++ b/api/apps/v1alpha1/opensearch/types.go @@ -45,9 +45,6 @@ type ConfigSpec struct { // HTTP-layer TLS configuration. Selects who issues the HTTP server certificate; TLS itself is always served. // +kubebuilder:default:={} Tls TLS `json:"tls"` - // Container images used by the operator. - // +kubebuilder:default:={} - Images Images `json:"images"` // Node roles configuration. // +kubebuilder:default:={} NodeRoles NodeRoles `json:"nodeRoles"` @@ -74,12 +71,6 @@ type Dashboards struct { ResourcesPreset ResourcesPreset `json:"resourcesPreset"` } -type Images struct { - // OpenSearch image. - // +kubebuilder:default:="" - Opensearch string `json:"opensearch"` -} - type NodeRoles struct { // Enable data role. // +kubebuilder:default:=true diff --git a/api/apps/v1alpha1/opensearch/zz_generated.deepcopy.go b/api/apps/v1alpha1/opensearch/zz_generated.deepcopy.go index c6b2f4182..2f7e287ca 100644 --- a/api/apps/v1alpha1/opensearch/zz_generated.deepcopy.go +++ b/api/apps/v1alpha1/opensearch/zz_generated.deepcopy.go @@ -56,7 +56,6 @@ func (in *ConfigSpec) DeepCopyInto(out *ConfigSpec) { in.Resources.DeepCopyInto(&out.Resources) out.Size = in.Size.DeepCopy() out.Tls = in.Tls - out.Images = in.Images out.NodeRoles = in.NodeRoles if in.Users != nil { in, out := &in.Users, &out.Users @@ -94,21 +93,6 @@ func (in *Dashboards) DeepCopy() *Dashboards { return out } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Images) DeepCopyInto(out *Images) { - *out = *in -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Images. -func (in *Images) DeepCopy() *Images { - if in == nil { - return nil - } - out := new(Images) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NodeRoles) DeepCopyInto(out *NodeRoles) { *out = *in diff --git a/api/apps/v1alpha1/postgresql/types.go b/api/apps/v1alpha1/postgresql/types.go index 3ebcb44cf..70beb678e 100644 --- a/api/apps/v1alpha1/postgresql/types.go +++ b/api/apps/v1alpha1/postgresql/types.go @@ -40,6 +40,9 @@ type ConfigSpec struct { // PostgreSQL major version to deploy // +kubebuilder:default:="v18" Version Version `json:"version"` + // PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases..extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore). + // +kubebuilder:default:="postgresql" + Flavor Flavor `json:"flavor"` // TLS configuration for server connections. // +kubebuilder:default:={} Tls TLS `json:"tls"` @@ -55,7 +58,7 @@ type ConfigSpec struct { // Users configuration map. Passwords are always auto-generated and stored in the `-credentials` Secret; they cannot be set from values — read a user's password from that Secret. A `password` left over in values from before the field was removed is ignored by the render and draws an admission warning, but it is not inert on an upgraded release: the chart preserves whatever password is already in the Secret, which on the first upgrade is the value that was set before removal, so that value stays the live credential until it is rotated (dedicated rotation is tracked in cozystack/community#72). The live password lives only in the Secret. // +kubebuilder:default:={} Users map[string]User `json:"users,omitempty"` - // Databases configuration map. + // Databases configuration map. The PostgreSQL system databases `postgres`, `template0` and `template1` are refused. // +kubebuilder:default:={} Databases map[string]Database `json:"databases,omitempty"` // Backup configuration. @@ -121,7 +124,7 @@ type Backup struct { // DEPRECATED. See `s3AccessKey`. // +kubebuilder:default:="" S3SecretKey string `json:"s3SecretKey,omitempty"` - // Legacy. Cron schedule (CNPG 6-field format) for the chart-emitted ScheduledBackup. Empty means no chart-managed schedule, which is the recommended setup when a `BackupClass` from `backups.cozystack.io` already drives backup orchestration. In the legacy chart-managed flow `spec.plugins` plus the barman-cloud ObjectStore is rendered when `backup.enabled=true` AND `useSystemBucket=false` AND `destinationPath` is non-empty AND inline-or-external creds are supplied; in the platform `useSystemBucket=true` flow the chart skips emitting `spec.plugins` and the CNPG driver SSA-applies the ObjectStore and patches `spec.plugins` onto the live Cluster at first BackupJob time. + // Legacy. Cron schedule for the chart-emitted ScheduledBackup, either a standard five-field cron such as `0 2 * * *` for every day at 02:00, or six fields with leading seconds such as `0 0 2 * * *` for the same time. Empty means no chart-managed schedule, which is the recommended setup when a `BackupClass` from `backups.cozystack.io` already drives backup orchestration. In the legacy chart-managed flow `spec.plugins` plus the barman-cloud ObjectStore is rendered when `backup.enabled=true` AND `useSystemBucket=false` AND `destinationPath` is non-empty AND inline-or-external creds are supplied; in the platform `useSystemBucket=true` flow the chart skips emitting `spec.plugins` and the CNPG driver SSA-applies the ObjectStore and patches `spec.plugins` onto the live Cluster at first BackupJob time. // +kubebuilder:default:="" Schedule string `json:"schedule,omitempty"` // Opt-in: when true, the chart-emitted `-s3-creds` Secret is skipped AND `spec.plugins` (plus the barman-cloud ObjectStore) is left UNSET in the chart-rendered Cluster — the cozy-default BackupClass driver SSA-applies an ObjectStore (carrying destinationPath/endpointURL/credentials) and patches `spec.plugins` on the live Cluster when the first BackupJob runs. Consequence: plugin WAL archiving is NOT active until that first BackupJob fires; WAL accumulates on the PVC in the meantime, so fire an ad-hoc BackupJob immediately after enabling the flag on existing releases. Use together with the platform `cozy-default` BackupClass — tenants do not need to fill `s3AccessKey`/`s3SecretKey` or `destinationPath`/`endpointURL`. The destination path automatically scopes to `s3://cozy-backups///`. @@ -130,6 +133,9 @@ type Backup struct { } type Bootstrap struct { + // Barman ID of the base backup to recover from, passed as `recoveryTarget.backupID`. Empty lets the barman-cloud plugin pick one: the newest backup when `recoveryTime` is empty, otherwise the newest one ending at or before it, on any timeline. The CNPG backup driver sets this on restore. + // +kubebuilder:default:="" + BackupID string `json:"backupID,omitempty"` // Whether to restore from a backup. // +kubebuilder:default:=false Enabled bool `json:"enabled"` @@ -174,6 +180,8 @@ type PostgreSQL struct { // PostgreSQL server parameters. Values may be strings or integers; integers are coerced to strings by the template (e.g. both `max_connections: 100` and `max_connections: "100"` are accepted). BLOCKED (enable arbitrary code execution): archive_command, restore_command, ssl_passphrase_command, archive_cleanup_command, recovery_end_command, dynamic_library_path, local_preload_libraries, session_preload_libraries, shared_preload_libraries. Do NOT override CloudNativePG-managed parameters: archive_mode, primary_conninfo, wal_level, max_replication_slots. // +kubebuilder:default:={"max_connections":"100"} Parameters map[string]intstr.IntOrString `json:"parameters,omitempty"` + // Libraries loaded at server start, restricted to an allowlist of modules already shipped in the PostgreSQL image. CloudNativePG also preloads `pg_stat_statements`, `auto_explain` and `pgaudit` by itself whenever `parameters` sets a key under their prefix (e.g. `pg_stat_statements.track`), so removing one of them from this list does not unload it while such a key is set; `pg_prewarm` is preloaded only through this list. Changing the list restarts PostgreSQL on every instance, the primary included, so writes pause briefly. + SharedPreloadLibraries []PreloadLibrary `json:"sharedPreloadLibraries,omitempty"` } type Quorum struct { @@ -205,15 +213,27 @@ type S3CredentialsSecret struct { } type TLS struct { - // Tri-state switch controlling whether the chart injects the external hostname into the operator-managed CNPG cert via spec.certificates.serverAltDNSNames. When omitted, the chart injects the SAN if `external: true` and skips it otherwise. Set explicitly to `true` to inject regardless of `external` (no-op when `external: false` since there is no external hostname to add). Set to `false` to skip injection. Note that CNPG keeps its built-in TLS on the wire regardless of this flag — this toggle only controls the chart-side SAN injection; to disable PostgreSQL TLS entirely set `postgresql.parameters.ssl = "off"` at the CNPG layer. + // Tri-state switch controlling whether the chart injects the external hostnames into the operator-managed CNPG cert via spec.certificates.serverAltDNSNames. When omitted, the chart injects them if `external: true` and skips them otherwise. Set explicitly to `true` to inject regardless of `external` (no-op when `external: false` since there is no external hostname to add). Set to `false` to skip injection. Note that CNPG keeps its built-in TLS on the wire regardless of this flag — this toggle only controls the chart-side SAN injection; to disable PostgreSQL TLS entirely set `postgresql.parameters.ssl = "off"` at the CNPG layer. Enabled *bool `json:"enabled,omitempty"` + // Tri-state switch controlling whether the server refuses sessions that are not encrypted. When omitted, it is on if `external: true` and off otherwise. When on, the chart renders `spec.postgresql.pg_hba` with `hostssl all all all scram-sha-256` (`md5` on PostgreSQL 13, matching CloudNativePG's default rule) followed by `host all all all reject`, so a client that connects with `sslmode=disable` is refused instead of getting a plaintext session; in-cluster clients are held to the same rule, since the pod network cannot be told apart from an external client. Set to `false` to keep accepting plaintext sessions on an external instance, or to `true` to require TLS on an in-cluster one. Rendering fails if `postgresql.parameters.ssl` is off while this is in effect. + Required *bool `json:"required,omitempty"` } type User struct { + // Whether the user can bypass row-level security policies (BYPASSRLS). A role can only create other roles carrying BYPASSRLS if it holds the attribute itself, so this is required alongside `createRole` to provision a privileged service role. + BypassRls bool `json:"bypassRls,omitempty"` + // Whether the user can create and manage roles (CREATEROLE). Requires PostgreSQL 16 or newer. Setting it back to `false` withdraws the attribute only: the roles the user created, and its ADMIN and SET memberships in them, stay. Once any user has held it, the chart no longer adopts an existing role it did not create, so a user or database declared later under the name of such a role fails the init job until a platform administrator drops that role. + CreateRole bool `json:"createRole,omitempty"` // Whether the user has replication privileges. Replication bool `json:"replication,omitempty"` } +// +kubebuilder:validation:Enum="postgresql";"postgis" +type Flavor string + +// +kubebuilder:validation:Enum="pg_stat_statements";"auto_explain";"pgaudit";"pg_prewarm" +type PreloadLibrary string + // +kubebuilder:validation:Enum="ReadConnections";"ReadCPUUtilization" type ReadMetric string diff --git a/api/apps/v1alpha1/postgresql/zz_generated.deepcopy.go b/api/apps/v1alpha1/postgresql/zz_generated.deepcopy.go index 17ede2740..bfbb11908 100644 --- a/api/apps/v1alpha1/postgresql/zz_generated.deepcopy.go +++ b/api/apps/v1alpha1/postgresql/zz_generated.deepcopy.go @@ -206,6 +206,11 @@ func (in *PostgreSQL) DeepCopyInto(out *PostgreSQL) { (*out)[key] = val } } + if in.SharedPreloadLibraries != nil { + in, out := &in.SharedPreloadLibraries, &out.SharedPreloadLibraries + *out = make([]PreloadLibrary, len(*in)) + copy(*out, *in) + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PostgreSQL. @@ -273,6 +278,11 @@ func (in *TLS) DeepCopyInto(out *TLS) { *out = new(bool) **out = **in } + if in.Required != nil { + in, out := &in.Required, &out.Required + *out = new(bool) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TLS. diff --git a/api/apps/v1alpha1/rabbitmq/types.go b/api/apps/v1alpha1/rabbitmq/types.go index ca9c965b5..7ba9fd8bf 100644 --- a/api/apps/v1alpha1/rabbitmq/types.go +++ b/api/apps/v1alpha1/rabbitmq/types.go @@ -7,6 +7,7 @@ package rabbitmq import ( resource "k8s.io/apimachinery/pkg/api/resource" "k8s.io/apimachinery/pkg/apis/meta/v1" + k8sRuntime "k8s.io/apimachinery/pkg/runtime" ) // +kubebuilder:object:root=true @@ -36,6 +37,9 @@ type ConfigSpec struct { // Enable external access from outside the cluster. // +kubebuilder:default:=false External bool `json:"external"` + // Pod affinity applied to RabbitMQ pods (standard Kubernetes corev1.Affinity). Use podAntiAffinity with topologyKey `kubernetes.io/hostname` to spread RabbitMQ pods across nodes. + // +kubebuilder:default:={} + Affinity *k8sRuntime.RawExtension `json:"affinity,omitempty"` // TLS configuration. TLS is off unless `tls.enabled` is set to true. // +kubebuilder:default:={} Tls TLS `json:"tls,omitempty"` diff --git a/api/apps/v1alpha1/rabbitmq/zz_generated.deepcopy.go b/api/apps/v1alpha1/rabbitmq/zz_generated.deepcopy.go index 83503ed5c..16f86a646 100644 --- a/api/apps/v1alpha1/rabbitmq/zz_generated.deepcopy.go +++ b/api/apps/v1alpha1/rabbitmq/zz_generated.deepcopy.go @@ -21,7 +21,7 @@ limitations under the License. package rabbitmq import ( - runtime "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. @@ -55,6 +55,11 @@ func (in *ConfigSpec) DeepCopyInto(out *ConfigSpec) { *out = *in in.Resources.DeepCopyInto(&out.Resources) out.Size = in.Size.DeepCopy() + if in.Affinity != nil { + in, out := &in.Affinity, &out.Affinity + *out = new(runtime.RawExtension) + (*in).DeepCopyInto(*out) + } out.Tls = in.Tls if in.Users != nil { in, out := &in.Users, &out.Users diff --git a/api/apps/v1alpha1/redis/types.go b/api/apps/v1alpha1/redis/types.go index e1d7eca1b..8343de05b 100644 --- a/api/apps/v1alpha1/redis/types.go +++ b/api/apps/v1alpha1/redis/types.go @@ -7,6 +7,7 @@ package redis import ( resource "k8s.io/apimachinery/pkg/api/resource" "k8s.io/apimachinery/pkg/apis/meta/v1" + k8sRuntime "k8s.io/apimachinery/pkg/runtime" ) // +kubebuilder:object:root=true @@ -17,7 +18,7 @@ type Config struct { } type ConfigSpec struct { - // Number of Redis replicas. + // Number of Redis replicas. Three Sentinels watch them, or a single one when `replicas` is 1, since a lone pod has no replica to fail over to. // +kubebuilder:default:=2 Replicas int `json:"replicas"` // Explicit CPU and memory configuration for each Redis replica. When omitted, the preset defined in `resourcesPreset` is applied. @@ -26,6 +27,9 @@ type ConfigSpec struct { // Default sizing preset used when `resources` is omitted. // +kubebuilder:default:="t1.nano" ResourcesPreset ResourcesPreset `json:"resourcesPreset"` + // Kubernetes affinity configuration for Redis and Sentinel pods. + // +kubebuilder:default:={} + Affinity AffinitySpec `json:"affinity,omitempty"` // Persistent Volume Claim size available for application data. // +kubebuilder:default:="1Gi" Size resource.Quantity `json:"size"` @@ -33,10 +37,10 @@ type ConfigSpec struct { // +kubebuilder:default:="" // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="storageClass is immutable" StorageClass string `json:"storageClass"` - // Enable external access from outside the cluster. + // Enable external access from outside the cluster. Can be enabled only when the instance is created, together with `tls.enabled: true`; turning it on for an existing instance, or changing `tls.enabled` while it is on, is refused at admission. // +kubebuilder:default:=false External bool `json:"external"` - // Redis major version to deploy + // Redis major version to deploy. The Redis and Sentinel pods run the same image. // +kubebuilder:default:="v8" Version Version `json:"version"` // TLS configuration. TLS is opt-in and is not inferred from `external`. @@ -45,6 +49,32 @@ type ConfigSpec struct { // Enable password generation. // +kubebuilder:default:=true AuthEnabled bool `json:"authEnabled"` + // Redis `min-replicas-to-write`: the master refuses writes unless at least this many replicas are connected and within `minReplicasMaxLag`. Unset by default, which leaves the Redis default (disabled). With `replicas: 2` and a value of 1 the master rejects writes while its only replica is down, trading availability for a bound on the writes lost if an isolated master is failed over. Replication stays asynchronous, so this bounds the loss, it does not remove it. Must be 0 or more and below `replicas` (a master with `replicas` pods has `replicas - 1` replicas), otherwise every write is refused; the chart refuses such a value. + // +kubebuilder:validation:Minimum=0 + MinReplicasToWrite *int `json:"minReplicasToWrite,omitempty"` + // Redis `min-replicas-max-lag`, in seconds: a replica whose last acknowledgement is older than this does not count towards `minReplicasToWrite`. Unset by default, which leaves the Redis default (10). Has no effect unless `minReplicasToWrite` is set. Must be at least 1 when `minReplicasToWrite` is set: Redis treats 0 as disabling the check, so the chart refuses it. + // +kubebuilder:validation:Minimum=0 + MinReplicasMaxLag *int `json:"minReplicasMaxLag,omitempty"` + // Redis `maxmemory`: the dataset size at which Redis applies `maxmemoryPolicy`. Unset by default, which renders `maxmemory 0` (no limit, the Redis default), so a value set by hand with `CONFIG SET` is reset on the next reconcile. Must be at most 90% of the memory request of each Redis pod (from `resources` or `resourcesPreset`): the operator silently drops a larger value, so the chart refuses it. Leave headroom below that for replication and snapshot buffers. + Maxmemory resource.Quantity `json:"maxmemory,omitempty"` + // Redis `maxmemory-policy`: what Redis does once `maxmemory` is reached. `noeviction` refuses writes; `allkeys-lru` evicts the least recently used keys, which suits an instance used purely as a cache. Has no effect while `maxmemory` is unset. + // +kubebuilder:default:="noeviction" + MaxmemoryPolicy MaxmemoryPolicy `json:"maxmemoryPolicy"` + // Write RDB snapshots to the persistent volume (the Redis `save` directive, with the Redis default schedule). Set to `false` for an instance used purely as a cache: `save ""` is rendered and the volume is kept, so no further scheduled snapshot is written while replicas still have room for the full-sync RDB they write to disk. An RDB file already on the volume is not removed, and Redis loads it on restart, so turning snapshots off does not by itself empty the dataset. Always off when `size` is empty. + // +kubebuilder:default:=true + Snapshots bool `json:"snapshots"` + // Sentinel configuration. When `sentinel.resources` is empty and `sentinel.resourcesPreset` is unset, the Sentinel pods are sized like the Redis pods (`resources` and `resourcesPreset`). An empty `sentinel.resources` map counts as unset, as an empty top-level `resources` does. + // +kubebuilder:default:={} + Sentinel Sentinel `json:"sentinel,omitempty"` +} + +type AffinitySpec struct { + // Kubernetes Affinity for Redis pods. When set, redis-operator uses it verbatim and does not add its default soft podAntiAffinity; include podAntiAffinity unless replica co-location is intended. + // +kubebuilder:default:={} + Redis *k8sRuntime.RawExtension `json:"redis,omitempty"` + // Kubernetes Affinity for Sentinel pods. When set, redis-operator uses it verbatim and does not add its default soft podAntiAffinity; include podAntiAffinity unless replica co-location is intended. + // +kubebuilder:default:={} + Sentinel *k8sRuntime.RawExtension `json:"sentinel,omitempty"` } type Resources struct { @@ -54,6 +84,13 @@ type Resources struct { Memory resource.Quantity `json:"memory,omitempty"` } +type Sentinel struct { + // Explicit CPU and memory configuration for each Sentinel pod. Keys left out are filled from the preset in `sentinel.resourcesPreset`. + Resources Resources `json:"resources,omitempty"` + // Sizing preset for the Sentinel pods. Defaults to `resourcesPreset`. + ResourcesPreset ResourcesPreset `json:"resourcesPreset,omitempty"` +} + type TLS struct { // Maps to the Redis `tls-auth-clients` directive. Defaults to `no` — the server certificate is presented but client certificates are not validated. `yes` requires a client certificate signed by this release's CA, which the platform does not issue. Changing it restarts the Redis and Sentinel pods, because the directive is read from the config file once at startup. AuthClients AuthClients `json:"authClients,omitempty"` @@ -64,6 +101,9 @@ type TLS struct { // +kubebuilder:validation:Enum="no";"optional";"yes" type AuthClients string +// +kubebuilder:validation:Enum="noeviction";"allkeys-lru";"allkeys-lfu";"allkeys-random";"volatile-lru";"volatile-lfu";"volatile-random";"volatile-ttl" +type MaxmemoryPolicy string + // +kubebuilder:validation:Enum="t1.nano";"t1.micro";"t1.small";"t1.medium";"t1.large";"t1.xlarge";"t1.2xlarge";"t1.4xlarge";"c1.nano";"c1.micro";"c1.small";"c1.medium";"c1.large";"c1.xlarge";"c1.2xlarge";"c1.4xlarge";"s1.nano";"s1.micro";"s1.small";"s1.medium";"s1.large";"s1.xlarge";"s1.2xlarge";"s1.4xlarge";"u1.nano";"u1.micro";"u1.small";"u1.medium";"u1.large";"u1.xlarge";"u1.2xlarge";"u1.4xlarge";"m1.nano";"m1.micro";"m1.small";"m1.medium";"m1.large";"m1.xlarge";"m1.2xlarge";"m1.4xlarge";"nano";"micro";"small";"medium";"large";"xlarge";"2xlarge" type ResourcesPreset string diff --git a/api/apps/v1alpha1/redis/zz_generated.deepcopy.go b/api/apps/v1alpha1/redis/zz_generated.deepcopy.go index 8760e9854..cbfeead6e 100644 --- a/api/apps/v1alpha1/redis/zz_generated.deepcopy.go +++ b/api/apps/v1alpha1/redis/zz_generated.deepcopy.go @@ -21,9 +21,34 @@ limitations under the License. package redis import ( - runtime "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime" ) +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *AffinitySpec) DeepCopyInto(out *AffinitySpec) { + *out = *in + if in.Redis != nil { + in, out := &in.Redis, &out.Redis + *out = new(runtime.RawExtension) + (*in).DeepCopyInto(*out) + } + if in.Sentinel != nil { + in, out := &in.Sentinel, &out.Sentinel + *out = new(runtime.RawExtension) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AffinitySpec. +func (in *AffinitySpec) DeepCopy() *AffinitySpec { + if in == nil { + return nil + } + out := new(AffinitySpec) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Config) DeepCopyInto(out *Config) { *out = *in @@ -54,8 +79,21 @@ func (in *Config) DeepCopyObject() runtime.Object { func (in *ConfigSpec) DeepCopyInto(out *ConfigSpec) { *out = *in in.Resources.DeepCopyInto(&out.Resources) + in.Affinity.DeepCopyInto(&out.Affinity) out.Size = in.Size.DeepCopy() in.Tls.DeepCopyInto(&out.Tls) + if in.MinReplicasToWrite != nil { + in, out := &in.MinReplicasToWrite, &out.MinReplicasToWrite + *out = new(int) + **out = **in + } + if in.MinReplicasMaxLag != nil { + in, out := &in.MinReplicasMaxLag, &out.MinReplicasMaxLag + *out = new(int) + **out = **in + } + out.Maxmemory = in.Maxmemory.DeepCopy() + in.Sentinel.DeepCopyInto(&out.Sentinel) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConfigSpec. @@ -85,6 +123,22 @@ func (in *Resources) DeepCopy() *Resources { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Sentinel) DeepCopyInto(out *Sentinel) { + *out = *in + in.Resources.DeepCopyInto(&out.Resources) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Sentinel. +func (in *Sentinel) DeepCopy() *Sentinel { + if in == nil { + return nil + } + out := new(Sentinel) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TLS) DeepCopyInto(out *TLS) { *out = *in diff --git a/api/apps/v1alpha1/tenant/types.go b/api/apps/v1alpha1/tenant/types.go index 0af5ab867..fdb75f2e1 100644 --- a/api/apps/v1alpha1/tenant/types.go +++ b/api/apps/v1alpha1/tenant/types.go @@ -26,10 +26,13 @@ type ConfigSpec struct { // Deploy own Monitoring Stack. // +kubebuilder:default:=false Monitoring bool `json:"monitoring"` + // Send this tenant's traces to the shared VictoriaTraces store in tenant-root instead of a per-tenant backend; its Grafana reads them through a vmauth there that pins the tenant's own account, so tenants sharing the store cannot read each other's traces. It needs the tenant's own Monitoring (`monitoring: true`) and tenant-root hosting the store (`tracingCentralHost: true` on its Monitoring, with a `cluster`-mode tracingStorages entry named `generic`); without that the tenant's monitoring render fails rather than dropping spans. tenant-root, and whoever it admits to its Grafana, are inside the store's trust boundary. Applications should export over OTLP/HTTP, in requests below 3 MiB: spans above the platform's per-tenant write rate are retried over HTTP but dropped over gRPC, and a larger request is refused and not retried. + // +kubebuilder:default:=false + TracingCentral bool `json:"tracingCentral"` // Deploy own Ingress Controller. // +kubebuilder:default:=false Ingress bool `json:"ingress"` - // Deploy own Gateway API Gateway (backed by Cilium Gateway API controller). When unset (the default), the chart auto-enables the Gateway for tenants whose apex is derived from the parent (i.e. `host` is empty), and leaves it off for tenants with a custom non-derived apex. Set to `true` or `false` explicitly to override that auto-behaviour. Note: leave the key absent (do not write `gateway: null`) — the chart distinguishes "unset" via missing-key, not via null value, to satisfy the JSON schema generated from this comment. + // Deploy own Gateway API Gateway (backed by Cilium Gateway API controller). When unset (the default) or set to `false`, the tenant does not own a Gateway and instead publishes through the nearest ancestor tenant that owns one, regardless of whether `host` is empty or custom (`false` currently behaves the same as unset and does not opt out of that inheritance). Set to `true` to give the tenant its own Gateway with its own LoadBalancer IP and Certificate. A tenant with a custom (non-derived) `host` that needs its apex publicly reachable must set `true` explicitly, because an ancestor's TLS certificate does not cover a custom apex. Note: leave the key absent (do not write `gateway: null`): the chart distinguishes "unset" via missing-key, not via null value, to satisfy the JSON schema generated from this comment. Gateway bool `json:"gateway,omitempty"` // GatewayClass for this tenant's own Gateway. Empty uses the platform default (`gateway.className`). Only the classes the operator lists in the platform's `gateway.tenantSelectableClasses`, plus that default, may be named here — anything else fails this tenant's own gateway release and reaches no other tenant. Read only when this tenant owns a Gateway; an inheriting tenant uses its ancestor's. Whether a class terminates TLS itself or at its provider's edge is declared once per class on the platform, not here. // +kubebuilder:default:="" diff --git a/api/apps/v1alpha1/vminstance/types.go b/api/apps/v1alpha1/vminstance/types.go index 325c250c4..e457f4cac 100644 --- a/api/apps/v1alpha1/vminstance/types.go +++ b/api/apps/v1alpha1/vminstance/types.go @@ -65,12 +65,18 @@ type ConfigSpec struct { // Cloud-init user data. // +kubebuilder:default:="" CloudInit string `json:"cloudInit"` + // Supply cloud-init network-data that requests DHCP on every `en*` and `eth*` interface and keeps the DNS search domains DHCP offers. Needed for a netplan guest (Ubuntu, Debian) to address a secondary network such as a VPC subnet. Leave it off for a guest rendered by anything other than netplan, which would lose DHCP on every interface, and for a guest that configures an interface statically through netplan, which this configuration would shadow. Turning it on for a VM that has neither `cloudInit` nor `sshKeys` adds a cloud-init disk, and the guest's next boot is then treated as a first boot. + // +kubebuilder:default:=false + NetplanDhcp bool `json:"netplanDhcp"` // Seed string to generate SMBIOS UUID for the VM. // +kubebuilder:default:="" CloudInitSeed string `json:"cloudInitSeed"` } type Disk struct { + // Boot priority of the disk, 1 being tried first. Unset falls back to the disk's position in `disks` (the first disk gets 1), so set it to boot from a disk other than the first, such as an attached installer or rescue ISO, without reordering the list. Effective boot orders must be unique across disks: when one disk is given a value that another takes from its position, set both. + // +kubebuilder:validation:Minimum=1 + BootOrder *int `json:"bootOrder,omitempty"` // Disk bus type (e.g. "sata"). Bus string `json:"bus,omitempty"` // Disk name. @@ -80,7 +86,7 @@ type Disk struct { type Firmware struct { // Bootloader to boot the VM with: "uefi" (OVMF) or "bios" (SeaBIOS). Empty inherits the instanceProfile default. Bootloader string `json:"bootloader,omitempty"` - // Persist EFI NVRAM (e.g. enrolled Secure Boot keys, such as an updated Microsoft UEFI CA) across reboots. Only applies when bootloader is "uefi". On default RWO storage the VM is node-pinned (no live-migration). + // Persist EFI NVRAM (e.g. enrolled Secure Boot keys, such as an updated Microsoft UEFI CA) across reboots. Only applies when bootloader is "uefi". EfiPersistent bool `json:"efiPersistent,omitempty"` // Enable UEFI Secure Boot. Only applies when bootloader is "uefi". SecureBoot bool `json:"secureBoot,omitempty"` @@ -97,11 +103,11 @@ type Network struct { } type Resources struct { - // Number of CPU cores allocated, as a positive whole number such as `2`. Millicore and fractional quantities are rejected at render time, because the value becomes the VM's integer `domain.cpu.cores`. + // Number of CPU cores allocated, as a positive whole number such as `2`. Millicore or other unit-suffixed, fractional, zero, negative, above 4294967295 and quoted leading-zero values are rejected at render time, because the value becomes the VM's unsigned integer `domain.cpu.cores`. Cpu resource.Quantity `json:"cpu,omitempty"` - // Amount of memory allocated, as a positive quantity such as `8Gi`. + // Amount of memory allocated, as a quantity of at least `1M` such as `8Gi`. Less than 1M is rejected at render time, because KubeVirt refuses a non-zero amount below 1M and a zero or negative amount sizes nothing. Memory resource.Quantity `json:"memory,omitempty"` - // Number of CPU sockets (vCPU topology), as a positive whole number such as `1`. Millicore and fractional quantities are rejected at render time, because the value becomes the VM's integer `domain.cpu.sockets`. + // Number of CPU sockets (vCPU topology), as a positive whole number such as `1`. Millicore or other unit-suffixed, fractional, zero, negative, above 4294967295 and quoted leading-zero values are rejected at render time, because the value becomes the VM's unsigned integer `domain.cpu.sockets`. Sockets resource.Quantity `json:"sockets,omitempty"` } diff --git a/api/apps/v1alpha1/vminstance/zz_generated.deepcopy.go b/api/apps/v1alpha1/vminstance/zz_generated.deepcopy.go index 060281042..84f7315ac 100644 --- a/api/apps/v1alpha1/vminstance/zz_generated.deepcopy.go +++ b/api/apps/v1alpha1/vminstance/zz_generated.deepcopy.go @@ -61,7 +61,9 @@ func (in *ConfigSpec) DeepCopyInto(out *ConfigSpec) { if in.Disks != nil { in, out := &in.Disks, &out.Disks *out = make([]Disk, len(*in)) - copy(*out, *in) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } } if in.Networks != nil { in, out := &in.Networks, &out.Networks @@ -100,6 +102,11 @@ func (in *ConfigSpec) DeepCopy() *ConfigSpec { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Disk) DeepCopyInto(out *Disk) { *out = *in + if in.BootOrder != nil { + in, out := &in.BootOrder, &out.BootOrder + *out = new(int) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Disk. diff --git a/api/apps/v1alpha1/vpc/types.go b/api/apps/v1alpha1/vpc/types.go index fed72f58a..d79460681 100644 --- a/api/apps/v1alpha1/vpc/types.go +++ b/api/apps/v1alpha1/vpc/types.go @@ -42,6 +42,8 @@ type Route struct { } type Subnet struct { + // Additional source CIDRs admitted into this private subnet, such as remote networks routed in through a gateway VM + AllowSubnets []string `json:"allowSubnets,omitempty"` // IP address range Cidr string `json:"cidr,omitempty"` // Subnet name diff --git a/api/apps/v1alpha1/vpc/zz_generated.deepcopy.go b/api/apps/v1alpha1/vpc/zz_generated.deepcopy.go index 3cda29c4c..6513cc19e 100644 --- a/api/apps/v1alpha1/vpc/zz_generated.deepcopy.go +++ b/api/apps/v1alpha1/vpc/zz_generated.deepcopy.go @@ -56,7 +56,9 @@ func (in *ConfigSpec) DeepCopyInto(out *ConfigSpec) { if in.Subnets != nil { in, out := &in.Subnets, &out.Subnets *out = make([]Subnet, len(*in)) - copy(*out, *in) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } } if in.Peers != nil { in, out := &in.Peers, &out.Peers @@ -113,6 +115,11 @@ func (in *Route) DeepCopy() *Route { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Subnet) DeepCopyInto(out *Subnet) { *out = *in + if in.AllowSubnets != nil { + in, out := &in.AllowSubnets, &out.AllowSubnets + *out = make([]string, len(*in)) + copy(*out, *in) + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Subnet. diff --git a/api/backups/strategy/v1alpha1/altinity_types.go b/api/backups/strategy/v1alpha1/altinity_types.go index 6ce95348a..d9ba3308c 100644 --- a/api/backups/strategy/v1alpha1/altinity_types.go +++ b/api/backups/strategy/v1alpha1/altinity_types.go @@ -66,6 +66,13 @@ type AltinitySpec struct { // exposes .Name, .Namespace, and // .ApplicationRef.{APIGroup,Kind,Name} so to-copy // restores can address the source release. + // + // Stored schemaless: the apiserver keeps it as written rather than + // checking it against the pod schema, and it is validated when the + // driver creates the workload from it. + // + // +kubebuilder:validation:Schemaless + // +kubebuilder:pruning:PreserveUnknownFields Template corev1.PodTemplateSpec `json:"template"` } diff --git a/api/backups/strategy/v1alpha1/cnpg_types.go b/api/backups/strategy/v1alpha1/cnpg_types.go index 31a1acb0f..8720ee071 100644 --- a/api/backups/strategy/v1alpha1/cnpg_types.go +++ b/api/backups/strategy/v1alpha1/cnpg_types.go @@ -79,8 +79,11 @@ type CNPGTemplate struct { BarmanObjectStore BarmanObjectStoreTemplate `json:"barmanObjectStore"` // ServerName overrides the Barman server name used as the storage path - // prefix. When empty, the driver defaults it to the application name. - // Templating is supported. + // prefix. When empty, the driver defaults it to the Cluster name suffixed + // with the application UID, so a recreated application never archives + // into its predecessor's prefix. A Cluster that already has the + // barman-cloud plugin attached keeps its serverName. Templating is + // supported. // +optional ServerName string `json:"serverName,omitempty"` } diff --git a/api/backups/strategy/v1alpha1/etcd_types.go b/api/backups/strategy/v1alpha1/etcd_types.go index 3c1731214..060d7ad2d 100644 --- a/api/backups/strategy/v1alpha1/etcd_types.go +++ b/api/backups/strategy/v1alpha1/etcd_types.go @@ -107,8 +107,8 @@ type EtcdTemplate struct { // Until the upstream gains symmetric semantics (or surfaces the final // file path via the equivalent of BackupSnapshot.URI for PVC), this // driver intentionally narrows the API contract to S3 only. The S3 -// path is fully exercised end-to-end on dev7 and covered by unit + -// e2e tests. +// path is fully exercised end-to-end on a test cluster and covered by +// unit + e2e tests. // +kubebuilder:validation:XValidation:rule="has(self.s3)",message="s3 destination is required (PVC is intentionally not supported by this strategy until upstream restore-agent reads the same path the backup-agent writes; see the strategy comments)" type EtcdDestinationTemplate struct { // S3 configures an S3-compatible storage target. Templating is diff --git a/api/backups/strategy/v1alpha1/foundationdb_types.go b/api/backups/strategy/v1alpha1/foundationdb_types.go index 75bd2f0bd..a762dffbe 100644 --- a/api/backups/strategy/v1alpha1/foundationdb_types.go +++ b/api/backups/strategy/v1alpha1/foundationdb_types.go @@ -108,7 +108,14 @@ type FoundationDBTemplate struct { // Admins use it to mount credentials, CA bundles, or any other // per-tenant secrets the backup_agent needs. Templating is supported // on every string field. + // + // Stored schemaless: the apiserver keeps it as written rather than + // checking it against the pod schema, and it is validated when the + // driver creates the workload from it. + // // +optional + // +kubebuilder:validation:Schemaless + // +kubebuilder:pruning:PreserveUnknownFields BackupDeploymentPodTemplateSpec *corev1.PodTemplateSpec `json:"backupDeploymentPodTemplateSpec,omitempty"` } diff --git a/api/backups/strategy/v1alpha1/groupversion_info.go b/api/backups/strategy/v1alpha1/groupversion_info.go index 6cbfc8c2b..1777ab7f9 100644 --- a/api/backups/strategy/v1alpha1/groupversion_info.go +++ b/api/backups/strategy/v1alpha1/groupversion_info.go @@ -15,6 +15,17 @@ limitations under the License. */ // Package v1alpha1 contains API Schema definitions for the v1alpha1 API group. +// +// Fields that embed a large upstream struct, a PodTemplateSpec above all, are +// marked Schemaless with PreserveUnknownFields. backupstrategy-controller +// renders these CRDs from templates, so Helm stores each one twice in every +// release revision, and a revision is one Secret capped at 1 MiB; with the +// upstream schemas inlined the revision that renders the default strategies +// no longer fits and that upgrade fails. The Go types stay typed, and the +// apiserver validates the content when a driver creates the workload from it. +// hack/strategy-crd-schemaless.bats fails on a strategy CRD that inlines a +// pod template schema. +// // +kubebuilder:object:generate=true // +groupName=strategy.backups.cozystack.io package v1alpha1 diff --git a/api/backups/strategy/v1alpha1/job_types.go b/api/backups/strategy/v1alpha1/job_types.go index 9fe506510..d842a9e62 100644 --- a/api/backups/strategy/v1alpha1/job_types.go +++ b/api/backups/strategy/v1alpha1/job_types.go @@ -61,6 +61,13 @@ type JobSpec struct { // - `.Parameters` — the resolved BackupClass strategy parameters. // - `.Backup` — only on restore runs: `.Backup.Name`, `.Backup.Namespace` // and `.Backup.ApplicationRef` describing the source backup. + // + // Stored schemaless: the apiserver keeps it as written rather than + // checking it against the pod schema, and it is validated when the + // driver creates the workload from it. + // + // +kubebuilder:validation:Schemaless + // +kubebuilder:pruning:PreserveUnknownFields Template corev1.PodTemplateSpec `json:"template"` } diff --git a/api/backups/strategy/v1alpha1/kafka_types.go b/api/backups/strategy/v1alpha1/kafka_types.go index 289366f35..54b567aa8 100644 --- a/api/backups/strategy/v1alpha1/kafka_types.go +++ b/api/backups/strategy/v1alpha1/kafka_types.go @@ -71,11 +71,10 @@ type KafkaSpec struct { // - `.Backup` — only on restore: `.Backup.Name`, `.Backup.Namespace` and // `.Backup.ApplicationRef` describing the source backup. // - // Stored schemaless deliberately: the full PodTemplateSpec OpenAPI schema is - // ~590 KB, and inlining it here (after Altinity/Job/FoundationDB) would push - // the chart's Helm state Secret over the 1 MiB cap. See job_types.go for the - // same field carried with its schema, and strategy-kafka-default.yaml for - // the rendered pod. + // Stored schemaless: the apiserver keeps it as written rather than + // checking it against the pod schema, and it is validated when the + // driver creates the workload from it. See + // strategy-kafka-default.yaml for the rendered pod. // // +kubebuilder:validation:Schemaless // +kubebuilder:pruning:PreserveUnknownFields diff --git a/api/backups/strategy/v1alpha1/kubernetes_types.go b/api/backups/strategy/v1alpha1/kubernetes_types.go new file mode 100644 index 000000000..704fc5d9f --- /dev/null +++ b/api/backups/strategy/v1alpha1/kubernetes_types.go @@ -0,0 +1,95 @@ +// SPDX-License-Identifier: Apache-2.0 +// Package v1alpha1 defines strategy.backups.cozystack.io API types. +// +// Group: strategy.backups.cozystack.io +// Version: v1alpha1 +package v1alpha1 + +import ( + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +func init() { + SchemeBuilder.Register(func(s *runtime.Scheme) error { + s.AddKnownTypes(GroupVersion, + &Kubernetes{}, + &KubernetesList{}, + ) + return nil + }) +} + +const ( + KubernetesStrategyKind = "Kubernetes" +) + +// +kubebuilder:object:root=true +// +kubebuilder:subresource:status +// +kubebuilder:resource:scope=Cluster + +// Kubernetes defines a backup strategy for a tenant Kubernetes application. +// A tenant cluster keeps its state in two places the platform can reach: the +// cluster's key prefix in the tenant's shared etcd DataStore, and host-side +// objects (control-plane PKI Secrets, the application HelmReleases, and the +// DataVolumes that back the tenant's PersistentVolumes). The strategy captures +// the first with a one-shot Job and the second with Velero. The two are taken +// one after another, so a backup is crash-consistent at best. +type Kubernetes struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec KubernetesSpec `json:"spec,omitempty"` + Status KubernetesStatus `json:"status,omitempty"` +} + +// +kubebuilder:object:root=true + +// KubernetesList contains a list of Kubernetes backup strategies. +type KubernetesList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []Kubernetes `json:"items"` +} + +// KubernetesSpec specifies the desired behavior of a Kubernetes backup strategy. +type KubernetesSpec struct { + // Template holds a PodTemplateSpec for the Job that dumps the cluster's + // key prefix from its etcd DataStore to object storage, writes it back on + // restore, and deletes the object on cleanup. The Job runs in the + // application namespace. Helm-like Go templates are supported in every + // string field and are rendered against: + // - `.Release.Name` and `.Release.Namespace` — the application's name and + // namespace; `.Release.Prefix` is `kubernetes-`. + // - `.Mode` — `"backup"`, `"restore"` or `"cleanup"`. + // - `.ObjectKey` — the object-storage key of this backup's dump. + // - `.Datastore.Prefix` — the cluster's key prefix, without slashes. + // - `.Datastore.Endpoints` — comma-separated etcd client URLs. + // - `.Datastore.CertificateSecret` — the Secret holding the cluster's + // etcd client certificate (`ca.crt`, `server.crt`, `server.key`). + // - `.Parameters` — the resolved BackupClass strategy parameters. + // + // Stored schemaless for the same CRD-size reason as redis_types.go. + // + // +kubebuilder:validation:Schemaless + // +kubebuilder:pruning:PreserveUnknownFields + Template corev1.PodTemplateSpec `json:"template"` + + // Velero holds the Velero Backup and Restore specs for the host-side + // objects and volumes. Rendered against `.Application` and `.Parameters`, + // like the Velero strategy. + // + // +kubebuilder:validation:Schemaless + // +kubebuilder:pruning:PreserveUnknownFields + Velero VeleroTemplate `json:"velero"` + + // CertificateWarningThreshold is how close to expiry a control-plane + // certificate may be before a backup records a warning. Defaults to 720h. + // +optional + CertificateWarningThreshold *metav1.Duration `json:"certificateWarningThreshold,omitempty"` +} + +type KubernetesStatus struct { + Conditions []metav1.Condition `json:"conditions,omitempty"` +} diff --git a/api/backups/strategy/v1alpha1/mongodb_types.go b/api/backups/strategy/v1alpha1/mongodb_types.go index 2f4772891..abefdabe7 100644 --- a/api/backups/strategy/v1alpha1/mongodb_types.go +++ b/api/backups/strategy/v1alpha1/mongodb_types.go @@ -37,11 +37,14 @@ const ( // carrying the S3 destination read back from the source backup, so the same // artifact restores in-place or into a differently-named instance. // -// Unlike the MariaDB strategy, the storage config is NOT inlined here: psmdb -// resolves spec.storageName against the source cluster's spec.backup.storages, -// so the S3/credentials live on the PerconaServerMongoDB CR (the mongodb chart -// declares them when backup.enabled=true) and the strategy only names the -// storage to use. +// The strategy always names the storage (spec.template.storageName) psmdb +// resolves against the source cluster's spec.backup.storages. On the legacy +// flow the S3/credentials for that storage live on the PerconaServerMongoDB CR +// (the mongodb chart declares them when backup.enabled=true and +// useSystemBucket=false). On the useSystemBucket flow the chart cannot know the +// platform bucket at render time, so the strategy also carries the storage's S3 +// coordinates (spec.template.s3) and the driver SSA-injects them onto the +// cluster at BackupJob time. type MongoDB struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` @@ -75,9 +78,11 @@ type MongoDBSpec struct { // MongoDBTemplate describes the templated PerconaServerMongoDBBackup shape the // driver renders per BackupJob. type MongoDBTemplate struct { - // StorageName names a storage entry declared in the source cluster's - // spec.backup.storages. The mongodb chart declares "s3-storage" when - // backup.enabled=true; leave empty to use that default. Templating is + // StorageName names a storage entry in the source cluster's + // spec.backup.storages. On the legacy flow the mongodb chart declares + // "s3-storage" when backup.enabled=true and useSystemBucket=false; on the + // useSystemBucket flow the driver injects an entry under this same name from + // the S3 coordinates below. Leave empty to use "s3-storage". Templating is // supported. // +optional StorageName string `json:"storageName,omitempty"` @@ -100,6 +105,45 @@ type MongoDBTemplate struct { // Left unset the operator picks its default. // +optional CompressionLevel *int `json:"compressionLevel,omitempty"` + + // S3 carries the system-bucket storage coordinates the driver SSA-patches + // onto the source PerconaServerMongoDB's spec.backup.storages[StorageName] + // on the useSystemBucket flow. PBM takes these as static CR fields (not + // secret refs), and the platform bucket name / endpoint are only known at + // BackupJob time, so the cozy-default strategy carries them (endpointUrl + // already scheme'd by the endpoint helper) and the driver injects them. Nil + // means the legacy flow: rely on the storage the app chart rendered + // statically, and patch nothing. + // +optional + S3 *MongoDBStorageS3 `json:"s3,omitempty"` +} + +// MongoDBStorageS3 mirrors the psmdb spec.backup.storages[].s3 block the +// driver injects. String fields support templating (e.g. Prefix uses +// {{ .Application.metadata.namespace }}/{{ .Application.metadata.name }}). +type MongoDBStorageS3 struct { + // Bucket is the S3 bucket name (the COSI-assigned system bucket). + // +optional + Bucket string `json:"bucket,omitempty"` + // EndpointURL is the full S3 endpoint URL including scheme. + // +optional + EndpointURL string `json:"endpointUrl,omitempty"` + // Region is the S3 region. + // +optional + Region string `json:"region,omitempty"` + // Prefix scopes this release's backups under the bucket. + // +optional + Prefix string `json:"prefix,omitempty"` + // CredentialsSecret names the Secret carrying AWS_ACCESS_KEY_ID / + // AWS_SECRET_ACCESS_KEY. Defaults to cozy-backups-creds when empty. + // +optional + CredentialsSecret string `json:"credentialsSecret,omitempty"` + // ForcePathStyle selects path-style S3 addressing. + // +optional + ForcePathStyle *bool `json:"forcePathStyle,omitempty"` + // InsecureSkipTLSVerify disables S3 endpoint certificate verification. + // +optional + InsecureSkipTLSVerify bool `json:"insecureSkipTLSVerify,omitempty"` } // MongoDBStatus reports observed state for the strategy CR. Driver controllers diff --git a/api/backups/strategy/v1alpha1/rabbitmq_types.go b/api/backups/strategy/v1alpha1/rabbitmq_types.go index b4f8c8e21..58ed160aa 100644 --- a/api/backups/strategy/v1alpha1/rabbitmq_types.go +++ b/api/backups/strategy/v1alpha1/rabbitmq_types.go @@ -83,13 +83,9 @@ type RabbitmqSpec struct { // .ApplicationRef.{APIGroup,Kind,Name} so a to-copy // restore can address the source release's object key. // - // The template is stored schemaless (its content is preserved but not - // validated by the apiserver): the driver renders and validates the pod - // spec, and generating the full PodTemplateSpec OpenAPI schema here would - // add ~590 KB to this CRD. The backupstrategy-controller chart inlines - // every definitions/*.yaml into one Helm release, whose state Secret is - // capped at 1 MiB - a fourth full PodTemplateSpec schema (after Altinity, - // Job and FoundationDB) pushes that Secret over the cap and fails install. + // Stored schemaless: the apiserver keeps it as written rather than + // checking it against the pod schema, and it is validated when the + // driver creates the workload from it. // // +kubebuilder:validation:Schemaless // +kubebuilder:pruning:PreserveUnknownFields diff --git a/api/backups/strategy/v1alpha1/redis_types.go b/api/backups/strategy/v1alpha1/redis_types.go index b17b200bd..154bd188c 100644 --- a/api/backups/strategy/v1alpha1/redis_types.go +++ b/api/backups/strategy/v1alpha1/redis_types.go @@ -29,11 +29,11 @@ const ( // +kubebuilder:subresource:status // +kubebuilder:resource:scope=Cluster -// Redis defines a backup strategy for a spotahome RedisFailover app. The -// spotahome operator ships no backup CRD, so the strategy runs a one-shot Job -// that dumps an RDB snapshot to object storage (and replays it on restore) - -// the same PodTemplateSpec model as the Job/Altinity strategies rather than an -// operator-CR delegation. +// Redis defines a backup strategy for a spotahome RedisFailover app, Redis or +// Valkey. The spotahome operator ships no backup CRD, so the strategy runs a +// one-shot Job that dumps an RDB snapshot to object storage (and replays it on +// restore) - the same PodTemplateSpec model as the Job/Altinity strategies +// rather than an operator-CR delegation. type Redis struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` @@ -61,6 +61,10 @@ type RedisSpec struct { // `.Application.spec.replicas`). // - `.Release.Name` and `.Release.Namespace` — the application's name // and namespace. + // - `.Release.Prefix` — the prefix the application's chart puts before + // the name of every resource it creates: `redis-` for a Redis + // application, `valkey-` for a Valkey one. Both run on the same + // RedisFailover operator, so one strategy serves either kind. // - `.Mode` — `"backup"`, `"restore"`, or `"cleanup"` (delete the object // of a removed Backup), identifying the run. // - `.ObjectKey` — the object-storage key for this run: unique per backup, @@ -72,14 +76,9 @@ type RedisSpec struct { // and `.Backup.ApplicationRef` describing the source backup, so a // to-copy restore reads the SOURCE release's object-storage prefix. // - // Stored schemaless (content preserved, not validated by the apiserver): the - // driver renders and validates the pod spec, and generating the full - // PodTemplateSpec OpenAPI schema here would add ~590 KB to this CRD. The - // backupstrategy-controller chart inlines every definitions/*.yaml into one - // Helm release whose state Secret is capped at 1 MiB, so a full - // PodTemplateSpec schema here (a fifth after Altinity, Job, FoundationDB and - // Redis's own siblings) pushes that Secret over the cap and fails install. - // Same reason as rabbitmq_types.go. + // Stored schemaless: the apiserver keeps it as written rather than + // checking it against the pod schema, and it is validated when the + // driver creates the workload from it. // // +kubebuilder:validation:Schemaless // +kubebuilder:pruning:PreserveUnknownFields diff --git a/api/backups/strategy/v1alpha1/zz_generated.deepcopy.go b/api/backups/strategy/v1alpha1/zz_generated.deepcopy.go index 6241b2fc2..9efd1fb9b 100644 --- a/api/backups/strategy/v1alpha1/zz_generated.deepcopy.go +++ b/api/backups/strategy/v1alpha1/zz_generated.deepcopy.go @@ -839,6 +839,109 @@ func (in *KafkaStatus) DeepCopy() *KafkaStatus { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Kubernetes) DeepCopyInto(out *Kubernetes) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Kubernetes. +func (in *Kubernetes) DeepCopy() *Kubernetes { + if in == nil { + return nil + } + out := new(Kubernetes) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Kubernetes) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *KubernetesList) DeepCopyInto(out *KubernetesList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Kubernetes, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new KubernetesList. +func (in *KubernetesList) DeepCopy() *KubernetesList { + if in == nil { + return nil + } + out := new(KubernetesList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *KubernetesList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *KubernetesSpec) DeepCopyInto(out *KubernetesSpec) { + *out = *in + in.Template.DeepCopyInto(&out.Template) + in.Velero.DeepCopyInto(&out.Velero) + if in.CertificateWarningThreshold != nil { + in, out := &in.CertificateWarningThreshold, &out.CertificateWarningThreshold + *out = new(v1.Duration) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new KubernetesSpec. +func (in *KubernetesSpec) DeepCopy() *KubernetesSpec { + if in == nil { + return nil + } + out := new(KubernetesSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *KubernetesStatus) DeepCopyInto(out *KubernetesStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new KubernetesStatus. +func (in *KubernetesStatus) DeepCopy() *KubernetesStatus { + if in == nil { + return nil + } + out := new(KubernetesStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MariaDB) DeepCopyInto(out *MariaDB) { *out = *in @@ -1151,6 +1254,26 @@ func (in *MongoDBStatus) DeepCopy() *MongoDBStatus { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MongoDBStorageS3) DeepCopyInto(out *MongoDBStorageS3) { + *out = *in + if in.ForcePathStyle != nil { + in, out := &in.ForcePathStyle, &out.ForcePathStyle + *out = new(bool) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MongoDBStorageS3. +func (in *MongoDBStorageS3) DeepCopy() *MongoDBStorageS3 { + if in == nil { + return nil + } + out := new(MongoDBStorageS3) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MongoDBTemplate) DeepCopyInto(out *MongoDBTemplate) { *out = *in @@ -1159,6 +1282,11 @@ func (in *MongoDBTemplate) DeepCopyInto(out *MongoDBTemplate) { *out = new(int) **out = **in } + if in.S3 != nil { + in, out := &in.S3, &out.S3 + *out = new(MongoDBStorageS3) + (*in).DeepCopyInto(*out) + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MongoDBTemplate. diff --git a/api/backups/v1alpha1/DESIGN.md b/api/backups/v1alpha1/DESIGN.md index 628b0d7b4..faaffbcde 100644 --- a/api/backups/v1alpha1/DESIGN.md +++ b/api/backups/v1alpha1/DESIGN.md @@ -31,7 +31,7 @@ Tenants reference `cozy-default` from `BackupJob`/`Plan`/`RestoreJob`; they neve The platform-managed flow is layered *on top of* — not in place of — the core API. Custom `BackupClass`/Strategy CRs targeting other buckets continue to work; tenants picking `cozy-default` simply opt into the platform's pre-wired stack. -**Open gap (FoundationDB):** the `cozy-default-foundationdb` Strategy CR is shipped but **not** bound by `cozy-default`. Restore for FoundationDB runs `fdbrestore` from inside the `cozy-foundationdb-operator` deployment, which does not yet mount `cozy-backups-creds` with the blob credentials file. Admins who want platform-default FDB backups today must either wire the operator deployment manually or use a custom BackupClass — see [Backup Classes](../../../docs/operations/backup-classes.md) for the follow-up plan. +**Open gap (FoundationDB):** the `cozy-default-foundationdb` Strategy CR is shipped but **not** bound by `cozy-default`. Restore for FoundationDB runs `fdbrestore` from inside the `cozy-foundationdb-operator` deployment, which does not yet mount `cozy-backups-creds` with the blob credentials file. Admins who want platform-default FDB backups today must either wire the operator deployment manually or use a custom BackupClass — see [Backup Classes](https://cozystack.io/docs/v1/operations/services/backup-classes/) for the follow-up plan. **Tenant visibility:** projected Secrets carry no `internal.cozystack.io/tenantresource` label, so the lineage-controller webhook does not promote them to a `TenantSecret` view. Combined with the default RBAC (no core/v1.Secret verbs on tenant ServiceAccounts), the projected credentials are unreadable from a tenant kubeconfig even when they sit in the tenant's own namespace; the operator Pods mount the Secret via kubelet, which bypasses tenant RBAC. diff --git a/api/backups/v1alpha1/backup_types.go b/api/backups/v1alpha1/backup_types.go index fd76ac47e..541488202 100644 --- a/api/backups/v1alpha1/backup_types.go +++ b/api/backups/v1alpha1/backup_types.go @@ -37,7 +37,14 @@ type BackupArtifact struct { // For example: s3://bucket/prefix/file.tar.gz URI string `json:"uri"` - // SizeBytes is the size of the artifact in bytes, if known. + // SizeBytes is the stored size in bytes of the files this backup owns, + // if known: the dump of a MariaDB backup, for example, or the base backup + // of a CNPG one, which leaves out the WAL archive the server's backups + // share and a point-in-time restore also reads. Strategies that cannot + // attribute stored bytes to a single backup, such as Velero's, whose + // repository deduplicates across backups, leave it unset. Drivers never + // write 0 for a size they cannot measure, so an absent value means + // "unknown", not "empty". // +optional SizeBytes int64 `json:"sizeBytes,omitempty"` diff --git a/api/gateway/v1alpha1/tenantgateway_types.go b/api/gateway/v1alpha1/tenantgateway_types.go index c1aa4a45a..ff6d48eb8 100644 --- a/api/gateway/v1alpha1/tenantgateway_types.go +++ b/api/gateway/v1alpha1/tenantgateway_types.go @@ -184,9 +184,10 @@ type TLSPassthroughListener struct { // native port (e.g. 5432 for PostgreSQL). Must be 1..65535, unique // across the list, and neither 80 nor 443 — the Gateway's own http // (80) and TLS-terminate (443) listeners already own those ports. - // It is not an access boundary: on the Cilium version this - // platform pins, the backend answers this listener's SNI on every - // port the Gateway exposes, so the hostname is what gates reach. + // It is not an access boundary: an implementation may serve every + // port of the Gateway from one proxy listener matched by SNI alone, + // and Cilium does so until the Gateway carries a configuration that + // splits it per port, so the hostname is what gates reach. // +kubebuilder:validation:Minimum=1 // +kubebuilder:validation:Maximum=65535 // +required @@ -246,7 +247,7 @@ type TLSPassthroughListener struct { // +kubebuilder:validation:XValidation:rule="!has(self.tlsPassthroughListeners) || self.tlsPassthroughListeners.all(l, self.tlsPassthroughListeners.filter(o, o.port == l.port).size() == 1)",message="tlsPassthroughListeners: each listener must occupy a distinct port" // +kubebuilder:validation:XValidation:rule="!has(self.tlsPassthroughListeners) || self.tlsPassthroughListeners.all(l, l.hostname == self.apex || l.hostname.endsWith('.' + self.apex))",message="tlsPassthroughListeners: hostname must equal the tenant apex or be a subdomain of it" // +kubebuilder:validation:XValidation:rule="!has(self.tlsPassthroughListeners) || !has(self.tlsPassthroughServices) || self.tlsPassthroughListeners.all(l, !(l.name in self.tlsPassthroughServices))",message="tlsPassthroughListeners: name collides with a tlsPassthroughServices entry; both render a tls- Gateway listener" -// +kubebuilder:validation:XValidation:rule="!has(self.tlsPassthroughListeners) || size(self.tlsPassthroughListeners) == 0 || !has(self.certMode) || self.certMode == 'http01'",message="tlsPassthroughListeners: supported with certMode http01 only; dns01 and existingSecret serve the tenant from one wildcard terminate listener that the pinned Cilium cannot keep apart from a passthrough listener under the same apex, and edge terminates TLS upstream and renders no TLS listener to sit beside" +// +kubebuilder:validation:XValidation:rule="!has(self.tlsPassthroughListeners) || size(self.tlsPassthroughListeners) == 0 || !has(self.certMode) || self.certMode != 'edge'",message="tlsPassthroughListeners: unsupported with certMode edge, which terminates TLS upstream and renders no TLS listener to sit beside" type TenantGatewaySpec struct { // MaxLength is the DNS ceiling, so it rejects nothing resolvable, // and it is not cosmetic: it is one of the three bounds the @@ -376,10 +377,10 @@ type TenantGatewaySpec struct { // for the listener's Hostname — a passthrough listener never // terminates TLS, so the Gateway neither holds nor issues that // certificate. Until such a route attaches and its backend - // resolves, the entry publishes the port and answers nothing on it: - // a passthrough listener carrying no forwarding route contributes - // no filter chain, so a hostname an HTTPS-terminate listener - // already serves goes on being served there. + // resolves, the entry publishes the port and answers nothing on it. + // Under certMode http01 its hostname is reserved from the moment it + // is declared: no HTTPS-terminate listener or certificate is + // rendered for it on 443, route or no route. // +optional // +listType=map // +listMapKey=name diff --git a/api/v1alpha1/workloadmonitor_types.go b/api/v1alpha1/workloadmonitor_types.go index e7639edb4..b5089652a 100644 --- a/api/v1alpha1/workloadmonitor_types.go +++ b/api/v1alpha1/workloadmonitor_types.go @@ -8,6 +8,7 @@ import ( type WorkloadMonitorSpec struct { // Selector is a label selector to find workloads to monitor // +required + // +kubebuilder:validation:MinProperties=1 Selector map[string]string `json:"selector"` // Kind specifies the kind of the workload @@ -34,6 +35,14 @@ type WorkloadMonitorSpec struct { Replicas *int32 `json:"replicas,omitempty"` } +// WorkloadMonitorReasonDataVolumeNotReady is the status Reason of a monitor +// that is not operational because a DataVolume it selects is not ready. +const WorkloadMonitorReasonDataVolumeNotReady = "DataVolumeNotReady" + +// WorkloadMonitorReasonBucketClaimNotReady is the status Reason of a monitor +// that is not operational because a BucketClaim it selects is not provisioned. +const WorkloadMonitorReasonBucketClaimNotReady = "BucketClaimNotReady" + // WorkloadMonitorStatus defines the observed state of WorkloadMonitor type WorkloadMonitorStatus struct { // Operational indicates if the workload meets all operational requirements @@ -47,6 +56,16 @@ type WorkloadMonitorStatus struct { // ObservedReplicas is the total number of pods observed // +optional ObservedReplicas int32 `json:"observedReplicas"` + + // Message names what keeps the workload from being operational, when the + // controller can tell. + // +optional + Message string `json:"message,omitempty"` + + // Reason is a machine-readable cause for Message, such as + // DataVolumeNotReady. + // +optional + Reason string `json:"reason,omitempty"` } // +kubebuilder:object:root=true diff --git a/cmd/backport-batch/README.md b/cmd/backport-batch/README.md new file mode 100644 index 000000000..7137bdaf0 --- /dev/null +++ b/cmd/backport-batch/README.md @@ -0,0 +1,151 @@ +# backport-batch + +Builds the automatic backport batch for a release line and gates a patch cut on it. What goes into a batch is decided by the rules of the [backport policy](../../docs/release/backports.md) alone; this page describes how the tool applies them and does not restate them. + +## Usage + +```bash +go build ./cmd/backport-batch +./backport-batch run --line release-1.7 [--onto SHA] [--date YYYY-MM-DD] [--no-workflow-files] [--push] [--policy REF] +./backport-batch run --line release-1.7 --continue [--no-workflow-files] [--push] [--policy REF] +./backport-batch run --line release-1.7 --defer 4321[,4322] --reason "fails the e2e of the app" [--push] [--policy REF] +./backport-batch run --line release-1.7 --drop 4321[,4322] --reason "builds on the 1.8 storage rework" [--push] [--policy REF] +./backport-batch run --line release-1.7 --undrop 4321[,4322] [--push] [--policy REF] +./backport-batch check --line release-1.7 [--cut] [--policy REF] +./backport-batch fold --line release-1.7 --original 4321 --commit SHA [--policy REF] +./backport-batch verify --line release-1.7 [--head SHA] +./backport-batch notify --line release-1.7 [--mention org/team|login] [--push] +./backport-batch report --pr 5246 [--id ID] [--json] +./backport-batch lines [--policy REF] +``` + +[`hack/backport-batch-scheduled.sh`](../../hack/backport-batch-scheduled.sh) runs `lines`, then `run --continue --push`, `check` and `notify` for each line; [`backport-batch.yaml`](../../.github/workflows/backport-batch.yaml) runs it on schedule as the cozystack-ci App, with `--no-workflow-files`, which it hands to `run`. + +Requires `git` and an authenticated `gh` on PATH, and a remote called `origin`. Every command but `notify` and `report` fetches `origin` first; `notify` reads only GitHub, and `report` reads GitHub and, for a report that keeps drops, the clone's history. The batch runs only for the lines `lines` prints. + +`run`, `check`, `fold` and `lines` read the `backport-policy` block of the policy page from `origin/main`, or from the ref `--policy` names, which is how a change to the page is tried before it merges; `verify` and `notify` do not read it and take no `--policy`. A line the block lists takes nothing merged into `main` before the day it gives, unless the original carries `backport/include`; any other line starts at its fork point. A page without exactly one readable block stops the run with exit 2. + +Build the binary wherever an exit code matters: `go run` turns any non-zero exit into its own `1`, so under it a check that could not be completed looks the same as one that found something missing. + +Output is written before a push or a publish. Once a write to stdout or stderr fails, a closed pipe included, the run changes nothing more: no push, no GitHub write, no local branch move, and no new pick; a pick already in flight still finishes its rollback. It exits 2 where it would have exited 0, saying on stderr, while it still can, that the output was lost. A confirmation lost after a push or a publish fails the run the same way. + +### run + +Switches the current working tree to `backport-batch/-`, created at `origin/`, and picks onto it one original at a time, in the order they merged into `main`, as one unit each on the branch's first-parent line. A pull request merged into `main` with a merge commit `M` goes on as its own commits, `git rev-list --reverse --topo-order --no-merges M^1..M^2`, each picked with `git cherry-pick -x --signoff`, so each keeps its author, message and sign-offs and gains the `(cherry picked from commit …)` line; the merges that brought `main` into its branch are left out, since `main` already has what they brought. A merge commit then joins the picks to the batch: its first parent is the batch before the original, its second the last pick, and its message is `M`'s with a paragraph of its own, `Backported-from: M`. A pull request squash-merged into `main` goes on as one pick. When any commit of an original conflicts, the pick is aborted, the branch goes back to where it was before that original, and the original is recorded with the commit that failed and its files; the run goes on with the next one. A commit the branch already carries is skipped as empty, and an original none of whose commits changes anything is reported as carried. The tree has to be clean. A local branch of that name is reset to where the run starts; when that drops commits only it has, the run first prints its tip and the `git branch` command that restores them, and so does `--defer`. Signing follows your git configuration; hooks are off for the picks and the merge, so each commit carries its message as git writes it. + +The pull request body goes to stdout, built from the line's own `.github/PULL_REQUEST_TEMPLATE.md`: the originals on the branch, each with how many commits it brought and which of them differ from the commit they were picked from by `git patch-id`, a resolution or a pick git had to fit, the deferred conflicts with the commit that failed and its files, what is parked and why, the skipped pull requests counted by rule with the lists collapsed, the originals' release notes, and two blocks of JSON. An original whose unit differs from it, a pick whose patch-id differs from its commit's or a unit whose net patch-id differs from the original merge's, as when a first commit came out empty because the line already had that change, keeps its release note out of the release-note block: it goes under "Check these notes", with a `git range-diff --creation-factor=999 ^! ^!` for each pick that differs, which pairs the two however much the pick lost, and the `git diff` of the original's merge and of its unit, and the record and the report mark it `changed`. The two blocks of JSON are the [line's record](#the-lines-record-and-reports) in `backport-batch`, which later runs, `check` and `notify` act on, and the run's report in `backport-batch-report`. The title is `fix(backport): batch for , `. A body that would pass GitHub's 65536-byte limit leaves out its longest skipped lists, and the run prints them on stderr instead; one that what it has to carry still puts over the limit is refused before anything is pushed. + +`--onto SHA` continues a batch already pushed instead of starting a new one. SHA has to be the head the remote has for a batch branch of the line right now, read with `git ls-remote`, so a head someone pushed onto since is refused. What that branch carries stays, and only what it does not carry yet is picked on top, so the next push is a fast-forward. `--continue` takes SHA from the open batch pull request, and starts a new batch when none is open, which is what the scheduled run does. + +`--no-workflow-files` is for a token that may not push a change to `.github/workflows/`, which the scheduled run's App token may not. An original that changes anything there is not picked: the body lists it under "Waiting for a maintainer" with those files, and the `backport-batch` block records it with `"workflows": true`, so `check`, `notify` and a run that continues the batch know it waits. It is never a conflict. A run without the flag, a maintainer's with their own token, picks it like any other original, onto the open batch when it continues one. + +A clean pick can still carry only part of its original: git deletes a file the line never had without a word, and leaves alone a file the line lacks. So every path the original modifies or deletes, `M` or `D` in `git diff --name-status --no-renames M^1 M`, is judged at its counterpart on the line: the path itself, or the one a rename `git diff -M` finds between the line's fork point and `M^1` on `main`, between the fork point and the line, or both in turn. A modified path counts as left without effect when its counterpart exists neither before nor after the pick; when the pick leaves an existing file as it was, the file counts as there only when its blob is the original's, binary files included, or when `git merge-file` of the original's preimage, the line's file and the original's postimage merges cleanly back into the line's file. A deleted path counts as left without effect when its counterpart is absent before a pick that changes something, a deletion the line already made being no change of that pick, or still there after it, whatever the pick changed in it; when the original adds that path itself, as when the line made the same rename, it is judged as a modified file against what the original makes of that path. Picks that change nothing carry the original only when the line already has what it does to every file it modifies or deletes, so a change made where its branch merged `main`, which no pick brings, is still missing. What cannot be judged, a mode or type change, content `merge-file` refuses, or a rename git skipped looking for, is shown with the original and never counts against it. An original whose net merge onto the line, `git merge-tree --merge-base=M^1`, leaves something without effect is not tried, and one whose picks do is taken back off the branch: either is parked as partial, listed under "Parked" with those paths, and its release note stays out of the body. A conflict is never called partial. `backport/include` lifts no park. + +Before it tries an original, `run` looks at what the original [builds on](#what-an-original-builds-on) that the branch lacks, in merge order, so what became of each prerequisite in this run is known. A prerequisite the line or the open batch carries, or that this run picked or found empty, counts as there; once earlier picks moved the branch, the original is judged at the branch's head, so a line another unit brought counts too. Of what is left, a direct push, an original rules 2 to 4, the line's start, `backport/skip` or a drop keep out, and one that is itself parked never come: the original is parked, not tried, and listed under "Parked" with what it builds on. In the scheduled mode an original that changes a workflow, whose missing dependencies that never come are only tests or docs and whose workflow lines build on nothing missing, waits for a maintainer instead, with a note saying so. Prerequisites still to come, a conflict, a deferral, a wait for a maintainer, one rule 6 holds, make the original wait: it is listed under "Waiting on another original", recorded with `needs`, the prerequisites of the kind that decides, in the order not on the line, waiting for a maintainer, deferred, rule 6, and tried again by a later run. A reason given with `--defer` comes before all of this, and a partial park before any of it. + +`--defer N[,N] --reason TEXT` takes originals out of the open batch pull request, usually the ones a failing check was pinned on. It builds the batch branch again off `origin/` without their units: while the batch still sits on the line's head, the units before the first one it drops stay as they are, and every later one, a pushed resolution included, is picked again in its own shape, a merge's picks one by one and then the merge with its message. When dropping one leaves a later commit that no longer applies, the run stops and names that commit's original, to defer as well. It adds no new original. It also takes out an original that got `backport/skip` after the batch picked it, which a run never removes on its own and the body lists as still on the branch. The body records each deferred original with the reason in the `backport-batch` block; a run that continues this batch keeps them out, and the next batch tries them again. A batch that carries a merge commit other than an original's, as GitHub's update-branch button makes, is refused, since picking such a merge again would lose what it resolved. When it takes out everything the batch carries, there is nothing left to push, and `--push` closes the batch pull request instead, as [the line's record](#the-lines-record-and-reports) describes. + +`--drop N[,N] --reason TEXT` drops originals from the line: where `--defer` holds one out of this batch, a drop keeps it out of every later batch of the line too, until `--undrop N[,N]` withdraws it. A drop is recorded in the [line's record](#the-lines-record-and-reports), so both need an open batch pull request that carries one, and exit 2 without it; once a batch merges, its drops are carried into the next batch's record. A dropped original the open batch carries is taken off it as `--defer` would, and the rebuild is pushed the same way; any other drop or undrop changes only the record, so the batch stays as it is even when the line moved since. An undropped original is missing until the next run tries it. A drop names the original's merge commit on `main` as well as its number, and a record whose drop does not match what that merge commit merged stops every command with exit 2. An original the line already carries cannot be dropped, and neither can a number that merged into `main` before the line branched. The order is the rules', then the drop: what `backport/skip`, rules 2 to 4 or the line itself decide comes first, with the drop kept on record beside it, and `backport/include` does not lift a drop. The body lists dropped originals under their own heading among the skipped ones, `check` prints a note for each, and `fold` refuses one. + +`--push` pushes the branch, refusing anything but a fast-forward of what the remote has, then opens the draft pull request against the line with `gh pr create --draft`, or updates the open batch pull request with `gh pr edit`, and prints its URL on stderr. On the open batch it first posts the run's report as a comment, so a body never names a report nobody can read; a new batch carries the report in the body it opens with, and the comment follows. Before every write to the pull request it reads the pull request again, and stops with exit 2 once it is merged or closed. When the branch it refuses to push over has no pull request open on it, as a run that stopped between its push and opening the pull request leaves it, the refusal names the `run --onto --push` that continues it. While a batch pull request is open on another branch it refuses, so a line never has two. It never pushes to or edits a batch pull request whose body has no `backport-batch` block either: someone wrote that body by hand, and the batch is theirs to merge or close. After `--defer` alone it replaces the branch, with `--force-with-lease=refs/heads/:`, where head is what `git ls-remote` reads for the branch and has to be the head the rebuild started from: a commit pushed since is never dropped, by the tool's check or, if one lands between that check and the push, by the remote. A record that says the batch is being closed is acted on before anything else, and only by `run --push`. + +### check + +Exits 1 and prints the URL of every pull request the rules take that is neither on the line nor on the open batch pull request, 0 when there is none, and 2 when it cannot tell. A pull request that the [line's record](#the-lines-record-and-reports) lists as deferred, a conflict or one taken out with `--defer`, prints as a warning and does not fail the check: deferring is a maintainer's call. That holds once the batch that recorded it merged or closed too. So does one the open batch lists as waiting for a maintainer because it changes workflows; once that batch is gone, nothing lists it any more, and it is missing. One a maintainer dropped from the line prints as a note, `#N is dropped from on #M ()`. + +`--cut` makes it the gate before a patch release or an rc is cut from a line. A cut tags the line, so a pull request that is only on the open batch pull request fails it too, with one line each: `#N is only on open batch PR #M, merge it before the cut`. One that waits there for a maintainer fails it as well, since nobody decided to leave it out, also when it is all the batch has left: bring it over, or take it out with `run --defer` and a reason. Everything else is as without it, and a cut that passes says `no change the policy takes is missing before the cut`. The scheduled run checks without `--cut`, since its batch is open by design. + +An original with `backport/skip` that the open batch picked before the label came prints a warning in either mode, naming the batch and `run --defer`, which takes it out; it fails neither. + +Every other original the policy takes that neither the line nor the open batch carries is decided in merge order, as [`run`](#run) decides it, with the open batch's found picks counting as there and the mode the open record saved, the scheduled run's when no batch is open, whose workflow waits on a closed record wait on nothing any more, so the original is judged as the scheduled run judges it: deferred for a reason, a warning; parked, a note naming what it builds on; in the scheduled mode a workflow original whose tests alone build on what never comes, waiting as the open batch lists it, or missing with none; and one that waits on other originals by the prerequisite that decides it: missing, which fails both modes, waiting for a maintainer, which warns and fails `--cut`, deferred, which warns, or held by rule 6, a note. A wait on one that waits itself inherits what decides that one. + +A unit on the open batch that leaves part of its original without effect, judged as [`run`](#run) judges a pick, at the unit's own first parent and whatever its original's rule, label or drop, prints a warning naming what it leaves out, and fails `--cut` ahead of any skip, drop or stale warning: take it out with `run --defer`. An original that is parked as partial prints as a note, `#N is parked: only part of it applies`, and fails neither. That includes one the open record parks as partial that the net merge at the line's head finds whole, since `run`'s picker found it after the picks before it: `check` and the operations that only change the record keep it parked while its net merge onto what the batch carries now still leaves something without effect, and call it missing once that went, as when the pick that made it partial was taken off. A park only the commit-by-commit replay sees, which no net merge shows, reads as missing in `check` until the next run. + +### fold + +Checks a hand-made resolution of a deferred conflict before it is pushed onto the batch, in the shape the run gives an original. For a merged pull request `--commit` is a merge whose first parent is the head of the open batch pull request and whose message names the original in exactly one `Backported-from:` trailer; its second parent ends a straight line from that head of picks of the pull request's own commits, in their order, each ending in the `(cherry picked from commit …)` line of the commit it came from, none claiming another commit of the same original, a commit of another pull request never among them. For a squash-merged one it is a single commit on that head whose `(cherry picked from commit …)` line names the original's commit on `main`. An original parked for what it builds on folds like any other when the resolution is complete. Either has to change something, and only files the original changes or the paths a rename on `main` or on the line gave them, and has to leave nothing the original modifies or deletes without effect, judged as [`run`](#run) judges a pick: a resolution that ports what the line has and leaves out what it lacks is refused, since such a port goes to the line as a pull request of its own. The [conflict task](../../docs/release/backport-tasks/resolve-conflict.md) gives the commands. fold prints `ok` and exits 0, or prints why not and exits 1. It never commits or pushes; push one checked resolution at a time, since the next one has to sit on the new head. + +### verify + +Holds every unit of a batch to the shape fold checks for one, the clean picks as well as resolutions: it walks the batch's first-parent line from `origin/` to `--head`, or to the head of the open batch pull request, and requires each unit to be one original, merged into `main` after the line branched, in that shape, and no original twice. A commit that carries no original fails it, and so does a merge of the line into the batch, and a unit that leaves part of its original without effect, judged as [`run`](#run) judges a pick. It prints one line per unit, and exits 0 when all pass, 1 when one does not, and 2 when it cannot tell. With `--head` it reads git alone, nothing from GitHub. fold runs only where someone resolved a conflict and chose to run it; [`pr-labeler.yaml`](../../.github/workflows/pr-labeler.yaml) runs verify on every push to a batch pull request, from a build of `main`, with the batch head fetched as data. + +### notify + +Reads the [line's record](#the-lines-record-and-reports) first, as the other commands do, and exits 2 when it cannot read it or when it says the open batch is being closed, with a batch open or not. Then it reads the open batch pull request of the line, trusted as described below, and prints one line for each thing that waits on it: a batch open for three days or more, the shortest gap between two scheduled runs, so one the previous run already saw; the conflicts it deferred; and the originals waiting for a maintainer because they change workflows. Nothing open prints nothing. + +An original the record has wait on others is listed once, as `#M, after #F`, where what decides its wait is listed: after a deferred conflict with the conflicts, after a workflow wait with the waits; one waiting on what is missing or held by rule 6 is not listed. A unit on the batch that carries only part of its original is listed apart, to be taken out before the cut. + +Each park the record of the open batch holds is named once. `run` marks a park `announced` when the line's record it found, open or closed, holds the same park announced: the same merge, kind, prerequisites, commits and files; a park that changed is news again. `notify` lists the parks not yet marked, and with `--push`, once the comment is written, marks them in the record with `gh pr edit --body-file`, only while the pull request is open and its body still carries the record `notify` read. A mark that fails after the comment exits 2, and the next `notify` names those parks once more. With no batch open nothing is named, and the next batch's first `notify` names what it parks. + +With `--push` it writes the same into one comment on the batch pull request: the conflicts, each to be resolved as the [conflict task](../../docs/release/backport-tasks/resolve-conflict.md) describes, and the originals that wait because they change workflows. + +The comment starts with `` and is one per pull request: a later run edits it in place rather than adding another, and once nothing waits it says so. Only a comment whose author the batch trusts counts as it, so one someone else wrote with the same first line is neither edited nor believed. It mentions `--mention`, an `org/team` or a login, with or without `@`, only while something waits. A failed batch CI is not among what it reports: the run has no trigger on the batch's CI finishing. + +### report + +Prints a report a batch pull request keeps: the one its body carries, or the one `--id` names. It reads the report comments the batch trusts and falls back to the body, recomputes the report's ID from what it says, and exits 2 when a trusted comment does not match its ID, when a report says anything a run does not write or is for another line than the pull request's, or when the pull request keeps no such report. A report comment counts only when its author is one the batch trusts with a record, so anyone else's comment, whatever ID it carries, is not read. It prints what the classification was made of, whether the pull request's head or body shows the report was published, which it calls unconfirmed when neither does, and one line per original with its category and what the report recorded about it; `--json` prints the report as stored. A report whose comment the run never got to post is printed from the body, with a note that the next `run --push` posts it, or, on a merged or closed batch, that it is kept in the body only. It writes nothing. It reads GitHub, and for a report that keeps drops also the clone's history, without fetching: each drop is bound to `main` as the record's drops are, over the heads of `main` and the line the report was made from, so a drop of an original the report classified has to name that original's merge, and any other a merge of its number on `main`'s first-parent line. A clone without those heads exits 2, asking for a fetch. + +### lines + +Prints the release lines the batch runs for, newest first: of the `release-X.Y` branches on `origin`, the newest that have a stable `vX.Y.Z` tag there, as many as `released-lines` in the policy block says, two when it says nothing, and every branch newer than the newest of them. The tags are read with `git ls-remote`; a tag with a pre-release suffix does not count. `run`, `check` and `fold` refuse any other line, and rule 6 holds each line to the next newer one among them. + +## Rule 4 and the API review gate + +A change to the API is held back only when the [API review gate](../../.github/workflows/api-review-gate.yaml) would call it sizeable. The gate is asked whenever an original changes something it parses: `pkg/apiserver/apiserver.go`, an ApplicationDefinition under `packages/system/*-rd/cozyrds/`, or a `.yaml` or `.yml` file under `packages/` or `internal/` that holds `CustomResourceDefinition` or `APIService` before or after the merge. An edit to the Go types under `api/` alone reaches none of them, so the gate would see no change. The batch calls the gate's own code, `apigate.LoadSnapshot` and `apigate.Classify` from `internal/apigate`, on the trees of the original's first parent and of its merge commit. It reads only what the gate reads, from `git ls-tree` and `git cat-file` into a temporary directory, so no attribute or export rule changes what the gate sees. A reworded description or a new optional field passes; a new or removed group or resource, or a schema change that can reject what the old schema accepted, does not. Migrations, `targetVersion` and CRDs keep their own checks: the gate sees only first-party `cozystack.io` CRDs, and only their sizeable changes, while a vendored operator's CRD is just as unsafe in a patch. + +The CRD check works document by document. In every changed manifest, a YAML, JSON or `.tpl` file or anything under `templates/` or `crds/`, outside `tests/` and `testdata/`, every document that names `CustomResourceDefinition` is read as YAML, which takes JSON too, and the CRDs among them are compared between the parent and the merge by `metadata.name`, compact JSON and quoted keys included. The change counts only when one was added, removed or edited, so an edit to the DaemonSet beside a CRD in one manifest does not, and neither does a sentence or a `lookup` call that merely names the kind. A document that declares `kind: CustomResourceDefinition` on a line of its own but cannot be read as an object, a CRD behind a Helm template guard for one, is compared by its text, so the check fails closed on it, and so does a `List` that holds a CRD. + +## Maintainer overrides + +`run`, `check` and `fold` read the merged pull requests that carry `backport/include` or `backport/skip`, through GitHub search, which answers at most 1000 per label; a listing that long is an error rather than a complete answer. `backport/skip` keeps a pull request out whatever the rules say, and wins over `backport/include`, which lifts rules 2 to 4 and nothing else: what the line already carries and, on the older line, what the newer one does not carry yet still decide. The batch pull request lists every overridden original and what became of it. Adding a label takes triage access to the repository, which is the trust the labels rest on; who added one is not checked. + +## What counts as already there + +An original is on a line when any of these holds, and the batch does not pick it again: + +- its merge commit is reachable from the line; +- picks on the line name its merge commit, or every commit of its own, in the `(cherry picked from commit …)` line git appended to them; +- picking it onto the line would change nothing. + +A pick is known by the line git appends: the last `(cherry picked from commit …)` line of the message's last paragraph, with nothing after it but trailers such as a sign-off. A picked commit keeps its message, and a batch merge carries the original's merge message, so whatever else a message says was written by someone the batch does not answer for: a line in it naming an original, as an `-x` line, a `Backported-from:` trailer or `Backport of #N`, does not count. On commits from before the policy's `batch-only` day it does, since those record the hand backports and earlier batches: + +- a `(cherry picked from commit …)` line anywhere in the trailer block naming its merge commit or, across commits, every commit of its own; +- a `Backported-from:` trailer naming its merge commit; +- `Backport of #N`, which is what a hand backport merged as one commit carries. + +An original is on the open batch pull request when its commits picked there show it the same way. The same rules on the newer line decide rule 6. + +Only the line's own commits count, the ones after the point where it branched from `main`, never a pull request against it: an open backport pull request, its title and its body are anyone's to write. The tool trusts the line's history because only maintainers merge into `release-*`; if that ever changes, a commit that names an original without carrying all of it would hide the rest. The batch pull request counts only when it comes from a `backport-batch/-` branch of this repository, not a fork, and was opened by the bot the scheduled batch runs as, the exact login `BACKPORT_BATCH_BOT` names, `cozystack-ci[bot]` when it is unset and no bot when it is set empty, or by someone whose permission on the repository GitHub reports as write or admin, and only at the head GitHub reports for it. No other bot counts, GitHub Actions' own included, since anything holding a workflow's token writes as it. So a maintainer's run by hand continues the scheduled batch with nothing set, rather than taking its pull request for a look-alike and opening a second one. The notify comment is trusted the same way. A permission GitHub does not answer stops the command with exit 2 rather than count the pull request or the comment out, which would open a second of either. The author association is not enough: an organization member or an invited collaborator can hold read access only. With more than one such pull request open the tool refuses to go on. + +Titles and bodies are read from the merge commits on `main`, which hold them as a maintainer merged them; the live pull request stays editable by its author. + +## What an original builds on + +An original the policy takes can build on code its line does not have: another pull request merged into `main` after the line branched that the line never got, or a commit pushed to `main` directly. For each original the policy takes that neither the line nor the open batch carries, `run` reads what it builds on from git alone, in two ways: + +- A file it modifies or deletes whose counterpart, as [`run`](#run) follows renames, the line does not have is named by the first-parent commit on `main` that added it since the line branched: `git --literal-pathspecs log --first-parent --diff-merges=first-parent --no-renames --diff-filter=A -1 ..M^1 -- `. A file nothing added since the fork point is shown with the original, since no other pull request brought it. +- A line it removes or changes in a file the line has is given by `git blame --porcelain -w`, at `M^1` named by its full commit, to a commit, which counts through the first-parent commit on `main` that brought it: each commit of `main`'s first-parent line since the fork point brings itself and every commit of the range reachable from its other parents that no earlier one brought. A commit from before the fork point, which the line has, and the original's own count for nothing. The commit counts only while one of its lines, with its edges trimmed and nothing else, is absent from the line's version of the file, so a hand backport under another commit clears it. A file the line already has as the original makes it, the same blob or a clean `git merge-file` back into the line's file, builds on nothing. + +Lines a tool wrote are not blamed: a generated file whole, `zz_generated*`, one with a `Code generated … DO NOT EDIT` marker in its first 100 lines, `go.sum` and the package-manager lock files, and in an ApplicationDefinition under `packages/system/*-rd/cozyrds/` the keys `hack/update-crd.sh` writes, found by their indentation. Controller-gen CRDs and `values.schema.json` are blamed like any other file. Each `git log`, `git diff` and `git blame` the detector and the rename detection run has two minutes, and rename detection that runs out of time counts as skipped, and an original has at most 256 files, missing or blamed, 20 000 blamed lines and 8 MiB per file read for it. Evidence it cannot read, past one of those bounds, a binary file, a symlink, a submodule, a commit blame names that did not come through `main`, a path that is not UTF-8, or a rename git skipped looking for, is shown with the original, whatever becomes of it, under its line in the body and in the report's `diag`. Output of git the tool cannot read whole stops it with exit 2, and is never taken for an absent dependency. A dependency carried only by lines an original adds is not seen. `run` prints how long reading the line took on stderr. What follows from a dependency, a park or a wait, is in [`run`](#run) and [`check`](#check). + +## The line's record and reports + +The line's record is the `backport-batch` block of its newest batch pull request: the newest pull request against the line from a `backport-batch/-` branch of this repository, opened by an author the batch trusts as above, whether it is open, merged or closed. `run`, `check`, `fold` and `notify` find it in GitHub's list of the line's pull requests, newest first, reading at most ten pages of 100. A batch pull request a person opened without the block is passed over. A block whose author the batch does not trust, a bot's batch without its block, a block that cannot be read whole, a closed record newer than the open batch, or ten pages with no record stop the command with exit 2, naming the pull request, rather than fall back to an older record. + +The record is written only while its pull request is open: a merged or closed batch pull request is never edited or commented on again. What it recorded keeps counting, so a conflict or a deferral a merged batch recorded still prints as a warning. A workflow original it listed as waiting is missing, since no open batch lists it. A run that picks nothing while no batch is open has nowhere to write: it prints the body, says that its classification is not retained, and exits 0. + +The record is only as trustworthy as the body it sits in. Anyone with write access can edit any body, the bot's included, and neither the bot's authorship nor anything in the block proves who edited it last. A hand edit that leaves a readable record is believed; one that breaks it stops every command with exit 2, naming the pull request. A reason or a file name in the record counts only in the form a run writes it, one line with no control, zero-width or bidi character, so text someone typed into the body never reaches a terminal, a body or a comment as they typed it. When the newest batch pull request is deleted and no later one exists, nothing shows it was there: the older record governs, and what was recorded since is lost. + +The record holds only what later commands act on. Version 3, which this tool writes, adds what is parked and why, with the merge commit each park is bound to, the units on the batch that do only part of their original, the picks that differ from theirs, and what each wait on another original waits on; it reads versions 1 to 3, and a tool that reads only 1 and 2 refuses version 3 with exit 2. Every run that classifies the line also makes a report, one line of JSON in a `backport-batch-report` block: every original merged into `main` since the line branched in exactly one category, picked, missing, deferred with what it was deferred for, or skipped with the rule that skipped it, each drop the record keeps with the merge commit it is bound to, its reason and the batch pull request that recorded it, the commits on `main` that merged no pull request, the labels, and what the classification was made of: the heads of `main`, the line and the newer line, the policy, the batch head it describes, the tool's commit, the Actions run and the flags. Its ID is a hash of all that but the time and the run, so two runs that find the same make the same report, and it names no pull request, so a new batch's report is whole before GitHub numbers the pull request. The body carries the latest report beside the record, and a comment on the open batch pull request keeps each one: `` and the same block, folded away. A report already posted is not posted again, and the tool never edits or deletes such a comment, so a report the next run replaces in the body is still read back by `report`, also after the batch merged. A comment that looks like one but whose author the batch does not trust is not read. When a run stops after writing the body but before posting its comment, the next `run --push` on the open batch posts that report first, byte for byte; once the batch is closed nothing is written to it, and the report stays in its body. A run that picks nothing while no batch is open keeps no report. + +A `--defer` that leaves the batch carrying nothing closes it, and writes everything while the pull request is still open: the report comment, then the body, whose record keeps the deferrals and says the batch is closing, with its number, branch and the head the rebuild started from. It then reads the pull request and the branch again, closes the pull request while both are at that head, and deletes the branch with `--force-with-lease` on it, printing `closed `. The next batch tries what was deferred again. A close that stops part way is finished by the next `run --push`, before it does anything else: it closes and deletes when the pull request is open at the frozen head, deletes the branch when the pull request is closed and the branch still at that head, and goes on as usual once both are gone. A run that finishes a close stops there, with exit 0, or with exit 2 when it was asked for `--defer`, `--drop` or `--undrop`, which it does not apply. It never takes a head it did not freeze: with the branch moved, it stops with exit 2 and names both heads. `run` without `--push`, `check` and `fold` stop with exit 2 while the pull request is still open; once it is closed they go on, warning about a branch the close left, and `notify` says nothing. A closed pull request is never written to, so its record says it was closing for good, and a closed pull request whose branch is gone counts as closed. + +One way for the branch to move is a new batch of the same day: it reuses the branch name, and if its push succeeds and opening its pull request fails, the closed batch is still the newest record while its branch now holds the new batch. The next run stops on it, naming the branch, and so does `--onto` with its head. Check what it carries before deleting it with `git push origin --delete backport-batch/-`: the next run picks again what the tool put there from the line, but not a commit someone pushed onto it, such as a resolved conflict. Separate writes to GitHub are not atomic: the re-reads and the leases refuse a race they see, but cannot prevent one. + +## What CI verifies + +The tool does not build or test anything. CI on the batch pull request runs the line's own build and tests against what was picked, and `verify` against its shape, and a maintainer reviews and merges it. A deferred conflict waits for the next batch unless someone resolves it, checks the resolution with `fold` and pushes it, and then CI runs again. + +## Untrusted text + +Titles, release notes and file names in the body come from whoever opened the originals, and a reason from whoever ran `--defer`. A title, a reason or a file name goes into a code span whose fence no backtick inside can close, and the release notes go into the `release-note` block with every run of three backticks or tildes defused, so GitHub acts on no mention, reference, link or HTML in them. Inside that block, in case a note is copied out of it, links lose any target outside this repository, and closing keywords, cross-repository references and mentions have their `@`, `#` and `://` swapped for fullwidth signs, which act on nothing however the backticks around them pair up. The record and the report are one line of JSON each, whose encoding leaves no newline, `<`, `>` or `&` in them, so nothing in a file name or a reason ends their block or opens HTML, and a report comment names no one: numbers are bare, and its only text outside the block is the line, the date and the report's ID. Zero-width, bidi and control characters are dropped first, and everything the tool prints passes the same filter, so nothing it relays can drive a terminal. Commit messages are read through `git cat-file --batch`, which gives each object's length, and end at their first NUL as `git log` shows them, so a message cannot pass for a second commit or hide a trailer from a reader of the log. Every value handed to git comes after `--end-of-options` or `--`, refs pass `git check-ref-format`, SHAs have to be 40 hex digits, and nothing runs through a shell. diff --git a/cmd/backport-batch/apisurface.go b/cmd/backport-batch/apisurface.go new file mode 100644 index 000000000..6966bce74 --- /dev/null +++ b/cmd/backport-batch/apisurface.go @@ -0,0 +1,188 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package main + +import ( + "fmt" + "os" + "path" + "path/filepath" + "slices" + "strconv" + "strings" + + "github.com/cozystack/cozystack/internal/apigate" +) + +// Rule 4's API clause is the API review gate's own verdict: the same +// apigate.LoadSnapshot and apigate.Classify that cmd/api-gate runs in +// api-review-gate.yaml, on the trees of the original's first parent and of its +// merge, so a change the gate passes as additive or descriptive is no reason to +// hold a fix back. + +const ( + apiserverGo = "pkg/apiserver/apiserver.go" + // apigate reads an ApplicationDefinition wherever this matches, whatever + // the file holds. + cozyRDGlob = "packages/system/*-rd/cozyrds/*.yaml" + // apigate skips a YAML file larger than this; reading it would be wasted. + apiFileLimit = 8 << 20 +) + +// apiYAMLRoots hold all YAML apigate.LoadSnapshot parses: the +// ApplicationDefinitions and every first-party CRD or APIService. +var apiYAMLRoots = []string{"packages", "internal"} + +// apiInputs are what apigate.LoadSnapshot reads of a checkout: the YAML roots +// and the apiserver's storage registrations. +var apiInputs = append(slices.Clone(apiYAMLRoots), apiserverGo) + +// apiMarkers are mightBeAPIManifest's: apigate parses no other YAML file that +// holds neither. +var apiMarkers = []string{"-e", "CustomResourceDefinition", "-e", "APIService"} + +var apiSnapshots = map[string]apigate.Snapshot{} + +// apiSnapshot is apigate's snapshot of commit, built from a temporary tree +// holding only what it reads. The blobs come from ls-tree and cat-file rather +// than a checkout or git archive: no attribute filters or export rules apply, +// and a symlink is never followed out of the tree. +func apiSnapshot(commit string) (apigate.Snapshot, error) { + if snap, ok := apiSnapshots[commit]; ok { + return snap, nil + } + out, err := git(append([]string{"ls-tree", "-r", "-z", "-l", "--full-tree", "--end-of-options", commit, "--"}, apiInputs...)...) + if err != nil { + return nil, err + } + paths := map[string]string{} + var blobs []string + for _, entry := range splitNUL(out) { + meta, name, ok := strings.Cut(entry, "\t") + f := strings.Fields(meta) + if !ok || len(f) != 4 { + return nil, fmt.Errorf("ls-tree %.12s: unreadable entry %q", commit, entry) + } + mode, kind, blob := f[0], f[1], f[2] + size, _ := strconv.Atoi(f[3]) + ext := path.Ext(name) + switch { + case kind != "blob" || (mode != "100644" && mode != "100755"): + case name != apiserverGo && ext != ".yaml" && ext != ".yml": + case size > apiFileLimit: + case checkSHA(blob) != nil || !filepath.IsLocal(filepath.FromSlash(name)): + return nil, fmt.Errorf("ls-tree %.12s: unreadable entry %q", commit, entry) + default: + paths[name] = blob + blobs = append(blobs, blob) + } + } + contents, err := readObjects(dedupe(blobs), "blob") + if err != nil { + return nil, err + } + dir, err := os.MkdirTemp("", "backport-batch-api-") + if err != nil { + return nil, err + } + defer func() { _ = os.RemoveAll(dir) }() + for name, blob := range paths { + file := filepath.Join(dir, filepath.FromSlash(name)) + if err := os.MkdirAll(filepath.Dir(file), 0o700); err != nil { + return nil, err + } + if err := os.WriteFile(file, contents[blob], 0o600); err != nil { + return nil, err + } + } + snap, err := apigate.LoadSnapshot(dir) + if err != nil { + return nil, fmt.Errorf("the API at %.12s: %w", commit, err) + } + apiSnapshots[commit] = snap + return snap, nil +} + +// readsAPI reports whether the change reaches anything apigate.LoadSnapshot +// parses at either end. A change to anything else leaves both snapshots alike, +// so the gate is not asked. A binary file is searched as well, since apigate +// reads one like any other; a file over its size limit is still asked about, +// which costs a snapshot and changes no verdict. +func readsAPI(parent, merge string, changes []fileChange) (bool, error) { + var yamls []string + for _, c := range changes { + p := c.path + if p == apiserverGo { + return true, nil + } + if ext := path.Ext(p); ext != ".yaml" && ext != ".yml" { + continue + } + if !slices.ContainsFunc(apiYAMLRoots, func(root string) bool { return strings.HasPrefix(p, root+"/") }) { + continue + } + if rd, _ := path.Match(cozyRDGlob, p); rd { + return true, nil + } + yamls = append(yamls, p) + } + for _, rev := range []string{parent, merge} { + found, err := grepFiles(rev, yamls, apiMarkers...) + if err != nil || len(found) > 0 { + return len(found) > 0, err + } + } + return false, nil +} + +// sizeableAPIChange says why the API review gate would call the original's +// change to the API sizeable, or "" when it would not. +func sizeableAPIChange(o *original) (string, error) { + parent, err := resolve(o.merge + "^1") + if err != nil { + return "", err + } + base, err := apiSnapshot(parent) + if err != nil { + return "", err + } + head, err := apiSnapshot(o.merge) + if err != nil { + return "", err + } + findings := apigate.Classify(base, head) + if len(findings) == 0 { + return "", nil + } + why := fmt.Sprintf("%s: %s", findings[0].Category, findings[0].Detail) + if len(findings) > 1 { + why += fmt.Sprintf(", and %d more", len(findings)-1) + } + return why, nil +} + +func dedupe(list []string) []string { + seen := map[string]bool{} + var out []string + for _, s := range list { + if !seen[s] { + seen[s] = true + out = append(out, s) + } + } + return out +} diff --git a/cmd/backport-batch/assemble.go b/cmd/backport-batch/assemble.go new file mode 100644 index 000000000..7f5529bcd --- /dev/null +++ b/cmd/backport-batch/assemble.go @@ -0,0 +1,975 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package main + +import ( + "errors" + "fmt" + "os" + "slices" + "strings" + "time" +) + +// pick is the outcome of picking one original onto the batch branch. +type pick struct { + v *verdict + status string // picked, conflict, empty, held out by --defer, or waiting for a maintainer + commit string + files []string + // failed is the commit whose pick conflicted. + failed string + // needs are the originals still to come it waits on. + needs []int + // more counts the conflicting files a recorded conflict no longer names. + more int + reason string +} + +// workflowsDir is where GitHub reads workflows from. A token without the +// workflows permission, a GitHub App's among them, cannot push a commit that +// changes anything under it. +const workflowsDir = ".github/workflows/" + +// workflowFiles lists the workflow files the commits change, each against its +// parent: a push carries every pick, so a change one commit makes and a later +// one takes back is in it although the pull request's merge changes nothing +// there. +func workflowFiles(commits []string) ([]string, error) { + if len(commits) == 0 { + return nil, nil + } + out, err := gitInput(strings.Join(commits, "\n")+"\n", "diff-tree", "--stdin", "--no-commit-id", "--name-only", "-r", "-z", "--no-renames") + if err != nil { + return nil, err + } + var files []string + for _, f := range splitNUL(out) { + if strings.HasPrefix(f, workflowsDir) && !slices.Contains(files, f) { + files = append(files, f) + } + } + return files, nil +} + +func batchBranch(l line, date time.Time) string { + return "backport-batch/" + l.branch() + "-" + date.Format("20060102") +} + +func (a *app) run(args []string) int { + fs := a.policyFlags("run") + lineArg := fs.String("line", "", "release line, release-X.Y") + onto := fs.String("onto", "", "head of the pushed batch branch to continue") + cont := fs.Bool("continue", false, "continue the open batch pull request, or start a batch when none is open") + dateArg := fs.String("date", "", "batch date, YYYY-MM-DD (default: today, UTC)") + deferArg := fs.String("defer", "", "originals to take out of the open batch, N[,N]; rebuilds it without them") + dropArg := fs.String("drop", "", "originals to drop from the line, N[,N]; recorded on the open batch, and taken off it") + undropArg := fs.String("undrop", "", "originals whose drop to withdraw, N[,N]") + noWorkflows := fs.Bool("no-workflow-files", false, "leave an original that changes "+workflowsDir+" to a maintainer, for a token that cannot push one") + reasonArg := fs.String("reason", "", "why --defer takes them out or --drop drops them, recorded in the batch body") + push := fs.Bool("push", false, "push the branch and open or update the draft batch PR") + if err := parse(fs, args); err != nil { + return 2 + } + l, err := parseLine(*lineArg) + if err != nil { + return a.fail(err) + } + date := a.now().UTC() + if *dateArg != "" { + if date, err = time.Parse(time.DateOnly, *dateArg); err != nil { + return a.fail(fmt.Errorf("--date %q is not YYYY-MM-DD", *dateArg)) + } + } + if *onto != "" { + if err := checkSHA(*onto); err != nil { + return a.fail(fmt.Errorf("--onto: %w", err)) + } + } + var deferred, drops []int + reason, ops := "", 0 + for _, op := range []string{*deferArg, *dropArg, *undropArg} { + if op != "" { + ops++ + } + } + switch { + case ops > 1: + return a.fail(errors.New("--defer, --drop and --undrop each change the open batch pull request on their own; give one")) + case *dropArg != "" || *undropArg != "": + if *onto != "" || *cont || *dateArg != "" { + return a.fail(errors.New("--drop and --undrop change the open batch pull request; each takes no --onto, --continue or --date")) + } + if *undropArg != "" && *reasonArg != "" { + return a.fail(errors.New("--undrop takes no --reason")) + } + list := *dropArg + *undropArg + if drops, err = parseNumbers(map[bool]string{true: "--drop", false: "--undrop"}[*dropArg != ""], list); err != nil { + return a.fail(err) + } + if reason = capped(oneLine(clean(*reasonArg, false)), titleLimit); *dropArg != "" && reason == "" { + return a.fail(errors.New("--drop needs a --reason, which the line's record keeps")) + } + case *deferArg != "" || *reasonArg != "": + if deferred, reason, err = parseDefer(*deferArg, *reasonArg); err != nil { + return a.fail(err) + } + if *onto != "" || *cont || *dateArg != "" { + return a.fail(errors.New("--defer rebuilds the open batch pull request; it takes no --onto, --continue or --date")) + } + case *cont && (*onto != "" || *dateArg != ""): + return a.fail(errors.New("--continue reads the batch to continue from the open batch pull request; it takes no --onto or --date")) + } + if err := cleanTree(); err != nil { + return a.fail(err) + } + if err := fetch(); err != nil { + return a.fail(err) + } + started := time.Now() + b, err := a.prepare(l) + if err != nil { + return a.fail(err) + } + if goOn, code := a.resumeClose(b, *push, deferred != nil || drops != nil); !goOn { + return code + } + if err := b.analyze(); err != nil { + return a.fail(err) + } + // The scheduled job has half an hour for every line; this says where it + // goes. + _, _ = fmt.Fprintf(a.stderr, "prepared %s in %s, %s of it judging partial units and what originals build on\n", l.branch(), time.Since(started).Round(time.Millisecond), b.detecting.Round(time.Millisecond)) + if drops != nil { + return a.redrop(b, drops, reason, *undropArg != "", *push) + } + if deferred != nil { + return a.rebuild(b, deferred, reason, *push) + } + if *cont && b.pr != nil { + *onto = b.prHead + } + + branch, start := batchBranch(l, date), b.lineHead + var carried *history + if *onto != "" { + if branch, err = ontoBranch(l, *onto, *dateArg != "", branch); err != nil { + return a.fail(err) + } + if carried, err = readPicks(*onto, b.lineHead, b.textUntil); err != nil { + return a.fail(err) + } + start = *onto + // The batch keeps the date it was opened under, in its title too. + if date, err = branchDate(branch); err != nil { + return a.fail(err) + } + } + if err := checkBranch(branch); err != nil { + return a.fail(err) + } + // Continuing the open batch keeps out what was deferred from it by hand; + // a new batch tries those again. + held := map[int]deferredEntry{} + if carried != nil && b.src.open && b.pr.Head.Ref == branch { + held = b.src.rec.deferred() + } + if err := a.warnReset(branch, start); err != nil { + return a.fail(err) + } + if _, err := git("switch", "--quiet", "--no-track", "-C", branch, "--end-of-options", start); err != nil { + return a.fail(err) + } + + r := newReport(b) + r.opts = runOptions{NoWorkflowFiles: *noWorkflows, Mode: modeNew} + // A drop is a decision about the line, not about one batch: a new batch + // keeps the ones the closed batch recorded. + r.dropped = b.src.rec.dropped() + if carried != nil { + r.opts.Mode = modeContinue + if r.stale, err = keptOut(b, carried); err != nil { + return a.fail(err) + } + } + // cls is what each original became in this run, to an original that + // builds on it; the rules decide the rest. + mode := analysisMode{noWorkflowFiles: *noWorkflows} + cls := map[*verdict]edgeClass{} + classOf := func(f *verdict) edgeClass { + if c, ok := b.ruleClass(f); ok { + return c + } + if c, ok := cls[f]; ok { + return c + } + return edgeMissing + } + for _, v := range b.qualifying() { + on := false + if carried != nil { + if on, err = b.onBranch(carried, v); err != nil { + return a.fail(err) + } + } + switch { + case on: + r.onBranch = append(r.onBranch, v) + cls[v] = edgeSatisfied + continue + case held[v.o.number].Reason != "": + r.held = append(r.held, pick{v: v, status: "held", reason: held[v.o.number].Reason}) + cls[v] = edgeDeferred + continue + case v.onBatch != "": + v.rule, v.reason = ruleOnLine, fmt.Sprintf("on the open batch pull request #%d", b.pr.Number) + r.skipped[ruleOnLine] = append(r.skipped[ruleOnLine], v) + continue + } + if v.partial != nil { + // Judged at the line's head; what the batch picked since may + // supply what it lacked there. + if err := a.partialAtHead(b, v); err != nil { + return a.fail(err) + } + if v.partial != nil { + r.parked = append(r.parked, v) + cls[v] = edgeNever + continue + } + } + if len(v.deps) > 0 { + kind, err := a.dependsAt(b, r, v, mode, classOf) + if err != nil { + return a.fail(err) + } + if kind != edgeSatisfied { + cls[v] = kind + continue + } + } + if *noWorkflows { + files, err := workflowFiles(v.commits) + if err != nil { + return a.fail(err) + } + if len(files) > 0 { + r.waiting = append(r.waiting, pick{v: v, status: "waiting", files: files}) + cls[v] = edgeWorkflow + continue + } + } + p, err := a.pickUnit(v, func(base, head string) ([]string, error) { + omitted, diag, err := b.omittedEffects(v, base, head) + v.addDiag(diag...) + return omitted, err + }) + if err != nil { + return a.fail(err) + } + switch p.status { + case "partial": + v.partial = p.files + v.park = &parkedEntry{Original: v.o.number, Merge: v.o.merge, Kind: parkPartial, Files: sortedClean(p.files)} + r.parked = append(r.parked, v) + cls[v] = edgeNever + case "picked": + r.onBranch = append(r.onBranch, v) + cls[v] = edgeSatisfied + case "conflict": + r.deferred = append(r.deferred, p) + cls[v] = edgeDeferred + case "empty": + v.rule, v.reason = ruleOnLine, "the earlier picks already carry it" + r.skipped[ruleOnLine] = append(r.skipped[ruleOnLine], v) + } + } + if *onto != "" { + head, err := resolve("HEAD") + if err != nil { + return a.fail(err) + } + descends, err := isAncestor(*onto, head) + if err != nil { + return a.fail(err) + } + if !descends { + return a.fail(fmt.Errorf("%.12s does not descend from --onto %.12s", head, *onto)) + } + if err := b.markPartial(r, carried.head); err != nil { + return a.fail(err) + } + } + return a.finish(b, r, branch, date, *push, false) +} + +// dependsAt decides, from what v builds on that the branch lacks, whether +// the run leaves it out: waiting for a maintainer in the scheduled mode +// when only tests or docs build on what never comes, parked when anything +// else never comes, or waiting on prerequisites still to come. What is +// there, the line's, the batch's, or what this run picked or found empty, +// counts for nothing; once earlier picks moved the branch, v is judged at +// its head. It returns what v became to an original that builds on it, +// edgeSatisfied when the run goes on to pick it. +func (a *app) dependsAt(b *batch, r *report, v *verdict, mode analysisMode, classOf func(*verdict) edgeClass) (edgeClass, error) { + deps := v.deps + head, err := resolve("HEAD") + if err != nil { + return 0, err + } + if head != b.lineHead { + if deps, err = b.depsAt(v, head); err != nil { + return 0, err + } + } + never, pending := edges(deps, classOf) + primary, err := workflowPrimary(mode, v, never, pending) + switch { + case err != nil: + return 0, err + case primary: + files, err := workflowFiles(v.commits) + if err != nil { + return 0, err + } + v.addDiag(testsOnly(v, never, b.line)) + r.waiting = append(r.waiting, pick{v: v, status: "waiting", files: files}) + return edgeWorkflow, nil + case len(never) > 0: + v.park = dependencyPark(v, never) + r.parked = append(r.parked, v) + return edgeNever, nil + case len(pending) > 0: + class, needs := strongest(pending) + r.needs = append(r.needs, pick{v: v, status: "waiting", needs: numbers(needs)}) + return class, nil + } + return edgeSatisfied, nil +} + +// partialAtHead judges v again where the run has got to, when earlier picks +// moved the branch past the line's head. +func (a *app) partialAtHead(b *batch, v *verdict) error { + head, err := resolve("HEAD") + if err != nil || head == b.lineHead { + return err + } + return b.partialAt(v, head) +} + +// keptOut lists the originals with backport/skip, or dropped, that the batch +// still carries: a run never takes a commit off the batch, --defer does. +func keptOut(b *batch, carried *history) ([]*verdict, error) { + var out []*verdict + for _, v := range b.verdicts { + if v.rule != ruleSkipLabel && v.rule != ruleDropped { + continue + } + if err := b.load(v); err != nil { + return nil, err + } + on, err := b.onBranch(carried, v) + if err != nil { + return nil, err + } + if on { + out = append(out, v) + } + } + return out, nil +} + +func found(h *history, v *verdict) bool { + c, _ := h.found(v.o, v.commits) + return c != "" +} + +// newReport starts the report of a run with what the rules left out and what +// the labels overrode. +func newReport(b *batch) *report { + r := &report{line: b.line, newer: b.newer, skipped: map[int][]*verdict{}, other: len(b.other), start: b.start, carried: b.src.rec} + for _, v := range b.verdicts { + if v.rule != 0 { + r.skipped[v.rule] = append(r.skipped[v.rule], v) + } + if v.label != "" { + r.overrides = append(r.overrides, v) + } + } + return r +} + +// finish prints the body and what the run did, and publishes the branch when +// asked to. +func (a *app) finish(b *batch, r *report, branch string, date time.Time, push, rebuilt bool) int { + head, err := resolve("HEAD") + if err != nil { + return a.fail(err) + } + if r.shapes, err = summarize(b, head, r.onBranch); err != nil { + return a.fail(err) + } + if rebuilt && head == b.lineHead && b.pr != nil { + // Deferring everything the batch carries leaves nothing to push: the + // batch is closed, and its record says so first, with the head the + // close is leased on. + r.closing = &closing{PR: b.pr.Number, Branch: branch, Head: b.prHead} + r.opts.Mode = modeClose + } + r.built = builtFrom{Main: b.mainHead, Line: b.lineHead, Newer: b.newerHead, Policy: b.policyAt, Batch: head, Tool: a.tool, + Run: runURL(os.LookupEnv), At: a.now().UTC().Format(time.RFC3339), Options: r.opts} + doc, err := buildReport(b, r) + if err != nil { + return a.fail(err) + } + p := publication{branch: branch, head: head, title: prTitle(b.line, date.Format(time.DateOnly)), report: storedReport{doc: doc, raw: reportJSON(doc)}} + p.record = r.lineRecord(doc) + // A record the next command would refuse is never written. + if err := p.record.validate(b.line); err != nil { + return a.fail(fmt.Errorf("the record this run made %w", err)) + } + r.blocks = recordBlock(p.record) + "\n\n" + reportBlock(p.report.raw) + template, err := lineTemplate(b.lineHead) + if err != nil { + return a.fail(err) + } + body, left := r.body(template) + p.body = body + _, _ = fmt.Fprint(a.stdout, body) + skipped := 0 + for _, items := range r.skipped { + skipped += len(items) + } + for _, rule := range left { + for _, v := range r.skipped[rule] { + _, _ = fmt.Fprintf(a.stderr, "skipped by %s: %s %s (%s)\n", ruleName(rule), v.o.url(), terminalSafe(v.o.title), terminalSafe(v.reason)) + } + } + for _, p := range r.waiting { + _, _ = fmt.Fprintf(a.stderr, "waiting for a maintainer: %s %s changes %s\n", p.v.o.url(), terminalSafe(p.v.o.title), terminalSafe(strings.Join(p.files, ", "))) + } + _, _ = fmt.Fprintf(a.stderr, "%s at %.12s: %d on the branch, %d deferred, %d waiting for a maintainer, %d skipped\ntitle: %s\nreport: %s\n", + branch, head, len(r.onBranch), len(r.deferred)+len(r.held), len(r.waiting), skipped, p.title, doc.ID) + if !push { + return 0 + } + if head == b.lineHead && b.pr == nil { + // Picking nothing is not a failure of the run; check still reports + // whatever the line lacks. Merged and closed batches are never + // written, so there is nowhere to keep what the run found. + _, _ = fmt.Fprintf(a.stderr, "%s carries nothing beyond %s; nothing to push\n", branch, b.line.branch()) + _, _ = fmt.Fprintf(a.stderr, "no batch pull request is open on %s; this run's classification is not retained\n", b.line.branch()) + return 0 + } + if err := a.publish(b, p, rebuilt); err != nil { + return a.fail(err) + } + return 0 +} + +// lineRecord is the record a run leaves for the line: what later commands +// act on, with the full classification left to the report it names. +func (r *report) lineRecord(doc reportDoc) lineRecord { + built := doc.Built + dropped := slices.Clone(r.dropped) + if dropped == nil { + dropped = []droppedEntry{} + } + slices.SortFunc(dropped, func(a, b droppedEntry) int { return a.Original - b.Original }) + return lineRecord{Version: recordVersion, Line: doc.Line, Built: &built, Report: doc.ID, Closing: r.closing, Deferred: slices.Clone(doc.Primary.Deferred), Dropped: dropped, Stale: slices.Clone(doc.Overlays.Stale), + Parked: carryAnnounced(doc.Primary.Parked, r.carried), Partial: slices.Clone(doc.Overlays.Partial), Changed: slices.Clone(doc.Overlays.Changed)} +} + +// branchDate is the date a batch branch was opened under. +func branchDate(branch string) (time.Time, error) { + m := batchBranchRE.FindStringSubmatch(branch) + if m == nil { + return time.Time{}, fmt.Errorf("%q is not a batch branch", branch) + } + return time.Parse("20060102", m[2]) +} + +// cleanTree refuses a working tree with changes or an operation in progress: +// run switches it to the batch branch. +func cleanTree() error { + out, err := git("status", "--porcelain", "--untracked-files=no") + if err != nil { + return err + } + if strings.TrimSpace(out) != "" { + return errors.New("the working tree has changes; run in a clean worktree") + } + for _, name := range []string{"CHERRY_PICK_HEAD", "MERGE_HEAD", "REVERT_HEAD", "REBASE_HEAD", "rebase-merge", "rebase-apply", "sequencer"} { + p, err := git("rev-parse", "--git-path", name) + if err != nil { + return err + } + if _, err := os.Stat(strings.TrimSpace(p)); err == nil { + return fmt.Errorf("an operation is in progress (%s); finish or abort it first", name) + } + } + return nil +} + +// warnReset says, before switch -C moves the local branch to start, which tip +// the move drops commits of and how to get them back: a clean tree says +// nothing about commits only a local branch has. +func (a *app) warnReset(branch, start string) error { + if err := a.mayAct(); err != nil { + return err + } + old, err := lookup("refs/heads/" + branch) + if err != nil || old == "" || old == start { + return err + } + kept, err := isAncestor(old, start) + if err != nil || kept { + return err + } + // The hint is the only way back to the dropped commits, so the reset does + // not run when it could not be written. + if _, err := fmt.Fprintf(a.stderr, "resetting the local %s from %s, dropping commits %.12s does not carry; git branch %s-%.12s %s restores them\n", branch, old, start, branch, old, old); err != nil { + return fmt.Errorf("not resetting the local %s: %w", branch, err) + } + return nil +} + +// ontoBranch is the pushed batch branch whose head --onto names, read from the +// remote itself: a head that moved since, or that no batch branch has, is +// refused rather than continued. +func ontoBranch(l line, onto string, dated bool, dateBranch string) (string, error) { + heads, err := remoteBatchHeads(l) + if err != nil { + return "", err + } + var found []string + for branch, sha := range heads { + if sha == onto && (!dated || branch == dateBranch) { + found = append(found, branch) + } + } + switch { + case len(found) == 0 && dated: + return "", fmt.Errorf("--onto %.12s is not the head of %s on %s (%.12s)", onto, dateBranch, remote, heads[dateBranch]) + case len(found) == 0: + return "", fmt.Errorf("--onto %.12s is not the head of any batch branch for %s on %s", onto, l.branch(), remote) + case len(found) > 1: + return "", fmt.Errorf("--onto %.12s heads more than one batch branch; name one with --date", onto) + } + have, err := lookup(onto) + if err != nil { + return "", err + } + if have == "" { + return "", fmt.Errorf("--onto %.12s is not in this repository; fetch it first", onto) + } + return found[0], nil +} + +// remoteBatchHeads lists the batch branches for l on the remote, read with +// ls-remote rather than from the possibly stale remote-tracking refs. +func remoteBatchHeads(l line) (map[string]string, error) { + out, err := git("ls-remote", "--refs", "--heads", "--end-of-options", remote) + if err != nil { + return nil, err + } + heads := map[string]string{} + for ln := range strings.Lines(out) { + sha, ref, ok := strings.Cut(strings.TrimSpace(ln), "\t") + branch, isHead := strings.CutPrefix(ref, "refs/heads/") + if !ok || !isHead || checkSHA(sha) != nil { + continue + } + if m := batchBranchRE.FindStringSubmatch(branch); m != nil && m[1] == l.branch() { + heads[branch] = sha + } + } + return heads, nil +} + +// applyPick runs one cherry-pick onto HEAD and leaves no operation in progress +// behind it: the outcome is picked, conflict, with the conflicting files, or +// empty. +func applyPick(args ...string) (string, []string, error) { + stdout, stderr, code, err := gitStatus(args...) + if err != nil { + return "", nil, err + } + if code == 0 { + return "picked", nil, nil + } + out, err := git("diff", "--name-only", "-z", "--diff-filter=U") + if err != nil { + return "", nil, err + } + if files := splitNUL(out); len(files) > 0 { + _, err := git("cherry-pick", "--abort") + return "conflict", files, err + } + if msg := stdout + stderr; strings.Contains(msg, "is now empty") || strings.Contains(msg, "nothing to commit") { + _, err := git("cherry-pick", "--skip") + return "empty", nil, err + } + failed := fmt.Errorf("failed: %s", strings.TrimSpace(stderr)) + if _, err := git("cherry-pick", "--abort"); err != nil { + return "", nil, errors.Join(failed, err) + } + return "", nil, failed +} + +// lineTemplate is the line's own pull request template, so the batch body has +// the sections reviewers of that line expect. +func lineTemplate(lineHead string) (string, error) { + const template = ".github/PULL_REQUEST_TEMPLATE.md" + out, err := git("--literal-pathspecs", "ls-tree", "--name-only", "--end-of-options", lineHead, "--", template) + if err != nil { + return "", err + } + if strings.TrimSpace(out) == "" { + return "## What this PR does\n\n### Release note\n\n```release-note\n\n```\n", nil + } + return git("show", "--end-of-options", lineHead+":"+template) +} + +// publication is what a run publishes: the branch at head, and the body that +// carries the record and the report. +type publication struct { + branch, head, title, body string + report storedReport + record lineRecord +} + +// publish pushes the batch branch, then opens the draft batch pull request or +// updates the open one. A run pushes only a fast-forward of what the remote +// has. A rebuild replaces the branch, and only the head it was rebuilt from: +// the lease is that head, as ls-remote reads it now, so a commit pushed since +// is never dropped. +// +// The report goes up as a comment before the push and the body that names +// it, so no write leaves a body naming a report nobody can read; a new batch +// carries the report in the body it is opened with, and the comment follows. +// Everything is rendered and measured before the first write. +func (a *app) publish(b *batch, p publication, rebuilt bool) error { + if b.pr != nil && b.pr.Head.Ref != p.branch { + return fmt.Errorf("the open batch pull request #%d is on %s; continue it with --onto %s", b.pr.Number, b.pr.Head.Ref, b.prHead) + } + // A body without the block was written by hand, and the tool's would + // replace it whole, title included; such a batch is the maintainer's. + if b.pr != nil && !b.src.open { + return fmt.Errorf("batch pull request #%d has no %s block, so backport-batch did not write it; merge or close it, and the next run opens a batch of its own", b.pr.Number, deferredFence) + } + if p.head == b.lineHead { + if rebuilt && p.record.Closing != nil { + return a.closeBatch(b, p) + } + return fmt.Errorf("%s carries nothing beyond %s; nothing to push", p.branch, b.line.branch()) + } + heads, err := remoteBatchHeads(b.line) + if err != nil { + return err + } + pushed, onRemote := heads[p.branch] + lease := "" + switch { + case rebuilt: + if !onRemote || pushed != b.prHead { + return fmt.Errorf("%s on %s is at %.12s, not at %.12s, which the rebuild started from; run again", p.branch, remote, pushed, b.prHead) + } + lease = pushed + case onRemote && pushed != p.head: + have, err := lookup(pushed) + if err != nil { + return err + } + descends := false + if have != "" { + if descends, err = isAncestor(pushed, p.head); err != nil { + return err + } + } + if !descends { + refusal := fmt.Sprintf("%s on %s is at %.12s, which %.12s does not descend from; refusing a non-fast-forward push", p.branch, remote, pushed, p.head) + // A run that stopped between its push and opening the pull request + // leaves the branch, and the next run that day builds it anew. + switch c := b.src.carrier; { + case b.pr != nil: + case c != nil && !b.src.open && c.Head.Ref == p.branch: + // Continuing a batch that merged or closed would publish + // what nobody can merge any more. + refusal += fmt.Sprintf("; it is the branch of batch pull request #%d, which is %s; the next run picks again what the tool put on it, but not a commit someone pushed there, such as a resolved conflict: check what %.12s carries, then delete it with git push origin --delete %s and run again", c.Number, prState(c), pushed, p.branch) + default: + refusal += fmt.Sprintf("; no batch pull request is open on it, and backport-batch run --line %s --onto %s --push continues it and opens one", b.line.branch(), pushed) + } + return errors.New(refusal) + } + } + if err := p.fits(); err != nil { + return err + } + if b.pr != nil { + if err := a.keepReports(b, &p); err != nil { + return err + } + } + if pushed != p.head { + if err := a.mayAct(); err != nil { + return err + } + if _, err := git(pushArgs(p.branch, p.head, lease)...); err != nil { + return err + } + } + name, err := writeTemp("backport-batch-body-*.md", p.body) + if err != nil { + return err + } + defer func() { _ = os.Remove(name) }() + if b.pr == nil { + n, url, err := a.gh.createPull(b.line.branch(), p.branch, p.title, name) + if err != nil { + return err + } + _, _ = fmt.Fprintf(a.stderr, "opened draft %s\n", url) + if err := a.postReport(n, p.report); err != nil { + return fmt.Errorf("posting report %.12s on #%d: %w; the body keeps it, and the next run --push posts it", p.report.doc.ID, n, err) + } + return nil + } + if err := a.stillOpen(b.pr.Number); err != nil { + return err + } + if err := a.gh.editPull(b.pr.Number, p.title, name); err != nil { + return err + } + _, _ = fmt.Fprintf(a.stderr, "updated %s\n", pullURL(b.pr)) + return nil +} + +// fits says why GitHub would not take the comment or the body. +func (p *publication) fits() error { + if _, err := reportComment(p.report); err != nil { + return err + } + if len(p.body) > bodyLimit { + return fmt.Errorf("the body is %d bytes with only what it cannot leave out, over GitHub's %d; nothing is published", len(p.body), bodyLimit) + } + return nil +} + +// keepReports makes sure the open batch's comments keep both the report its +// body carries now and the one this run made, in that order, each once. +// When this run's report is one already kept, the body carries the kept +// bytes, which differ only in when and in which job it was made. +func (a *app) keepReports(b *batch, p *publication) error { + pr := b.pr + posted, bad, err := findReports(a.gh, pr.Number, b.line) + if err != nil { + return err + } + for _, why := range bad { + a.warn("batch pull request #%d: %s; it does not count as a report", pr.Number, why) + } + earlier, err := bodyReport(pr.Body, b.line) + if err != nil { + return fmt.Errorf("batch pull request #%d: %w", pr.Number, err) + } + kept, ok := posted[p.report.doc.ID] + if !ok && earlier != nil && earlier.doc.ID == p.report.doc.ID { + kept, ok = *earlier, true + } + if ok { + p.body = strings.Replace(p.body, reportBlock(p.report.raw), reportBlock(kept.raw), 1) + p.report = kept + if err := p.fits(); err != nil { + return err + } + } + if earlier != nil { + if _, ok := posted[earlier.doc.ID]; !ok { + if err := a.postReport(pr.Number, *earlier); err != nil { + return fmt.Errorf("posting the earlier report %.12s on #%d: %w", earlier.doc.ID, pr.Number, err) + } + posted[earlier.doc.ID] = *earlier + } + } + if _, ok := posted[p.report.doc.ID]; !ok { + if err := a.postReport(pr.Number, p.report); err != nil { + return fmt.Errorf("posting report %.12s on #%d: %w", p.report.doc.ID, pr.Number, err) + } + } + return nil +} + +// pullURL is where a pull request is on GitHub. +func pullURL(pr *pullRequest) string { + if pullURLRE.MatchString(pr.HTMLURL) { + return pr.HTMLURL + } + return fmt.Sprintf("%spull/%d", ourRepoURL, pr.Number) +} + +// closeBatch closes the open batch that --defer left carrying nothing. Every +// write happens while it is open: the report, then the body whose record +// says it is closing and at which head. The close and the deletion of its +// branch then go only while both are still at that head. +func (a *app) closeBatch(b *batch, p publication) error { + c := *p.record.Closing + if err := p.fits(); err != nil { + return err + } + if err := a.keepReports(b, &p); err != nil { + return err + } + name, err := writeTemp("backport-batch-body-*.md", p.body) + if err != nil { + return err + } + defer func() { _ = os.Remove(name) }() + if err := a.stillOpen(c.PR); err != nil { + return err + } + if err := a.gh.editPull(c.PR, p.title, name); err != nil { + return fmt.Errorf("recording the close of #%d: %w", c.PR, err) + } + return a.finishClose(b.line, pullURL(b.pr), c) +} + +// finishClose closes the batch pull request a record says is closing, and +// deletes its branch, each only while it is at the head the record froze. +func (a *app) finishClose(l line, url string, c closing) error { + pr, err := a.gh.pull(c.PR) + if err != nil { + return fmt.Errorf("closing #%d, reading it again: %w", c.PR, err) + } + if st := prState(&pr); st != "open" || pr.Head.SHA != c.Head { + return fmt.Errorf("closing #%d: it is %s at %.12s, not open at %.12s, which its record froze", c.PR, st, terminalSafe(pr.Head.SHA), c.Head) + } + heads, err := remoteBatchHeads(l) + if err != nil { + return err + } + if h := heads[c.Branch]; h != c.Head { + return fmt.Errorf("closing #%d: %s on %s is at %.12s, not at %.12s, which its record froze", c.PR, c.Branch, remote, h, c.Head) + } + if err := a.gh.closePull(c.PR); err != nil { + return fmt.Errorf("closing #%d: %w; backport-batch run --line %s --push finishes it", c.PR, err, l.branch()) + } + if err := a.deleteBranch(l, c); err != nil { + return err + } + _, _ = fmt.Fprintf(a.stderr, "closed %s: without what is deferred it carries nothing beyond %s; the next batch tries them again\n", url, l.branch()) + return nil +} + +// deleteBranch deletes the branch of a closed batch, leased on the head it +// was closed at: one someone pushed since is a person's to delete or keep. +func (a *app) deleteBranch(l line, c closing) error { + heads, err := remoteBatchHeads(l) + if err != nil { + return err + } + switch h, ok := heads[c.Branch]; { + case !ok: + return nil + case h != c.Head: + return movedBranch(c, h) + } + if err := a.mayAct(); err != nil { + return err + } + if _, err := git(deleteArgs(c.Branch, c.Head)...); err != nil { + return fmt.Errorf("deleting %s, left by the close of #%d: %w; backport-batch run --line %s --push deletes it", c.Branch, c.PR, err, l.branch()) + } + return nil +} + +// takenBranch is the refusal for a branch a close left that an open batch +// pull request now uses, whatever it holds, or nil. +func takenBranch(b *batch, c closing) error { + if b.pr == nil || b.pr.Head.Ref != c.Branch { + return nil + } + return fmt.Errorf("batch pull request #%d is open on %s, which the close of #%d left; the branch is that pull request's now, and the close leaves it alone", b.pr.Number, c.Branch, c.PR) +} + +func movedBranch(c closing, h string) error { + return fmt.Errorf("batch pull request #%d was closed at %.12s, but %s is at %.12s now; the next run picks again what the tool put on it, but not a commit someone pushed there, such as a resolved conflict: check what %.12s carries, then delete it with git push origin --delete %s, and run again", c.PR, c.Head, c.Branch, h, h, c.Branch) +} + +// resumeClose finishes a close the record says is under way, before a run +// does anything else, and only under --push. It says whether the run may go +// on: only once the batch is closed and its branch gone. A run that finishes +// one stops there, and fails when it was asked to change the batch. +func (a *app) resumeClose(b *batch, push, changing bool) (bool, int) { + if b.src.rec == nil || b.src.rec.Closing == nil { + return true, 0 + } + c := *b.src.rec.Closing + heads, err := remoteBatchHeads(b.line) + if err != nil { + return false, a.fail(err) + } + h, onRemote := heads[c.Branch] + switch { + case b.src.open && h != c.Head: + return false, a.fail(fmt.Errorf("batch pull request #%d is being closed, but %s is at %.12s, not at %.12s, which its record froze; a person closes it, or pushes the branch back, by hand", c.PR, c.Branch, h, c.Head)) + case b.src.open && !push: + return false, a.fail(fmt.Errorf("batch pull request #%d is being closed: closing it and deleting %s are left; backport-batch run --line %s --push finishes it", c.PR, c.Branch, b.line.branch())) + case b.src.open: + if err := a.finishClose(b.line, pullURL(b.src.carrier), c); err != nil { + return false, a.fail(err) + } + return false, a.finished(c, changing) + case !onRemote: + return true, 0 + case takenBranch(b, c) != nil: + return false, a.fail(takenBranch(b, c)) + case h != c.Head: + return false, a.fail(movedBranch(c, h)) + case !push: + return false, a.fail(fmt.Errorf("batch pull request #%d was closed, but %s is still at %.12s; backport-batch run --line %s --push deletes it", c.PR, c.Branch, h, b.line.branch())) + } + if err := a.deleteBranch(b.line, c); err != nil { + return false, a.fail(err) + } + _, _ = fmt.Fprintf(a.stderr, "deleted %s, which the close of #%d left\n", c.Branch, c.PR) + return false, a.finished(c, changing) +} + +// finished is the exit of a run that finished a close: a change it was asked +// for needs an open batch pull request, and none is left to make it on. +func (a *app) finished(c closing, changing bool) int { + if !changing { + return 0 + } + return a.fail(fmt.Errorf("finished the close of #%d and made no other change: what this run was asked to change needs an open batch pull request, which the next run opens", c.PR)) +} + +// pushArgs pushes head to branch: as a fast-forward, which the remote checks, +// or, given a lease, over exactly that commit and no other. +func pushArgs(branch, head, lease string) []string { + args := []string{"push", "--quiet"} + if lease != "" { + args = append(args, "--force-with-lease=refs/heads/"+branch+":"+lease) + } + return append(args, "--end-of-options", remote, head+":refs/heads/"+branch) +} + +// deleteArgs deletes branch, only while the remote has it at lease. +func deleteArgs(branch, lease string) []string { + return []string{"push", "--quiet", "--force-with-lease=refs/heads/" + branch + ":" + lease, "--end-of-options", remote, ":refs/heads/" + branch} +} diff --git a/cmd/backport-batch/assemble_test.go b/cmd/backport-batch/assemble_test.go new file mode 100644 index 000000000..31dfd7dda --- /dev/null +++ b/cmd/backport-batch/assemble_test.go @@ -0,0 +1,318 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package main + +import ( + "os" + "path/filepath" + "slices" + "strings" + "testing" +) + +// A merged pull request lands as its own commits, each picked with -x and +// keeping its author and sign-offs, under a merge commit that carries the +// merge message from main and names it; a squash lands as one pick; a merge +// of main into the pull request's branch is left out; all in main's merge +// order. +func TestRunPicksInMergeOrder(t *testing.T) { + f := newFixture(t) + f.lines() + signoff := "Signed-off" + "-by: " + contributor + mc5 := f.prCommits(5, "fix(app): five", "Body.\n\n```release-note\nfix(app): five is fixed\n```", + change{files: map[string]string{"app/five.txt": "5\n"}, author: contributor, message: "fix(app): start five\n\n" + signoff}, + change{files: map[string]string{"app/five.txt": "5, done\n", "app/five-more.txt": "more\n"}, author: contributor, message: "fix(app): finish five\n\n" + signoff}) + sq6 := f.squash(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + f.pr(7, "feat(app): seven", "", map[string]string{"app/seven.txt": "7\n"}) + mc8 := f.prCommits(8, "fix(app): eight", "", + change{files: map[string]string{"app/eight.txt": "8\n"}}, + change{mergeMain: true}, + change{files: map[string]string{"app/eight.txt": "8, after main\n"}}) + + code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1") + if code != 0 { + t.Fatalf("run = %d\n%s", code, stderr) + } + if got := f.git("branch", "--show-current"); got != batchBranch1 { + t.Fatalf("on %q, want %s", got, batchBranch1) + } + want := []string{"fix(app): five (#5)", "fix(app): six (#6)", "fix(app): eight (#8)"} + if got := f.subjects("origin/release-1.1", "HEAD"); !slices.Equal(got, want) { + t.Errorf("the batch carries %q, want %q", got, want) + } + + line := f.git("rev-parse", "origin/release-1.1") + u5 := f.git("rev-parse", "HEAD~2") + if got := f.git("rev-parse", u5+"^1"); got != line { + t.Errorf("#5's merge sits on %.12s, want the line's head %.12s", got, line) + } + if msg := f.git("log", "-1", "--format=%B", u5); !strings.HasSuffix(msg, "\n\n"+batchTrailer+": "+mc5) || !strings.HasPrefix(msg, "fix(app): five (#5)") { + t.Errorf("#5's merge does not carry the merge message and name %s:\n%s", mc5, msg) + } + own := strings.Fields(f.git("rev-list", "--reverse", mc5+"^1.."+mc5+"^2")) + picks := strings.Fields(f.git("rev-list", "--reverse", u5+"^2", "^"+u5+"^1")) + if len(picks) != 2 || len(own) != 2 { + t.Fatalf("#5 brought %d picks of its %d commits, want 2", len(picks), len(own)) + } + for i, c := range picks { + msg := f.git("log", "-1", "--format=%B", c) + if got := f.git("log", "-1", "--format=%an <%ae>", c); got != contributor { + t.Errorf("pick %d is authored by %q, want %q", i, got, contributor) + } + if !strings.Contains(msg, signoff+"\n(cherry picked from commit "+own[i]+")\nSigned-off-by: Batch Test ") { + t.Errorf("pick %d lacks the contributor's sign-off, its -x line for %s or the batch's sign-off:\n%s", i, own[i], msg) + } + } + + u6 := f.git("rev-parse", "HEAD~1") + if parents := strings.Fields(f.git("rev-list", "--parents", "-n", "1", u6)); len(parents) != 2 || parents[1] != u5 { + t.Errorf("#6 is %v, want one commit on #5's merge", parents) + } + if msg := f.git("log", "-1", "--format=%B", u6); !strings.Contains(msg, "(cherry picked from commit "+sq6+")") { + t.Errorf("#6's pick lacks its -x line:\n%s", msg) + } + + picks8 := strings.Fields(f.git("rev-list", "--reverse", "HEAD^2", "^HEAD^1")) + if got := len(picks8); got != 2 { + t.Errorf("#8 brought %d commits, want its own 2 without the merge of main", got) + } + if !strings.HasSuffix(f.git("log", "-1", "--format=%B", "HEAD"), batchTrailer+": "+mc8) { + t.Error("#8's merge does not name its merge commit") + } + if f.git("rev-parse", "HEAD:app/eight.txt") != f.git("rev-parse", mc8+":app/eight.txt") { + t.Error("app/eight.txt is not what main has after #8") + } + for _, s := range []string{"[#5]", "[#6]", "[#8]", "fix(app): five is fixed", "Rule 2", "`fix(app): five`, 2 commits", "`fix(app): six`, 1 commit"} { + if !strings.Contains(stdout, s) { + t.Errorf("the body lacks %q:\n%s", s, stdout) + } + } + if code, out, stderr := f.exec(nil, "verify", "--line", "release-1.1", "--head", f.git("rev-parse", "HEAD")); code != 0 { + t.Errorf("verify of the batch = %d\n%s\n%s", code, out, stderr) + } +} + +// A conflict is aborted, recorded with its files, and the next original is +// still picked. +func TestRunRecordsConflictsAndGoesOn(t *testing.T) { + f := newFixture(t) + f.lines() + f.onLine("release-1.1", "fix(chart): a line-only value", map[string]string{"chart/values.yaml": "replicas: 3\nimage: app:1\n"}) + f.pr(5, "fix(chart): five", "", map[string]string{"chart/values.yaml": "replicas: 5\nimage: app:1\n"}) + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + + code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1") + if code != 0 { + t.Fatalf("run = %d\n%s", code, stderr) + } + if got := f.subjects("origin/release-1.1", "HEAD"); !slices.Equal(got, []string{"fix(app): six (#6)"}) { + t.Errorf("picked %q, want only #6", got) + } + if out := f.git("status", "--porcelain"); out != "" { + t.Errorf("the tree is left dirty:\n%s", out) + } + if _, err := os.Stat(filepath.Join(f.dir, ".git", "CHERRY_PICK_HEAD")); err == nil { + t.Error("a cherry-pick is left in progress") + } + l, _ := parseLine("release-1.1") + deferred, err := parseDeferred(stdout, l) + if err != nil || len(deferred[5].Files) == 0 || len(deferred) != 1 { + t.Errorf("deferred = %v, %v; want #5", deferred, err) + } + if !strings.Contains(stdout, "### Deferred conflicts") || !strings.Contains(stdout, "`chart/values.yaml`") { + t.Errorf("the body does not name the conflict and its file:\n%s", stdout) + } +} + +// An original the earlier picks already carry is skipped as an empty pick. +func TestRunSkipsAnEmptyPick(t *testing.T) { + f := newFixture(t) + f.lines() + f.pr(5, "fix(app): add x", "", map[string]string{"app/x.txt": "x\n"}) + f.pr(6, "revert(app): drop x", "", map[string]string{"app/x.txt": ""}) + f.pr(7, "fix(app): add x again", "", map[string]string{"app/x.txt": "x\n"}) + + code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1") + if code != 0 { + t.Fatalf("run = %d\n%s", code, stderr) + } + if got := f.subjects("origin/release-1.1", "HEAD"); !slices.Equal(got, []string{"fix(app): add x (#5)"}) { + t.Errorf("picked %q, want only #5", got) + } + if !strings.Contains(stdout, "the earlier picks already carry it") { + t.Errorf("#7 is not reported as carried by the earlier picks:\n%s", stdout) + } +} + +// A hook in the repository or the user's configuration never rewrites what a +// pick carries. +func TestRunIgnoresHooks(t *testing.T) { + f := newFixture(t) + f.lines() + f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"}) + hooks := filepath.Join(f.dir, ".git", "hooks") + for _, hook := range []string{"prepare-commit-msg", "commit-msg"} { + if err := os.WriteFile(filepath.Join(hooks, hook), []byte("#!/bin/sh\necho rewritten by a hook > \"$1\"\n"), 0o755); err != nil { + t.Fatal(err) + } + } + if code, _, stderr := f.exec(nil, "run", "--line", "release-1.1"); code != 0 { + t.Fatalf("run = %d\n%s", code, stderr) + } + if got := f.subjects("origin/release-1.1", "HEAD"); !slices.Equal(got, []string{"fix(app): five (#5)"}) { + t.Errorf("picked %q, want #5 as it was merged", got) + } +} + +func TestRunRefusesADirtyTree(t *testing.T) { + f := newFixture(t) + f.lines() + f.write("README.md", "changed\n") + code, _, stderr := f.exec(nil, "run", "--line", "release-1.1") + if code != 2 || !strings.Contains(stderr, "has changes") { + t.Errorf("run on a dirty tree = %d (%s), want 2", code, stderr) + } + if f.git("branch", "--show-current") != "main" { + t.Error("the tree was switched anyway") + } + + // A pick that stopped empty leaves the tree clean and the pick going. + f.git("checkout", "-q", "--", "README.md") + if err := os.WriteFile(filepath.Join(f.dir, ".git", "CHERRY_PICK_HEAD"), []byte(f.git("rev-parse", "HEAD")+"\n"), 0o644); err != nil { + t.Fatal(err) + } + code, _, stderr = f.exec(nil, "run", "--line", "release-1.1") + if code != 2 || !strings.Contains(stderr, "operation is in progress (CHERRY_PICK_HEAD)") { + t.Errorf("run during a cherry-pick = %d (%s), want 2", code, stderr) + } +} + +// A clean tree says nothing about commits only the local batch branch has, so +// a run or a rebuild that resets that branch over them names its tip and the +// command that gets them back; one that drops nothing says nothing. +func TestResetNamesWhatItDrops(t *testing.T) { + f := newFixture(t) + f.lines() + f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"}) + unpushed := func(base string) string { + t.Helper() + f.git("switch", "-q", "-C", batchBranch1, base) + f.write("app/mine.txt", "unpushed\n") + f.git("add", "-A") + f.git("commit", "-q", "-m", "an unpushed resolution") + tip := f.git("rev-parse", "HEAD") + f.git("switch", "-q", "main") + return tip + } + notice := func(stderr, tip string) bool { + t.Helper() + restore := "git branch " + batchBranch1 + "-" + tip[:12] + " " + tip + if !strings.Contains(stderr, "resetting the local "+batchBranch1+" from "+tip+",") || !strings.Contains(stderr, restore) { + return false + } + f.git(strings.Fields(restore)[1:]...) + if got := f.git("rev-parse", batchBranch1+"-"+tip[:12]); got != tip { + t.Errorf("%s restored %.12s, want %.12s", restore, got, tip) + } + return true + } + + tip := unpushed("origin/release-1.1") + if code, _, stderr := f.exec(nil, "run", "--line", "release-1.1"); code != 0 || !notice(stderr, tip) { + t.Errorf("run over an unpushed commit = %d, want it named with its restore:\n%s", code, stderr) + } + f.git("switch", "-q", "main") + f.git("branch", "-f", batchBranch1, "origin/release-1.1~1") + if code, _, stderr := f.exec(nil, "run", "--line", "release-1.1"); code != 0 || strings.Contains(stderr, "resetting") { + t.Errorf("run over a branch it fast-forwards = %d, want no notice:\n%s", code, stderr) + } + + f.git("switch", "-q", "main") + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + gh := &fakeGH{} + head := openBatch(t, f, gh) + tip = unpushed(head) + if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--defer", "6", "--reason", "fails the app e2e"); code != 0 || !notice(stderr, tip) { + t.Errorf("a rebuild over an unpushed commit = %d, want it named with its restore:\n%s", code, stderr) + } +} + +// --push pushes a fresh branch and opens the draft, and a second push of the +// same branch updates the open pull request instead. +func TestRunPush(t *testing.T) { + f := newFixture(t) + f.lines() + f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"}) + gh := &fakeGH{} + code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--push") + if code != 0 { + t.Fatalf("run --push = %d\n%s", code, stderr) + } + if !strings.Contains(stderr, "opened draft https://github.com/cozystack/cozystack/pull/90\n") { + t.Errorf("the run does not print the pull request it opened:\n%s", stderr) + } + l, _ := parseLine("release-1.1") + if _, err := parseDeferred(stdout, l); err != nil || !strings.HasPrefix(stdout, "## What this PR does") || strings.Contains(stdout, "https://github.com/cozystack/cozystack/pull/90") { + t.Errorf("stdout is no longer the body alone (%v):\n%s", err, stdout) + } + head := f.git("rev-parse", "HEAD") + if got := f.remoteHead(batchBranch1); got != head { + t.Errorf("remote %s = %q, want %s", batchBranch1, got, head) + } + if want := []string{"release-1.1 " + batchBranch1 + " fix(backport): batch for release-1.1, 2026-10-26"}; !slices.Equal(gh.created, want) { + t.Errorf("created %q, want %q", gh.created, want) + } + + f.git("switch", "-q", "main") + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + gh.prs = []pullRequest{f.batchPR(90, "release-1.1", batchBranch1, gh.bodies[0])} + code, _, stderr = f.exec(gh, "run", "--line", "release-1.1", "--onto", head, "--push") + if code != 0 { + t.Fatalf("run --onto --push = %d\n%s", code, stderr) + } + if !strings.Contains(stderr, "updated https://github.com/cozystack/cozystack/pull/90\n") { + t.Errorf("the run does not print the pull request it updated:\n%s", stderr) + } + if got := f.subjects("origin/release-1.1", f.remoteHead(batchBranch1)); !slices.Equal(got, []string{"fix(app): five (#5)", "fix(app): six (#6)"}) { + t.Errorf("the pushed batch carries %q, want #5 then #6", got) + } + if len(gh.edited) != 1 || gh.edited[0] != "#90 fix(backport): batch for release-1.1, 2026-10-26" { + t.Errorf("edited %q, want #90", gh.edited) + } + if body := gh.bodies[len(gh.bodies)-1]; !strings.Contains(body, "[#5]") || !strings.Contains(body, "[#6]") { + t.Errorf("the updated body does not list both originals:\n%s", body) + } +} + +// With a batch pull request open on another branch, a fresh push would open +// a second one; it is refused before anything is pushed. +func TestRunPushRefusesASecondBatch(t *testing.T) { + f := newFixture(t) + f.lines() + f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"}) + old := "backport-batch/release-1.1-20261022" + f.git("push", "-q", "origin", "origin/release-1.1:refs/heads/"+old) + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + gh := &fakeGH{prs: []pullRequest{f.batchPR(90, "release-1.1", old, "")}} + code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--push") + if code != 2 || !strings.Contains(stderr, "continue it with --onto") { + t.Errorf("run --push = %d (%s), want a refusal", code, stderr) + } + if f.remoteHead(batchBranch1) != "" || len(gh.created)+len(gh.edited) != 0 { + t.Error("something was pushed or opened") + } +} diff --git a/cmd/backport-batch/batchbot_test.go b/cmd/backport-batch/batchbot_test.go new file mode 100644 index 000000000..ff1cb342a --- /dev/null +++ b/cmd/backport-batch/batchbot_test.go @@ -0,0 +1,86 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package main + +import ( + "slices" + "strings" + "testing" +) + +// A maintainer's run by hand continues the batch pull request the scheduled +// run opened as its bot, with nothing set: it edits that pull request rather +// than opening a second one for the line. A record another bot wrote is no +// record the batch trusts, and the run stops rather than reach past it. +func TestHandRunContinuesTheBotsBatch(t *testing.T) { + for _, tc := range []struct { + name, author string + continued bool + }{ + {"the scheduled run's bot", "cozystack-ci[bot]", true}, + {"another bot", "renovate[bot]", false}, + } { + t.Run(tc.name, func(t *testing.T) { + f := newFixture(t) + f.lines() + f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"}) + gh := &fakeGH{bot: batchBotLogin(func(string) (string, bool) { return "", false })} + openBatch(t, f, gh) + gh.prs[0].User.Login, gh.prs[0].User.Type = tc.author, "Bot" + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + f.now = f.now.AddDate(0, 0, 3) + + code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--push") + if tc.continued && code != 0 || !tc.continued && (code != 2 || !strings.Contains(stderr, "batch pull request #90 (open) carries a ```backport-batch block but was opened by \"renovate[bot]\"")) { + t.Fatalf("run --continue = %d\n%s", code, stderr) + } + continued := slices.Equal(gh.edited, []string{"#90 fix(backport): batch for release-1.1, 2026-10-26"}) && len(gh.created) == 1 + if continued != tc.continued || len(gh.created) != 1 { + t.Errorf("edited %q, created %q; want the batch of %s continued=%v and no second one\n%s", gh.edited, gh.created, tc.author, tc.continued, stderr) + } + if !tc.continued && !strings.Contains(stderr, "ignoring #90") { + t.Errorf("the run does not say it ignores #90:\n%s", stderr) + } + }) + } +} + +// The bot comes from BACKPORT_BATCH_BOT when it is set, empty included, and +// is the scheduled run's own bot when it is not. +func TestBatchBotLogin(t *testing.T) { + env := func(v string, ok bool) func(string) (string, bool) { + return func(key string) (string, bool) { + if key != batchBotEnv { + t.Errorf("looked up %s", key) + } + return v, ok + } + } + for _, tc := range []struct { + name, v string + ok bool + want string + }{ + {"unset", "", false, "cozystack-ci[bot]"}, + {"set empty", "", true, ""}, + {"set", "other-app[bot]", true, "other-app[bot]"}, + } { + if got := batchBotLogin(env(tc.v, tc.ok)); got != tc.want { + t.Errorf("%s: batchBotLogin = %q, want %q", tc.name, got, tc.want) + } + } +} diff --git a/cmd/backport-batch/body.go b/cmd/backport-batch/body.go new file mode 100644 index 000000000..dbb9d6050 --- /dev/null +++ b/cmd/backport-batch/body.go @@ -0,0 +1,632 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package main + +import ( + "encoding/json" + "fmt" + "regexp" + "slices" + "strconv" + "strings" + "time" + "unicode" +) + +// Titles, release notes and file names in the body were written by whoever +// opened the originals, and the body is published under the name of whoever +// runs --push. None of it is searched for what might be dangerous and then +// rendered by other rules: a title, a reason or a file name goes whole into a +// code span, and the release notes into the fenced release-note block, both +// of which GitHub shows as written, with no mention, reference, link or HTML +// in them acted on. neutralNote is for a note copied out of that block. + +const ( + ourRepoURL = "https://github.com/" + upstreamRepo + "/" + // tasksURL is where the instructions for the work a batch leaves live. + tasksURL = ourRepoURL + "blob/main/docs/release/backport-tasks/" +) + +const ( + titleLimit = 200 + // GitHub refuses a pull request body longer than this. + bodyLimit = 65536 +) + +var ( + backtickRunRE = regexp.MustCompile("`+") + fenceRunRE = regexp.MustCompile("`{3,}|~{3,}") + mdLinkRE = regexp.MustCompile(`!?\[([^\]]*)\]\(([^)]*)\)`) + urlRE = regexp.MustCompile("(?i)\\b(?:https?|ftp)://[^\\s<>()\\[\\]`]+|\\bwww\\.[^\\s<>()\\[\\]`]+") + // A closing keyword with its target, a cross-repository reference and a + // mention, wherever they stand: no exception for what precedes them, so + // nothing depends on agreeing with GitHub about word boundaries. + actingRE = regexp.MustCompile(`(?i)\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\b\s*:?\s*(?:(?:[\w.-]+/[\w.-]+)?#\d+|https?://github\.com/[\w.-]+/[\w.-]+/(?:issues|pull)/\d+)` + + `|[\w.-]+/[\w.-]+#\d+|@[A-Za-z0-9][A-Za-z0-9-]*(?:/[A-Za-z0-9_.-]+)?`) + // A link into this repository survives, unless a dot segment or an escape + // could take it somewhere else. + safeURLRE = regexp.MustCompile(`^` + regexp.QuoteMeta(ourRepoURL) + `[\w/?=&#+.-]*$`) + releaseNotRE = regexp.MustCompile("(?ms)^[ \t]*```+[ \t]*release-note[ \t]*\n(.*?)^[ \t]*```") + headingRE = regexp.MustCompile(`^#{1,6} `) + placeholders = []string{"", "none", "n/a", "na", "no", "-", "nothing"} +) + +// clean drops what is not text: control characters other than tab and, when +// asked, newline, which a terminal acts on, and format characters such as the +// zero-width and bidi ones, which make text read as something it is not. +// Invalid UTF-8, a raw 8-bit escape among it, becomes U+FFFD. +func clean(s string, newlines bool) string { + var b strings.Builder + for _, r := range strings.ToValidUTF8(s, "\uFFFD") { + switch { + case r == '\t', r == '\n' && newlines: + b.WriteRune(r) + case r == '\r' || unicode.Is(unicode.Cf, r): + case r == '\n', r == '\u2028', r == '\u2029': + b.WriteRune(' ') + case unicode.IsControl(r): + b.WriteRune('\uFFFD') + default: + b.WriteRune(r) + } + } + return b.String() +} + +func oneLine(s string) string { + return strings.Join(strings.FieldsFunc(s, func(r rune) bool { return unicode.IsSpace(r) || unicode.IsControl(r) }), " ") +} + +func capped(s string, limit int) string { + if r := []rune(s); len(r) > limit { + return strings.TrimRightFunc(string(r[:limit-1]), unicode.IsSpace) + "…" + } + return s +} + +// codeSpan puts s on one line in a code span: its fence is longer than any +// backtick run inside, so nothing in s can close it. +func codeSpan(s string) string { + s = oneLine(clean(s, false)) + longest := 0 + for _, run := range backtickRunRE.FindAllString(s, -1) { + longest = max(longest, len(run)) + } + fence := strings.Repeat("`", longest+1) + pad := "" + if s == "" || strings.HasPrefix(s, "`") || strings.HasSuffix(s, "`") { + pad = " " + } + return fence + pad + s + pad + fence +} + +// titleSpan is a carried title as the body shows it. +func titleSpan(s string) string { return codeSpan(capped(oneLine(clean(s, false)), titleLimit)) } + +func prLink(n int) string { + return fmt.Sprintf("[#%d](%spull/%d)", n, ourRepoURL, n) +} + +func ours(url string) bool { + return safeURLRE.MatchString(url) && !strings.Contains(url, "/.") +} + +// inertSigns swaps the characters GitHub acts on for their fullwidth forms, +// which read the same and act on nothing. Unlike a code span, the swap does +// not depend on how the backticks around it pair up. +var inertSigns = strings.NewReplacer("@", "@", "#", "#", "://", "://") + +// neutralNote makes a release note safe inside the fenced block and inert +// outside it: no run of backticks or tildes is left to close the fence, links +// lose their target unless it is this repository, and closing keywords, +// cross-repository references and mentions lose the signs that make them +// act. Each step runs on the output of the one before, so a mention a link's +// text carried is still found. +func neutralNote(s string) string { + s = clean(s, true) + s = mdLinkRE.ReplaceAllString(s, "$1 ($2)") + s = urlRE.ReplaceAllStringFunc(s, func(u string) string { + if ours(u) { + return u + } + return "(link removed)" + }) + s = actingRE.ReplaceAllStringFunc(s, inertSigns.Replace) + return fenceRunRE.ReplaceAllStringFunc(s, func(f string) string { return strings.Repeat("'", len(f)) }) +} + +// releaseNote is the release-note block of a body, or "" when it has none or +// only a placeholder. +func releaseNote(body string) string { + m := releaseNotRE.FindStringSubmatch(htmlCommentRE.ReplaceAllString(body, "")) + if m == nil { + return "" + } + note := strings.TrimSpace(m[1]) + if slices.Contains(placeholders, strings.Trim(strings.ToLower(note), " .")) { + return "" + } + return note +} + +// deferredFence opens the block check reads the deferred conflicts from. +const deferredFence = "```backport-batch" + +// deferredEntry is a conflict, with the commit that failed and its files, an +// original --defer took out of the batch, with the reason given, or one that +// waits for a maintainer because it changes workflows, with those files. +type deferredEntry struct { + Original int `json:"original"` + Commit string `json:"commit,omitempty"` + Files []string `json:"files"` + More int `json:"more,omitempty"` + Reason string `json:"reason,omitempty"` + Workflows bool `json:"workflows,omitempty"` + // Needs, from version 3, are the originals still to come that it waits + // on, those of the kind that decides the wait. + Needs []int `json:"needs,omitempty"` +} + +// How many conflicting files of one original the body names, in the list and +// in the block: a vendored chart can conflict in hundreds. +const ( + filesListed = 5 + filesKept = 50 +) + +type deferredRecord struct { + Line string `json:"line"` + Deferred []deferredEntry `json:"deferred"` +} + +// deferredBlock is a version 1 record, which batches carried before records +// had a version. encoding/json leaves bidi and zero-width characters as they +// are, so file names go through clean first, as the reason does. +func deferredBlock(l line, conflicts, held, waiting []pick) string { + data, _ := json.Marshal(deferredRecord{Line: l.branch(), Deferred: deferredEntries(conflicts, held, waiting, nil)}) + return deferredFence + "\n" + string(data) + "\n```" +} + +func cleanFiles(files []string) []string { + out := make([]string, len(files)) + for i, f := range files { + out[i] = clean(f, false) + } + return out +} + +// parseDeferred reads what a batch body's record defers. +func parseDeferred(body string, l line) (map[int]deferredEntry, error) { + rec, err := parseRecord(body, l) + if err != nil { + return nil, err + } + return rec.deferred(), nil +} + +// prTitle is built from the line and the date alone, never from carried text. +func prTitle(l line, date string) string { + return fmt.Sprintf("fix(backport): batch for %s, %s", l.branch(), date) +} + +// skipRules are the rules a skipped original is reported under, in order. +var skipRules = []int{ruleBeforeStart, ruleOnLine, ruleType, ruleBreaking, ruleTouches, ruleNewer, ruleDropped} + +// report is what one run put on the batch branch and what it left out. +type report struct { + line line + newer *line + onBranch []*verdict // carried from --onto and picked now, in merge order + deferred []pick // conflicts + held []pick // what --defer took out, with the reason + waiting []pick // what changes workflows, left to a maintainer + needs []pick // what waits on other originals still to come + skipped map[int][]*verdict + other int + // overrides are the originals a backport/ label kept out or let in, and + // stale those with backport/skip that are still on the batch. + overrides []*verdict + stale []*verdict + start time.Time + // shapes says, for an original on the branch, what it brought, and + // partialFiles what a partial unit leaves without effect. + shapes map[*verdict]unitShape + partialFiles map[*verdict][]string + // missing are originals the policy takes that the run neither tried nor + // found anywhere. + missing []*verdict + // opts is how the run was asked to classify, and built what it read. + opts runOptions + built builtFrom + // blocks are the record and the report the body ends with. + blocks string + // closing is the close of the open batch this run leaves carrying + // nothing. + closing *closing + // dropped are the maintainers' drops the record keeps. + dropped []droppedEntry + // parked are what the batch leaves out because it cannot land whole, + // each with its park, and partial the originals on the branch whose unit + // does only part of what they do on main. + parked []*verdict + partial []*verdict + // carried is the line's record this run found, whose announcements the + // parks that did not change keep. + carried *lineRecord +} + +// ruleName is how output names what kept an original out: the policy's +// number for its own rules, and words for what the policy does not number. +func ruleName(rule int) string { + switch rule { + case ruleSkipLabel: + return labelSkip + case ruleBeforeStart: + return "rule 1, before the line's start" + case ruleDropped: + return "a maintainer's drop" + } + return "rule " + strconv.Itoa(rule) +} + +// listTitle titles the list of what a rule skipped, a drop among them. +func (r *report) listTitle(rule int) string { + if rule == ruleDropped { + return "Dropped from " + codeSpan(r.line.branch()) + " by a maintainer" + } + return r.ruleTitle(rule) +} + +func (r *report) ruleTitle(rule int) string { + switch rule { + case ruleBeforeStart: + return "Rule 1, merged before " + codeSpan(r.line.branch()) + " started under the policy on " + r.start.Format(time.DateOnly) + case ruleOnLine: + return "Rule 1, already on " + codeSpan(r.line.branch()) + case ruleType: + return "Rule 2, the title type is not `fix` or `security`, or the scope is `deps`" + case ruleBreaking: + return "Rule 3, a breaking change" + case ruleTouches: + return "Rule 4, touches platform migrations, `targetVersion` or a CRD, or makes a sizeable API change" + case ruleNewer: + return "Rule 6, not on " + codeSpan(r.newer.branch()) + " yet" + } + return fmt.Sprintf("Rule %d", rule) +} + +// what is the What this PR does section, with the skipped lists of the rules +// in details written out. +func (r *report) what(details map[int]bool) string { + var b strings.Builder + fmt.Fprintf(&b, "Backports to %s from `main`, picked by the rules of the [backport policy](%s) in merge order. A merged pull request comes as its own commits, picked with `git cherry-pick -x` so each keeps its author, message and sign-offs, and a merge commit that carries the original's merge message with a `%s:` trailer naming it; a squash-merged one comes as one pick. `backport-batch verify` checks that shape. A pick listed as changed differs from the commit it came from, and its release note waits under Check these notes. A conflict or a failing check here is a [backport task](%sREADME.md).\n\n", codeSpan(r.line.branch()), policyURL, batchTrailer, tasksURL) + if len(r.onBranch) == 0 { + b.WriteString("Nothing is picked yet.\n") + } + for _, v := range r.onBranch { + shape := "" + if s, ok := r.shapes[v]; ok { + shape = ", " + s.String() + } + fmt.Fprintf(&b, "- %s %s%s\n%s", prLink(v.o.number), titleSpan(v.o.title), shape, diagItems(v)) + } + if len(r.deferred) > 0 { + fmt.Fprintf(&b, "\n### Deferred conflicts\n\nThese do not pick cleanly onto this branch. Each names the first of its commits that conflicted and the files it conflicted in, and nothing of it is on the branch. Each moves to the next batch, unless a resolution checked with `backport-batch fold` is pushed here first, as [resolving a conflict](%sresolve-conflict.md) describes.\n\n", tasksURL) + for _, p := range r.deferred { + var files []string + for _, f := range p.files[:min(len(p.files), filesListed)] { + files = append(files, codeSpan(f)) + } + if more := len(p.files) - len(files) + p.more; more > 0 { + files = append(files, fmt.Sprintf("%d more", more)) + } + at := "" + if p.failed != "" { + at = " at " + codeSpan(p.failed[:12]) + } + fmt.Fprintf(&b, "- %s %s%s: %s\n%s", prLink(p.v.o.number), titleSpan(p.v.o.title), at, strings.Join(files, ", "), diagItems(p.v)) + } + } + if len(r.held) > 0 { + b.WriteString("\n### Deferred to the next batch\n\nTaken out of this batch with `backport-batch run --defer`, each for the reason given. This pull request keeps them out; the next batch picks them again.\n\n") + for _, p := range r.held { + fmt.Fprintf(&b, "- %s %s: %s\n%s", prLink(p.v.o.number), titleSpan(p.v.o.title), titleSpan(p.reason), diagItems(p.v)) + } + } + if len(r.waiting) > 0 { + fmt.Fprintf(&b, "\n### Waiting for a maintainer\n\nThese change `%s`, which the token this batch runs with may not push, so it leaves them out. The policy still takes each, and `backport-batch check` lists it until it is on the line. A maintainer brings one over as [changes to workflows](%s#changes-to-workflows) describes.\n\n", workflowsDir, policyURL) + for _, p := range r.waiting { + var files []string + for _, f := range p.files[:min(len(p.files), filesListed)] { + files = append(files, codeSpan(f)) + } + if more := len(p.files) - len(files) + p.more; more > 0 { + files = append(files, fmt.Sprintf("%d more", more)) + } + fmt.Fprintf(&b, "- %s %s: %s\n%s", prLink(p.v.o.number), titleSpan(p.v.o.title), strings.Join(files, ", "), diagItems(p.v)) + } + } + if changed := r.changed(); len(changed) > 0 { + b.WriteString("\n### Check these notes\n\nThese picks differ from their originals, so their release notes are left out of the release-note block until someone checks that each still holds for this line. Each comes with what to compare: every pick that differs against the commit it came from, and the original's change against the unit's.\n") + for _, v := range changed { + s := r.shapes[v] + fmt.Fprintf(&b, "\n%s %s, carried by %s:\n\n", prLink(v.o.number), titleSpan(v.o.title), codeSpan(s.unit[:12])) + if n := releaseNote(v.o.body); n != "" { + fmt.Fprintf(&b, "```text\n%s\n```\n\n", neutralNote(n)) + } else { + b.WriteString("It has no release note.\n\n") + } + for _, p := range s.pairs { + fmt.Fprintf(&b, "- %s\n", codeSpan(fmt.Sprintf("git range-diff --creation-factor=999 %s^! %s^!", p.source[:12], p.pick[:12]))) + } + fmt.Fprintf(&b, "- %s\n- %s\n", codeSpan(fmt.Sprintf("git diff %s^1 %s", v.o.merge[:12], v.o.merge[:12])), codeSpan(fmt.Sprintf("git diff %s^1 %s", s.unit[:12], s.unit[:12]))) + } + } + if len(r.partial) > 0 { + fmt.Fprintf(&b, "\n### Still on this branch: only part of it applies\n\nEach of these is on this branch but leaves files of its original as they were on %s, so it carries only part of what it does on `main`. Take each out with `backport-batch run --defer` before the cut; what applies of it goes as a pull request of its own.\n\n", codeSpan(r.line.branch())) + for _, v := range r.partial { + fmt.Fprintf(&b, "- %s %s: leaves %s without effect\n", prLink(v.o.number), titleSpan(v.o.title), fileSpans(r.partialFiles[v])) + } + } + if len(r.parked) > 0 { + fmt.Fprintf(&b, "\n### Parked\n\nThese cannot land on %s whole, so the batch does not pick them: each would leave part of it without effect there, or builds on a change that never reaches the line. A maintainer ports what applies as a pull request of its own, or drops the original with `backport-batch run --drop`; `backport/include` does not lift a park.\n\n", codeSpan(r.line.branch())) + for _, v := range r.parked { + fmt.Fprintf(&b, "- %s %s: %s\n%s", prLink(v.o.number), titleSpan(v.o.title), parkReason(*v.park), diagItems(v)) + } + } + if len(r.needs) > 0 { + fmt.Fprintf(&b, "\n### Waiting on another original\n\nThese build on another original that has not reached %s yet, so the batch does not try them; each names the one it waits on, and the batch tries it again once that one is there.\n\n", codeSpan(r.line.branch())) + for _, p := range r.needs { + fmt.Fprintf(&b, "- %s %s: after %s\n%s", prLink(p.v.o.number), titleSpan(p.v.o.title), prLinks(p.needs), diagItems(p.v)) + } + } + if len(r.overrides) > 0 { + b.WriteString("\n### Maintainer overrides\n\n") + for _, v := range r.overrides { + fmt.Fprintf(&b, "- %s %s: %s, %s\n", prLink(v.o.number), titleSpan(v.o.title), codeSpan(v.label), r.outcome(v)) + } + } + b.WriteString("\n### Skipped\n\n") + for _, rule := range skipRules { + items := r.skipped[rule] + if len(items) == 0 { + continue + } + left := "" + if !details[rule] { + left = ", too many to list here; the run's output lists them" + } + fmt.Fprintf(&b, "- %s: %d%s\n", r.listTitle(rule), len(items), left) + } + if r.other > 0 { + fmt.Fprintf(&b, "- Commits on `main` that merged no pull request: %d\n", r.other) + } + for _, rule := range skipRules { + items := r.skipped[rule] + if len(items) > 0 && details[rule] { + fmt.Fprintf(&b, "\n
%s\n\n", r.listTitle(rule)) + for _, v := range items { + fmt.Fprintf(&b, "- %s %s, %s\n", prLink(v.o.number), titleSpan(v.o.title), titleSpan(v.reason)) + } + b.WriteString("\n
\n") + } + } + b.WriteString("\n" + r.blocks + "\n") + return b.String() +} + +// outcome is what became of an original a label overrode. +func (r *report) outcome(v *verdict) string { + switch { + case slices.Contains(r.partial, v): + return "still on this branch, but only part of it applies; take it out with `backport-batch run --defer`" + case slices.Contains(r.stale, v) && v.rule == ruleDropped: + return "dropped, but still on this branch; take it out with `backport-batch run --defer`" + case slices.Contains(r.stale, v): + return "still on this branch, picked before the label; take it out with `backport-batch run --defer`" + case v.label == labelSkip: + return "left out" + case slices.Contains(r.onBranch, v): + return "on this branch" + case slices.ContainsFunc(r.deferred, func(p pick) bool { return p.v == v }): + return "a deferred conflict" + case slices.ContainsFunc(r.held, func(p pick) bool { return p.v == v }): + return "deferred to the next batch" + case slices.ContainsFunc(r.waiting, func(p pick) bool { return p.v == v }): + return "waiting for a maintainer: it changes " + codeSpan(workflowsDir) + case slices.Contains(r.parked, v): + return "parked: " + parkReason(*v.park) + case slices.ContainsFunc(r.needs, func(p pick) bool { return p.v == v }): + i := slices.IndexFunc(r.needs, func(p pick) bool { return p.v == v }) + return "waiting on " + prLinks(r.needs[i].needs) + case v.rule != 0: + return "skipped by " + ruleName(v.rule) + ", " + titleSpan(v.reason) + } + return "not picked" +} + +// diagItems lists, under an original's line, what could not be judged about +// it or what it was seen to build on, each as a code span. +func diagItems(v *verdict) string { + var b strings.Builder + for _, d := range v.diag { + fmt.Fprintf(&b, " - %s\n", titleSpan(d)) + } + return b.String() +} + +// fileSpans lists files as code spans, the first few of them. +func fileSpans(files []string) string { + var out []string + for _, f := range files[:min(len(files), filesListed)] { + out = append(out, codeSpan(f)) + } + if more := len(files) - len(out); more > 0 { + out = append(out, fmt.Sprintf("%d more", more)) + } + return strings.Join(out, ", ") +} + +// prLinks links to pull requests by number. +func prLinks(numbers []int) string { + var out []string + for _, n := range numbers { + out = append(out, prLink(n)) + } + return strings.Join(out, ", ") +} + +// parkReason says why a park leaves its original out, for the body. +func parkReason(p parkedEntry) string { + if p.Kind == parkPartial { + return "only part of it applies; it would leave " + fileSpans(p.Files) + " without effect" + } + var needs []string + for _, n := range p.Needs { + needs = append(needs, prLink(n)) + } + for _, c := range p.Commits { + needs = append(needs, codeSpan(c[:12])) + } + return "builds on " + strings.Join(needs, ", ") + ", which never reaches this line" +} + +// changed lists the originals on the branch whose unit differs from them, in +// merge order. +func (r *report) changed() []*verdict { + var out []*verdict + for _, v := range r.onBranch { + if s, ok := r.shapes[v]; ok && s.changed() { + out = append(out, v) + } + } + return out +} + +// notes are the release notes of what the branch carries as its originals +// made it; a changed pick's note waits under Check these notes. +func (r *report) notes() string { + var notes []string + for _, v := range r.onBranch { + if s, ok := r.shapes[v]; ok && s.changed() { + continue + } + if n := releaseNote(v.o.body); n != "" { + notes = append(notes, neutralNote(n)) + } + } + return strings.Join(notes, "\n\n") +} + +// section is one heading of the pull request template and what follows it. +type section struct { + heading string + text string +} + +func sections(template string) (string, []section) { + var lead strings.Builder + var out []section + inFence := false + for _, ln := range strings.Split(htmlCommentRE.ReplaceAllString(template, ""), "\n") { + if strings.HasPrefix(strings.TrimSpace(ln), "```") { + inFence = !inFence + } + if !inFence && headingRE.MatchString(ln) { + out = append(out, section{heading: ln}) + continue + } + if len(out) == 0 { + lead.WriteString(ln + "\n") + } else { + out[len(out)-1].text += ln + "\n" + } + } + return strings.TrimSpace(lead.String()), out +} + +func headingIs(heading, name string) bool { + return strings.EqualFold(strings.TrimSpace(strings.TrimLeft(heading, "#")), name) +} + +// body fills the line's own pull request template: the What, Screenshots and +// Release note sections are the batch's, every other section stays as the +// template has it. A body over GitHub's limit loses its longest skipped lists +// first, and its release notes' tail last; left out are the rules whose lists +// it lost. +func (r *report) body(template string) (body string, left []int) { + details := map[int]bool{} + for rule, items := range r.skipped { + details[rule] = len(items) > 0 + } + notes := r.notes() + for { + full := r.render(template, r.what(details), notes) + if len(full) <= bodyLimit { + return full, left + } + longest := 0 + for _, rule := range skipRules { + if details[rule] && (longest == 0 || len(r.skipped[rule]) > len(r.skipped[longest])) { + longest = rule + } + } + if longest == 0 { + const marker = "\n\n(release notes truncated; see the original pull requests)" + cut := max(0, len(notes)-(len(full)-bodyLimit)-len(marker)) + for cut > 0 && !utf8Start(notes[cut]) { + cut-- + } + return r.render(template, r.what(details), notes[:cut]+marker), left + } + details[longest] = false + left = append(left, longest) + } +} + +func utf8Start(c byte) bool { return c&0xC0 != 0x80 } + +func (r *report) render(template, what, notes string) string { + lead, secs := sections(template) + var b strings.Builder + if lead != "" { + b.WriteString(lead + "\n\n") + } + seen := map[string]bool{} + for _, s := range secs { + switch { + case headingIs(s.heading, "What this PR does"): + seen["what"] = true + b.WriteString(s.heading + "\n\n" + what + "\n") + case headingIs(s.heading, "Screenshots"): + b.WriteString(s.heading + "\n\nSee the original pull requests.\n\n") + case headingIs(s.heading, "Release note"): + seen["note"] = true + b.WriteString(s.heading + "\n\n```release-note\n" + notes + "\n```\n\n") + default: + b.WriteString(s.heading + "\n\n" + strings.TrimSpace(s.text) + "\n\n") + } + } + out := b.String() + if !seen["what"] { + out = "## What this PR does\n\n" + what + "\n" + out + } + if !seen["note"] { + out += "### Release note\n\n```release-note\n" + notes + "\n```\n" + } + return strings.TrimSpace(regexp.MustCompile(`\n{3,}`).ReplaceAllString(out, "\n\n")) + "\n" +} diff --git a/cmd/backport-batch/body_test.go b/cmd/backport-batch/body_test.go new file mode 100644 index 000000000..3f746d17d --- /dev/null +++ b/cmd/backport-batch/body_test.go @@ -0,0 +1,382 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package main + +import ( + "fmt" + "os" + "path/filepath" + "regexp" + "slices" + "strings" + "testing" + "unicode" +) + +// visible is what of a body GitHub renders as markdown rather than shows as +// code: fenced blocks and code spans taken out, delimited as CommonMark +// delimits them. Everything carried has to be gone from it. +func visible(body string) string { + fenceOpen := regexp.MustCompile("^(`{3,}|~{3,})") + var out []string + fence := "" + for _, ln := range strings.Split(body, "\n") { + t := strings.TrimLeft(ln, " ") + indented := len(ln)-len(t) > 3 + if fence != "" { + run := strings.TrimLeft(t, fence[:1]) + if !indented && len(t)-len(run) >= len(fence) && strings.TrimSpace(run) == "" { + fence = "" + } + continue + } + if m := fenceOpen.FindString(t); m != "" && !indented && (m[0] == '~' || !strings.Contains(t[len(m):], "`")) { + fence = m + continue + } + out = append(out, stripSpans(ln)) + } + return strings.Join(out, "\n") +} + +func stripSpans(s string) string { + var b strings.Builder + for i := 0; i < len(s); { + switch { + case s[i] == '\\' && i+1 < len(s): + b.WriteString(s[i : i+2]) + i += 2 + continue + case s[i] != '`': + b.WriteByte(s[i]) + i++ + continue + } + j := i + for j < len(s) && s[j] == '`' { + j++ + } + n, closing := j-i, -1 + for k := j; k < len(s); { + if s[k] != '`' { + k++ + continue + } + e := k + for e < len(s) && s[e] == '`' { + e++ + } + if e-k == n { + closing = k + break + } + k = e + } + if closing < 0 { + b.WriteString(s[i:j]) + i = j + continue + } + i = closing + n + } + return b.String() +} + +// hostile is carried text built to get out of its span or block: each carries +// a marker that must never be visible. +var hostile = []string{ + "zqx01 thanks @alice", + "zqx02 (@org/team) please look", + "zqx03 [@bob](https://evil.example/x) [docs](https://github.com/cozystack/cozystack/../../evil/repo)", + "zqx04 zero\u200b@carol bidi \u202e@dave \ufeff@erin", + "zqx05 ``` `@frank` ``` still inside", + "zqx06 ` closes a single span, then @grace", + "zqx07 `` `` ``` ```` four", + "zqx08 Fixes #1, closes other/repo#2, resolves https://github.com/other/repo/issues/3", + "zqx09 x", + "zqx10 www.evil.example ", + "zqx11 [ref]: https://evil.example", + "zqx12 @heidi & <b>", + "zqx13 \x1b[31mred\x1b[0m \u009b2J \x07 bell", + "zqx14
x", + "`zqx15` starts and ends with a backtick`", +} + +// hostileNote is a release note whose own block a bare fence line would end, +// so it hides one behind a zero-width space, which clean then removes. +func hostileNote(i int, s string) string { + return fmt.Sprintf("fix(x): zqn%02d %s\n\u200b```\n@ivan zqn%02d after a fence\n~~~\n[@judy](https://evil.example) Fixes #9 \x1b[2J", i, s, i) +} + +// Every carried title, reason and release note stays inside a code span or the +// release-note block, however it is written. +func TestBodyContainsCarriedText(t *testing.T) { + f := newFixture(t) + f.lines() + for i, s := range hostile { + typ := "fix" + if i%2 == 1 { + typ = "feat" // skipped, so it lands in a
list + } + body := "## What this PR does\n\n```release-note\n" + hostileNote(i, s) + "\n```\n" + f.pr(100+i, typ+"(x): "+s, body, map[string]string{fmt.Sprintf("app/%d.txt", i): "x\n"}) + } + gh := &fakeGH{} + code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--push") + if code != 0 { + t.Fatalf("run = %d\n%s", code, stderr) + } + if len(gh.bodies) != 1 { + t.Fatalf("gh got %d bodies, want 1", len(gh.bodies)) + } + for _, body := range []string{gh.bodies[0], stdout} { + for i := range hostile { + title, note := fmt.Sprintf("zqx%02d", i+1), fmt.Sprintf("zqn%02d", i) + if i == len(hostile)-1 { + title = "zqx15" + } + if !strings.Contains(body, title) { + t.Errorf("%s is missing from the body", title) + } + if i%2 == 0 && !strings.Contains(body, note) { + t.Errorf("%s is missing from the release notes", note) + } + } + if v := visible(body); strings.Contains(v, "zqx") || strings.Contains(v, "zqn") { + t.Errorf("carried text is visible outside code:\n%s", v) + } + for _, r := range body { + if r != '\n' && r != '\t' && unicode.IsControl(r) || unicode.Is(unicode.Cf, r) { + t.Errorf("the body carries %U", r) + break + } + } + } +} + +// Copied out of the fenced block, a note must still close, ping and link +// nothing. +func TestNeutralNote(t *testing.T) { + cases := []struct{ in, gone string }{ + {"thanks @alice", "@alice"}, + {"(@org/team) look", "@org/team"}, + {"[@bob](https://evil.example)", "@bob"}, + {"x\u200b@carol", "@carol"}, + {"a@dave.example", "@dave"}, + {"Fixes #1", "Fixes #1"}, + {"closes other/repo#2", "other/repo#2"}, + {"see other/repo#3", "other/repo#3"}, + {"resolves https://github.com/other/repo/issues/3", "github.com/other"}, + {"Fixes https://github.com/cozystack/cozystack/issues/3", "Fixes https://"}, + {"x``@erin", "@erin"}, + {"`code @frank here`", "@frank"}, + {"```@grace```", "@grace"}, + {"go to https://evil.example/x", "evil.example"}, + {"go to www.evil.example", "evil.example"}, + {"[docs](https://evil.example)", "evil.example"}, + {"[docs](https://github.com/cozystack/cozystack/../../evil/repo)", "evil/repo"}, + {"line\n```\nescaped", "```"}, + {"line\n~~~\nescaped", "~~~"}, + {"zero\u200b``\u200b`", "```"}, + {"\x1b[2J", "\x1b"}, + } + for _, tc := range cases { + got := neutralNote(tc.in) + if strings.Contains(visible(got), tc.gone) { + t.Errorf("neutralNote(%q) = %q, still shows %q", tc.in, got, tc.gone) + } + } + keep := "see https://github.com/cozystack/cozystack/blob/main/docs/release/backports.md" + if got := neutralNote(keep); got != keep { + t.Errorf("neutralNote(%q) = %q, want a link into this repository kept", keep, got) + } +} + +func TestCodeSpan(t *testing.T) { + cases := []string{"plain", "a `b` c", "``x``", "`lead", "trail`", "", "a\nb", "````", "\x1b[31m`\u202e`"} + for _, s := range cases { + got := codeSpan(s) + if v := visible(got); v != "" { + t.Errorf("codeSpan(%q) = %q leaves %q outside the span", s, got, v) + } + if strings.ContainsAny(got, "\n\x1b\u202e") { + t.Errorf("codeSpan(%q) = %q carries a newline or a control", s, got) + } + } +} + +func TestDeferredRoundTrip(t *testing.T) { + l, _ := parseLine("release-1.6") + v := &verdict{o: &original{number: 3735}} + held := &verdict{o: &original{number: 3736}} + block := deferredBlock(l, []pick{{v: v, files: []string{"a\n```\nb", "&d", "e`f"}}}, []pick{{v: held, reason: "breaks\n```\ne2e"}}, nil) + if lines := strings.Split(block, "\n"); len(lines) != 3 { + t.Fatalf("the block is %d lines, want 3:\n%s", len(lines), block) + } + body := "## What this PR does\n\ntext\n\n" + block + "\n\n### Release note\n" + got, err := parseDeferred(body, l) + if err != nil || len(got) != 2 || len(got[3735].Files) != 3 || got[3735].Reason != "" { + t.Errorf("parseDeferred = %v, %v; want the conflict #3735 with its files", got, err) + } + if e := got[3736]; e.Reason != "breaks ``` e2e" || len(e.Files) != 0 { + t.Errorf("parseDeferred = %+v; want #3736 held, for its reason on one line", e) + } + if strings.ContainsAny(strings.Split(block, "\n")[1], "<>&") { + t.Errorf("the JSON line carries raw HTML characters: %s", block) + } + + other, _ := parseLine("release-1.5") + for name, body := range map[string]string{ + "another line": body, + "two blocks": body + "\n" + block, + "not JSON": deferredFence + "\nnot json\n```", + "an unknown key": deferredFence + "\n{\"line\":\"release-1.6\",\"deferred\":[],\"x\":1}\n```", + "a bad number": deferredFence + "\n{\"line\":\"release-1.6\",\"deferred\":[{\"original\":-1}]}\n```", + "a repeat": deferredFence + "\n{\"line\":\"release-1.6\",\"deferred\":[{\"original\":5},{\"original\":5,\"reason\":\"x\"}]}\n```", + "a bad commit": deferredFence + "\n{\"line\":\"release-1.6\",\"deferred\":[{\"original\":5,\"commit\":\"-x\"}]}\n```", + "a broken fence": deferredFence + "\n{}\nmore\n```", + "an empty fence": deferredFence + "\n```", + "a trailing line": deferredFence, + } { + want := l + if name == "another line" { + want = other + } + if _, err := parseDeferred(body, want); err == nil { + t.Errorf("%s: parseDeferred accepted it", name) + } + } + if got, err := parseDeferred("no block here", l); err != nil || len(got) != 0 { + t.Errorf("no block: %v, %v; want nothing deferred", got, err) + } +} + +func TestReleaseNote(t *testing.T) { + cases := map[string]string{ + "### Release note\n\n```release-note\nfix(x): y\n```\n": "fix(x): y", + "```release-note\nNONE\n```": "", + "```release-note\n\n```": "", + "": "", + "no block": "", + } + for body, want := range cases { + if got := releaseNote(body); got != want { + t.Errorf("releaseNote(%q) = %q, want %q", body, got, want) + } + } +} + +// The body is the line's template with the batch's sections filled in, and +// fits the size GitHub accepts. +func TestBodyFollowsTheTemplate(t *testing.T) { + l, _ := parseLine("release-1.6") + template := "\n\n## What this PR does\n\n\n### Screenshots\n\n\n\n### Downstream repositories\n\n- [ ] No downstream repository is affected by this change\n\n### Release note\n\n```release-note\n\n```\n" + o := &original{number: 7, title: "fix(x): y", body: "```release-note\nfix(x): note\n```"} + r := &report{line: l, onBranch: []*verdict{{o: o}}, skipped: map[int][]*verdict{}, blocks: deferredBlock(l, nil, nil, nil)} + body, _ := r.body(template) + for _, want := range []string{"## What this PR does\n\nBackports to", "- [#7](https://github.com/cozystack/cozystack/pull/7) `fix(x): y`", "### Downstream repositories\n\n- [ ] No downstream", "```release-note\nfix(x): note\n```", deferredFence} { + if !strings.Contains(body, want) { + t.Errorf("the body lacks %q:\n%s", want, body) + } + } + if strings.Contains(body, "" + +// stalledAfter is how many days a batch stays open before notify calls it +// stalled: the shorter gap between two scheduled runs, Monday to Thursday, so +// a batch the previous run opened or continued is stalled at the next one. +const stalledAfter = 3 + +var mentionRE = regexp.MustCompile(`^@?([A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:/[A-Za-z0-9_.-]+)?)$`) + +// notify reports what waits on the open batch pull request of a line for a +// maintainer: a batch open since before the previous run, the conflicts it +// deferred, and the originals that change workflows. One line per finding goes +// to stdout, for the run's summary. --push writes them into the comment, one +// per pull request, updated in place on every run. +func (a *app) notify(args []string) int { + fs := a.flags("notify") + lineArg := fs.String("line", "", "release line, release-X.Y") + mention := fs.String("mention", "", "team or person the comment mentions, org/team or login, with or without @") + push := fs.Bool("push", false, "write the comment") + if err := parse(fs, args); err != nil { + return 2 + } + l, err := parseLine(*lineArg) + if err != nil { + return a.fail(err) + } + if *mention != "" { + m := mentionRE.FindStringSubmatch(*mention) + if m == nil { + return a.fail(fmt.Errorf("--mention %q is not @login or @org/team", *mention)) + } + *mention = "@" + m[1] + } + prs, err := a.gh.openPulls(l.branch()) + if err != nil { + return a.fail(err) + } + pr, warnings, err := batchPull(a.gh, prs, l) + for _, w := range warnings { + a.warn("%s", w) + } + if err != nil { + return a.fail(err) + } + // With no batch open there is nothing to report on and nowhere to write, + // but a record nobody can read is said all the same. + src, err := findLineRecord(a.gh, l, pr) + if err != nil { + return a.fail(err) + } + if c := src.closingOpen(); c != nil { + return a.fail(fmt.Errorf("batch pull request #%d is being closed; backport-batch run --line %s --push finishes it", c.PR, l.branch())) + } + if pr == nil { + return 0 + } + opened, err := branchDate(pr.Head.Ref) + if err != nil { + return a.fail(err) + } + deferred := map[int]deferredEntry{} + var partial []int + var parks []parkedEntry + if src.open { + deferred, partial = src.rec.deferred(), src.rec.Partial + for _, p := range src.rec.Parked { + if !p.Announced { + parks = append(parks, p) + } + } + } + // An original that waits on others is listed once, after what decides + // its wait, where that one is listed. + var conflicts, waiting []int + after := map[int][]int{} + for n, e := range deferred { + switch placement(deferred, n, map[int]bool{}) { + case "workflow": + waiting = append(waiting, n) + case "conflict": + conflicts = append(conflicts, n) + } + if len(e.Needs) > 0 { + after[n] = e.Needs + } + } + slices.Sort(conflicts) + slices.Sort(waiting) + item := func(n int) string { + if needs := after[n]; len(needs) > 0 { + return fmt.Sprintf("\n- %s, after %s", prLink(n), prLinks(needs)) + } + return "\n- " + prLink(n) + } + count := func(ns []int) int { + c := 0 + for _, n := range ns { + if len(after[n]) == 0 { + c++ + } + } + return c + } + + today := a.now().UTC().Truncate(24 * time.Hour) + days := int(today.Sub(opened).Hours() / 24) + stalled := days >= stalledAfter + var text []string + if stalled { + _, _ = fmt.Fprintf(a.stdout, "%s: batch pull request #%d has been open since %s, %d days\n", l.branch(), pr.Number, opened.Format(time.DateOnly), days) + text = append(text, fmt.Sprintf("This batch has been open since %s, %d days, through at least one scheduled run. Merge it, or close it and the next run starts a new one; until then each run adds what the rules take to it.", opened.Format(time.DateOnly), days)) + } + if len(partial) > 0 { + _, _ = fmt.Fprintf(a.stdout, "%s: %d units on #%d carry only part of their originals\n", l.branch(), len(partial), pr.Number) + var b strings.Builder + b.WriteString("These are on the batch but carry only part of their originals on this line; take each out with `backport-batch run --defer` before the cut, and port what applies as a pull request of its own:\n") + for _, n := range partial { + b.WriteString(item(n)) + } + text = append(text, b.String()) + } + if len(conflicts) > 0 { + _, _ = fmt.Fprintf(a.stdout, "%s: %d deferred conflicts on #%d wait for a maintainer\n", l.branch(), count(conflicts), pr.Number) + var b strings.Builder + fmt.Fprintf(&b, "These conflicts wait for a maintainer, as [resolving a conflict](%sresolve-conflict.md) describes; unresolved, each goes to the next batch, and so does what waits on one:\n", tasksURL) + for _, n := range conflicts { + b.WriteString(item(n)) + } + text = append(text, b.String()) + } + if len(waiting) > 0 { + if count(waiting) == len(waiting) { + _, _ = fmt.Fprintf(a.stdout, "%s: %d originals on #%d change %s and wait for a maintainer\n", l.branch(), len(waiting), pr.Number, workflowsDir) + } else { + _, _ = fmt.Fprintf(a.stdout, "%s: %d originals on #%d change %s or wait on one that does\n", l.branch(), len(waiting), pr.Number, workflowsDir) + } + var b strings.Builder + fmt.Fprintf(&b, "These change `%s`, which the batch's token may not push, and wait for a maintainer to bring them over, as [changes to workflows](%s#changes-to-workflows) describes, or wait on one that does:\n", workflowsDir, policyURL) + for _, n := range waiting { + b.WriteString(item(n)) + } + text = append(text, b.String()) + } + if len(parks) > 0 { + _, _ = fmt.Fprintf(a.stdout, "%s: %d parked originals on #%d, named once\n", l.branch(), len(parks), pr.Number) + var b strings.Builder + fmt.Fprintf(&b, "These cannot land on this line whole, so the batch parked them; each is named here once. A maintainer ports what applies as a pull request of its own, as [fixes that exist only on a release line](%s#fixes-that-exist-only-on-a-release-line) describes, or drops the original with `backport-batch run --drop`:\n", policyURL) + for _, p := range parks { + fmt.Fprintf(&b, "\n- %s: %s", prLink(p.Original), parkReason(p)) + } + text = append(text, b.String()) + } + if !*push { + return 0 + } + if code := a.comment(pr, *mention, today, text); code != 0 || len(parks) == 0 { + return code + } + if err := a.announced(pr, src.rec, parks); err != nil { + return a.fail(fmt.Errorf("%w; the next notify names them again", err)) + } + return 0 +} + +// announced marks parks as named in the record of the open batch pull +// request, which the comment just named: only while it is open and its body +// still carries the record notify read, so a run that rewrote the body +// meanwhile loses nothing; the next notify names those parks again. +func (a *app) announced(pr *pullRequest, rec *lineRecord, parks []parkedEntry) error { + marked := *rec + marked.Parked = slices.Clone(rec.Parked) + for i, p := range marked.Parked { + if slices.ContainsFunc(parks, func(q parkedEntry) bool { return q.Original == p.Original && parkEvent(q) == parkEvent(p) }) { + marked.Parked[i].Announced = true + } + } + now, err := a.gh.pull(pr.Number) + if err != nil { + return err + } + if st := prState(&now); st != "open" { + return fmt.Errorf("batch pull request #%d is %s now; nothing is written to it", pr.Number, st) + } + lines, err := fencedLines(now.Body, deferredFence) + if err != nil || len(lines) != 1 { + return fmt.Errorf("batch pull request #%d no longer carries the record notify read", pr.Number) + } + read, err := parseRecord(now.Body, notifyLineOf(rec)) + if err != nil || recordBlock(*read) != recordBlock(*rec) { + return fmt.Errorf("batch pull request #%d no longer carries the record notify read", pr.Number) + } + // GitHub keeps the CRLF line ends a body edited on the web has; the + // record is found, and the body written back, with LF ones. + body := strings.ReplaceAll(now.Body, "\r\n", "\n") + block := deferredFence + "\n" + lines[0] + "\n```" + if strings.Count(body, block) != 1 { + return fmt.Errorf("batch pull request #%d carries the record notify read, but not as one block it can mark", pr.Number) + } + body = strings.Replace(body, block, recordBlock(marked), 1) + name, err := writeTemp("backport-batch-body-*.md", body) + if err != nil { + return err + } + defer func() { _ = os.Remove(name) }() + return a.gh.editBody(pr.Number, name) +} + +// notifyLineOf is the line a record is for, which it was read against. +func notifyLineOf(rec *lineRecord) line { + l, _ := parseLine(rec.Line) + return l +} + +// placement says under which list notify names original n of the record: +// workflow for a wait for a maintainer, conflict for a deferred conflict, "" +// for neither, a deferral for a reason among them. One that waits on others +// goes where what decides its wait goes, followed down the record; one that +// is not in the record is held by rule 6 or missing, and waits on nobody. +func placement(deferred map[int]deferredEntry, n int, seen map[int]bool) string { + e, ok := deferred[n] + switch { + case !ok || seen[n]: + return "" + case e.Workflows: + return "workflow" + case e.Reason != "": + return "" + case len(e.Needs) == 0: + return "conflict" + } + seen[n] = true + place := "" + for _, f := range e.Needs { + switch p := placement(deferred, f, seen); p { + case "workflow": + return p + case "conflict": + place = p + } + } + return place +} + +// comment writes what waits into the one notify comment on the batch pull +// request: it edits the comment if there is one, and opens it only when +// something waits. Only a comment by an author the batch trusts is taken for +// it, so a look-alike someone else wrote is neither edited nor believed. +func (a *app) comment(pr *pullRequest, mention string, today time.Time, text []string) int { + comments, err := a.gh.comments(pr.Number) + if err != nil { + return a.fail(err) + } + var ours *issueComment + for i := range comments { + c := &comments[i] + if !strings.HasPrefix(c.Body, notifyMarker) { + continue + } + why, err := trustedAuthor(a.gh, c.User.Login, c.User.Type) + if err != nil { + return a.fail(err) + } + if why == "" { + ours = c + } + } + if ours == nil && len(text) == 0 { + return 0 + } + var b strings.Builder + b.WriteString(notifyMarker + "\n") + if mention != "" && len(text) > 0 { + b.WriteString(mention + "\n\n") + } + if len(text) == 0 { + text = []string{"Nothing waits on a maintainer."} + } + b.WriteString(strings.Join(text, "\n\n")) + fmt.Fprintf(&b, "\n\nUpdated by the backport batch on %s.\n", today.Format(time.DateOnly)) + f, err := os.CreateTemp("", "backport-batch-comment-*.md") + if err != nil { + return a.fail(err) + } + defer func() { _ = os.Remove(f.Name()) }() + if _, err := f.WriteString(b.String()); err != nil { + _ = f.Close() + return a.fail(err) + } + if err := f.Close(); err != nil { + return a.fail(err) + } + if err := a.stillOpen(pr.Number); err != nil { + return a.fail(err) + } + if ours != nil { + err = a.gh.editComment(ours.ID, f.Name()) + } else { + err = a.gh.createComment(pr.Number, f.Name()) + } + if err != nil { + return a.fail(err) + } + return 0 +} + +// lines prints the lines the batch runs for, newest first, in the order the +// policy has them processed. +func (a *app) lines(args []string) int { + fs := a.policyFlags("lines") + if err := parse(fs, args); err != nil { + return 2 + } + if err := fetch(); err != nil { + return a.fail(err) + } + mainHead, err := resolve("refs/remotes/" + remote + "/main") + if err != nil { + return a.fail(err) + } + pol, _, err := a.policy(mainHead) + if err != nil { + return a.fail(err) + } + lines, err := batchLines(pol.released) + if err != nil { + return a.fail(err) + } + for _, l := range slices.Backward(lines) { + _, _ = fmt.Fprintln(a.stdout, l.branch()) + } + return 0 +} diff --git a/cmd/backport-batch/notify_test.go b/cmd/backport-batch/notify_test.go new file mode 100644 index 000000000..7f870baee --- /dev/null +++ b/cmd/backport-batch/notify_test.go @@ -0,0 +1,496 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package main + +import ( + "bytes" + "errors" + "slices" + "strings" + "testing" + "time" +) + +// notifyPR is an open batch pull request for release-1.1 on the branch opened +// on date, YYYYMMDD, with body. +func notifyPR(date, body string) pullRequest { + var pr pullRequest + pr.Number, pr.Body = 90, body + pr.User.Login, pr.User.Type = "maintainer", "User" + pr.Head.Ref, pr.Head.SHA = "backport-batch/release-1.1-"+date, strings.Repeat("a", 40) + pr.Head.Repo = &struct { + FullName string `json:"full_name"` + }{upstreamRepo} + pr.Base.Ref, pr.Base.Repo.FullName = "release-1.1", upstreamRepo + return pr +} + +// notifyRun runs notify on 2026-10-26 with gh faked. +func notifyRun(gh *fakeGH, args ...string) (int, string, string) { + var stdout, stderr bytes.Buffer + a := &app{gh: gh, stdout: &stdout, stderr: &stderr, now: func() time.Time { return time.Date(2026, 10, 26, 6, 23, 0, 0, time.UTC) }} + code := a.main(append([]string{"notify", "--line", "release-1.1"}, args...)) + return code, stdout.String(), stderr.String() +} + +var notifyLine, _ = parseLine("release-1.1") + +// A batch open since before the previous run gets one comment, mentioning +// the team, and keeps that one comment however many runs see it. +func TestNotifyStalled(t *testing.T) { + for _, tc := range []struct { + date string + stalled bool + }{ + {"20261026", false}, + {"20261024", false}, + {"20261023", true}, + {"20261019", true}, + } { + gh := &fakeGH{prs: []pullRequest{notifyPR(tc.date, "")}} + code, stdout, stderr := notifyRun(gh, "--mention", "cozystack/maintainers", "--push") + if code != 0 { + t.Fatalf("%s: notify = %d\n%s", tc.date, code, stderr) + } + if got := strings.Contains(stdout, "release-1.1: batch pull request #90 has been open since"); got != tc.stalled { + t.Errorf("%s: stalled = %v, want %v:\n%s", tc.date, got, tc.stalled, stdout) + } + if got := len(gh.issueComments); got != map[bool]int{true: 1, false: 0}[tc.stalled] { + t.Errorf("%s: %d comments, want one only when stalled", tc.date, got) + } + if !tc.stalled { + continue + } + c := gh.issueComments[0].Body + if !strings.HasPrefix(c, notifyMarker+"\n@cozystack/maintainers\n") || !strings.Contains(c, "open since") { + t.Errorf("%s: the comment does not mention the team and say why:\n%s", tc.date, c) + } + for range 2 { + if code, _, stderr := notifyRun(gh, "--mention", "@cozystack/maintainers", "--push"); code != 0 { + t.Fatalf("notify again = %d\n%s", code, stderr) + } + } + if len(gh.issueComments) != 1 { + t.Errorf("%s: %d comments after three runs, want the one updated", tc.date, len(gh.issueComments)) + } + } + + gh := &fakeGH{prs: []pullRequest{notifyPR("20261019", "")}} + if code, _, _ := notifyRun(gh, "--push"); code != 0 || strings.Contains(gh.issueComments[0].Body, "@") { + t.Errorf("notify with no team = %d and wrote %q; want no mention", code, gh.issueComments[0].Body) + } + gh = &fakeGH{prs: []pullRequest{notifyPR("20261019", "")}} + if code, stdout, _ := notifyRun(gh); code != 0 || stdout == "" || len(gh.issueComments) != 0 { + t.Errorf("notify without --push = %d, %q and %d comments; want the line and no comment", code, stdout, len(gh.issueComments)) + } +} + +// The comment lists the deferred conflicts for a maintainer, and nothing +// --defer held out. +func TestNotifyConflicts(t *testing.T) { + conflict := pick{v: &verdict{o: &original{number: 6}}, files: []string{"app/six.txt"}} + held := pick{v: &verdict{o: &original{number: 7}}, reason: "fails the e2e"} + body := "text\n\n" + deferredBlock(notifyLine, []pick{conflict}, []pick{held}, nil) + "\n" + + gh := &fakeGH{prs: []pullRequest{notifyPR("20261026", body)}} + code, stdout, stderr := notifyRun(gh, "--mention", "@cozystack/maintainers", "--push") + if code != 0 || !strings.Contains(stdout, "release-1.1: 1 deferred conflicts on #90 wait for a maintainer") { + t.Fatalf("notify = %d, %q\n%s", code, stdout, stderr) + } + if len(gh.issueComments) != 1 { + t.Fatalf("%d comments, want one", len(gh.issueComments)) + } + c := gh.issueComments[0].Body + if !strings.Contains(c, "@cozystack/maintainers") || !strings.Contains(c, "[#6](") || !strings.Contains(c, "resolve-conflict.md") || strings.Contains(c, "#7") { + t.Errorf("the comment does not list #6 alone for a maintainer:\n%s", c) + } +} + +// Only a comment by an author the batch trusts is taken for the notify +// comment: a look-alike is neither edited nor counted. +func TestNotifyKeepsToItsOwnComment(t *testing.T) { + look := issueComment{ID: 7, Body: notifyMarker + "\nplanted"} + look.User.Login, look.User.Type = "someone", "User" + gh := &fakeGH{prs: []pullRequest{notifyPR("20261019", "")}, issueComments: []issueComment{look}} + if code, _, stderr := notifyRun(gh, "--push"); code != 0 { + t.Fatalf("notify = %d\n%s", code, stderr) + } + if len(gh.issueComments) != 2 || gh.issueComments[0].Body != look.Body { + t.Errorf("comments = %+v; want the look-alike untouched and one of ours", gh.issueComments) + } + + // Ours says so once nothing waits any more, and calls nobody for it. + gh.prs = []pullRequest{notifyPR("20261026", "")} + if code, _, _ := notifyRun(gh, "--mention", "@cozystack/maintainers", "--push"); code != 0 || len(gh.issueComments) != 2 || + !strings.Contains(gh.issueComments[1].Body, "Nothing waits") || strings.Contains(gh.issueComments[1].Body, "@cozystack") { + t.Errorf("comments = %+v; want ours updated to say nothing waits, mentioning nobody", gh.issueComments) + } +} + +// The scheduled batch writes as its bot: notify keeps to the comment that bot +// wrote, on a pull request it opened, and to no other bot's. +func TestNotifyFindsTheBotsComment(t *testing.T) { + const bot = "cozystack-ci[bot]" + ours := issueComment{ID: 7, Body: notifyMarker + "\nearlier"} + ours.User.Login, ours.User.Type = bot, "Bot" + other := issueComment{ID: 8, Body: notifyMarker + "\nplanted"} + other.User.Login, other.User.Type = "renovate[bot]", "Bot" + // The bot writes the record into every body it opens. + pr := notifyPR("20261019", deferredBlock(notifyLine, nil, nil, nil)) + pr.User.Login, pr.User.Type = bot, "Bot" + gh := &fakeGH{prs: []pullRequest{pr}, issueComments: []issueComment{ours, other}, bot: bot} + if code, stdout, stderr := notifyRun(gh, "--push"); code != 0 || !strings.Contains(stdout, "has been open since") { + t.Fatalf("notify = %d, %q\n%s", code, stdout, stderr) + } + if len(gh.issueComments) != 2 || !strings.Contains(gh.issueComments[0].Body, "has been open since") || gh.issueComments[1].Body != other.Body { + t.Errorf("comments = %+v; want the bot's own comment edited and the other bot's untouched", gh.issueComments) + } + if code, _, stderr := notifyRun(&fakeGH{prs: []pullRequest{pr}, bot: "cozystack-ci"}, "--push"); code != 2 || !strings.Contains(stderr, batchBotEnv) { + t.Errorf("a %s that is no bot login = %d (%s), want a refusal", batchBotEnv, code, stderr) + } +} + +// A permission GitHub does not answer fails notify before it writes: read as +// a refusal, it would pass over a person's batch, or over the comment notify +// keeps and post a second one. +func TestNotifyFailsOnAnUnreadablePermission(t *testing.T) { + gh := &fakeGH{prs: []pullRequest{notifyPR("20261019", "")}, permErr: errString("HTTP 502")} + if code, stdout, stderr := notifyRun(gh, "--push"); code != 2 || stdout != "" || len(gh.issueComments) != 0 || !strings.Contains(stderr, "HTTP 502") { + t.Errorf("notify on a person's batch = %d, %q, %d comments (%s); want 2 and nothing written", code, stdout, len(gh.issueComments), stderr) + } + + const bot = "cozystack-ci[bot]" + pr := notifyPR("20261019", deferredBlock(notifyLine, nil, nil, nil)) + pr.User.Login, pr.User.Type = bot, "Bot" + ours := issueComment{ID: 7, Body: notifyMarker + "\nearlier"} + ours.User.Login, ours.User.Type = "maintainer", "User" + gh = &fakeGH{prs: []pullRequest{pr}, issueComments: []issueComment{ours}, bot: bot, permErr: errString("HTTP 502")} + if code, _, stderr := notifyRun(gh, "--push"); code != 2 || len(gh.issueComments) != 1 || gh.issueComments[0].Body != ours.Body || !strings.Contains(stderr, "HTTP 502") { + t.Errorf("notify with a person's comment = %d, comments %+v (%s); want 2 and the comment untouched", code, gh.issueComments, stderr) + } +} + +func TestNotifyRefuses(t *testing.T) { + gh := &fakeGH{prs: []pullRequest{notifyPR("20261019", "")}} + for _, args := range [][]string{ + {"--mention", "@a b"}, + {"--mention", "@org/team/x"}, + {"--mention", "@-x"}, + } { + if code, _, _ := notifyRun(gh, args...); code != 2 { + t.Errorf("notify %q = %d, want 2", args, code) + } + } + if code, stdout, _ := notifyRun(&fakeGH{}, "--push"); code != 0 || stdout != "" { + t.Errorf("notify with no batch open = %d, %q; want nothing", code, stdout) + } + pr := notifyPR("20261019", "") + pr.User.Login = "someone" + if code, stdout, _ := notifyRun(&fakeGH{prs: []pullRequest{pr}}, "--push"); code != 0 || stdout != "" { + t.Errorf("notify on a batch someone untrusted opened = %d, %q; want nothing", code, stdout) + } +} + +// notify reads the line's record the way the other commands do, and stays +// silent with no batch open, but a record it cannot read, or one that says +// its open batch is being closed, stops it. +func TestNotifyValidatesTheRecord(t *testing.T) { + sha := strings.Repeat("a", 40) + closingRecord := strings.Replace(v2(""), `"closing":null`, `"closing":{"pr":91,"branch":"backport-batch/release-1.1-20261002","head":"`+sha+`"}`, 1) + block := func(json string) string { return "text\n\n" + deferredFence + "\n" + json + "\n```\n" } + for _, tc := range []struct { + name string + pr pullRequest + code int + quiet bool + }{ + {"a clean closed record", recordPR(91, "closed", "maintainer", block(v2(""))), 0, true}, + {"a malformed record", recordPR(91, "closed", "maintainer", block(`{"line":`)), 2, false}, + {"a closed record that was closing", recordPR(91, "closed", "maintainer", block(closingRecord)), 0, true}, + {"an open record that is closing", recordPR(91, "open", "maintainer", block(closingRecord)), 2, false}, + } { + gh := &fakeGH{prs: []pullRequest{tc.pr}} + code, stdout, stderr := notifyRun(gh, "--push") + if code != tc.code || tc.quiet && (stdout != "" || stderr != "") || len(gh.issueComments) != 0 { + t.Errorf("%s: notify = %d, %q, %q, %d comments; want %d and nothing written", tc.name, code, stdout, stderr, len(gh.issueComments), tc.code) + } + } +} + +// The maintainer's example: with 1.6 and 1.7 released, release-1.8 joins them +// when it branches, and 1.8.0 drops 1.6. +func TestSupportedLines(t *testing.T) { + l := func(minor int) line { return line{1, minor} } + cases := []struct { + name string + all []line + shipped []line + released int + want []line + }{ + {"two released", []line{l(5), l(6), l(7)}, []line{l(5), l(6), l(7)}, 2, []line{l(6), l(7)}}, + {"release-1.8 branched", []line{l(5), l(6), l(7), l(8)}, []line{l(5), l(6), l(7)}, 2, []line{l(6), l(7), l(8)}}, + {"1.8.0 shipped", []line{l(5), l(6), l(7), l(8)}, []line{l(5), l(6), l(7), l(8)}, 2, []line{l(7), l(8)}}, + {"three released", []line{l(5), l(6), l(7), l(8)}, []line{l(5), l(6), l(7)}, 3, []line{l(5), l(6), l(7), l(8)}}, + {"one released", []line{l(6), l(7), l(8)}, []line{l(6), l(7)}, 1, []line{l(7), l(8)}}, + {"a line between releases that never shipped", []line{l(5), l(6), l(7)}, []line{l(5), l(7)}, 2, []line{l(5), l(7)}}, + {"nothing shipped yet", []line{l(0), l(1)}, nil, 2, []line{l(0), l(1)}}, + } + for _, tc := range cases { + shipped := map[line]bool{} + for _, s := range tc.shipped { + shipped[s] = true + } + if got := supportedLines(tc.all, shipped, tc.released); !slices.Equal(got, tc.want) { + t.Errorf("%s: supportedLines = %v, want %v", tc.name, got, tc.want) + } + } +} + +// lines prints the lines the batch runs for, newest first, which is the order +// the scheduled run takes them in: the newest released lines, as many as the +// policy says, and a line branched since, whose stable release drops the +// oldest. +func TestLines(t *testing.T) { + f := newFixture(t) + f.release("release-0.9") + f.tag("v0.9.0") + f.lines() + f.release("release-1.2") + f.release("release-1.2.0-rc.1") + f.tag("v1.2.0-rc.1") + lines := func() string { + t.Helper() + code, stdout, stderr := f.exec(nil, "lines") + if code != 0 { + t.Fatalf("lines = %d (%s)", code, stderr) + } + return stdout + } + if got := lines(); got != "release-1.2\nrelease-1.1\nrelease-1.0\n" { + t.Errorf("with release-1.2 at its first rc, lines = %q; want it before the two released lines", got) + } + f.setPolicy(releasedKey + ": 3\n") + if got := lines(); got != "release-1.2\nrelease-1.1\nrelease-1.0\nrelease-0.9\n" { + t.Errorf("with three released lines, lines = %q; want release-0.9 too", got) + } + f.setPolicy("") + f.tag("v1.2.0") + if got := lines(); got != "release-1.2\nrelease-1.1\n" { + t.Errorf("once v1.2.0 ships, lines = %q; want release-1.0 dropped", got) + } + f.setPolicy(releasedKey + ": 3\n") + if got := lines(); got != "release-1.2\nrelease-1.1\nrelease-1.0\n" { + t.Errorf("once v1.2.0 ships, with three released lines, lines = %q", got) + } +} + +// A scheduled run with nothing to pick for a line succeeds without pushing or +// opening anything. +func TestRunWithNothingToPick(t *testing.T) { + f := newFixture(t) + f.lines() + f.pr(5, "feat(app): five", "", map[string]string{"app/five.txt": "5\n"}) + gh := &fakeGH{} + code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--push") + if code != 0 || !strings.Contains(stderr, "nothing to push") { + t.Errorf("run with nothing to pick = %d, want 0:\n%s", code, stderr) + } + if f.remoteHead(batchBranch1) != "" || len(gh.created) != 0 { + t.Errorf("pushed %q and opened %q with nothing picked", f.remoteHead(batchBranch1), gh.created) + } +} + +// notify writes its comment only after GitHub says the batch is still open, +// so a batch closed while notify reads it is not written to, whether the +// comment would be new or an update of its own. +func TestNotifyWritesNothingOnABatchClosedMeanwhile(t *testing.T) { + for _, update := range []bool{false, true} { + t.Run(map[bool]string{false: "a new comment", true: "an update"}[update], func(t *testing.T) { + gh := &fakeGH{prs: []pullRequest{notifyPR("20261023", recordBody(5))}} + if update { + ours := issueComment{ID: 7, Body: notifyMarker + "\nearlier"} + ours.User.Login, ours.User.Type = "maintainer", "User" + gh.issueComments = []issueComment{ours} + } + gh.after = map[string]func(){"comments": func() { gh.find(90).State = "closed" }} + code, _, stderr := notifyRun(gh, "--push") + if code != 2 || !strings.Contains(stderr, "batch pull request #90 is closed now; nothing is written to it") || len(gh.closedWrites) != 0 || update && gh.issueComments[0].Body != notifyMarker+"\nearlier" { + t.Errorf("notify = %d, closed writes %q, comments %+v; want 2 and nothing written:\n%s", code, gh.closedWrites, gh.issueComments, stderr) + } + }) + } +} + +// parkedBody is an open batch body whose version 3 record parks p. +func parkedBody(p ...parkedEntry) string { + sha := strings.Repeat("a", 40) + rec := lineRecord{Version: recordVersion, Line: "release-1.1", Report: strings.Repeat("b", 64), + Built: &builtFrom{Main: sha, Line: sha, Policy: sha, Batch: sha, At: "2026-10-26T06:00:00Z", Options: runOptions{Mode: modeContinue}}, + Deferred: []deferredEntry{}, Dropped: []droppedEntry{}, Stale: []int{}, Parked: p} + return "batch\n\n" + recordBlock(rec) + "\n" +} + +// notifyAt runs notify at a time of day, with gh faked. +func notifyAt(gh *fakeGH, at time.Time, args ...string) (int, string, string) { + var stdout, stderr bytes.Buffer + a := &app{gh: gh, stdout: &stdout, stderr: &stderr, now: func() time.Time { return at }} + code := a.main(append([]string{"notify", "--line", "release-1.1"}, args...)) + return code, stdout.String(), stderr.String() +} + +// A park is announced once on the open batch: notify names it in its +// comment and marks it announced in the record; a later notify is silent +// about it. A mark that fails to land repeats the announcement once, the +// next day. With no batch open nothing is announced, and the first notify of +// the next batch does it. +func TestNotifyAnnouncesAParkOnce(t *testing.T) { + park := parkedEntry{Original: 5, Merge: strings.Repeat("c", 40), Kind: parkDependency, Needs: []int{3}} + parked := func(gh *fakeGH) []parkedEntry { + t.Helper() + rec, err := parseRecord(gh.prs[0].Body, notifyLine) + if err != nil { + t.Fatal(err) + } + return rec.Parked + } + gh := &fakeGH{prs: []pullRequest{notifyPR("20261026", parkedBody(park))}} + code, stdout, stderr := notifyRun(gh, "--push") + if code != 0 || !strings.Contains(stdout, "release-1.1: 1 parked originals on #90, named once") || len(gh.issueComments) != 1 || !strings.Contains(gh.issueComments[0].Body, "- [#5](https://github.com/cozystack/cozystack/pull/5): builds on [#3](") { + t.Fatalf("notify = %d, want #5 announced:\n%s\n%s\n%v", code, stdout, stderr, gh.issueComments) + } + if p := parked(gh); len(p) != 1 || !p[0].Announced { + t.Errorf("the record parks %+v, want #5 marked announced", p) + } + if code, stdout, _ = notifyRun(gh, "--push"); code != 0 || strings.Contains(stdout, "parked") || strings.Contains(gh.issueComments[0].Body, "[#5]") { + t.Errorf("notify again = %d, want nothing about #5:\n%s\n%s", code, stdout, gh.issueComments[0].Body) + } + + gh = &fakeGH{prs: []pullRequest{notifyPR("20261026", parkedBody(park))}, fail: map[string]error{"editBody": errors.New("HTTP 502")}} + if code, _, _ := notifyRun(gh, "--push"); code != 2 || len(gh.issueComments) != 1 || parked(gh)[0].Announced { + t.Fatalf("notify with a failing mark = %d, want 2 after the comment, the record unmarked", code) + } + code, _, stderr = notifyAt(gh, time.Date(2026, 10, 27, 0, 5, 0, 0, time.UTC), "--push") + if code != 0 || !strings.Contains(gh.issueComments[0].Body, "[#5](") || !parked(gh)[0].Announced { + t.Errorf("notify the next day = %d, want #5 named once more and marked:\n%s\n%s", code, stderr, gh.issueComments[0].Body) + } + + // Closed, or rewritten by a run, between the comment and the mark: the + // mark is not written, and the next notify names #5 again. + gh = &fakeGH{prs: []pullRequest{notifyPR("20261026", parkedBody(park))}} + gh.after = map[string]func(){"createComment": func() { gh.prs[0].State = "closed" }} + if code, _, _ := notifyRun(gh, "--push"); code != 2 || len(gh.closedWrites) != 0 || parked(gh)[0].Announced { + t.Errorf("notify on a batch closed meanwhile = %d, writes %q; want 2 and no mark", code, gh.closedWrites) + } + gh = &fakeGH{prs: []pullRequest{notifyPR("20261026", parkedBody(park))}} + rewritten := parkedBody(park, parkedEntry{Original: 6, Merge: strings.Repeat("d", 40), Kind: parkPartial, Files: []string{"x"}}) + gh.after = map[string]func(){"createComment": func() { gh.prs[0].Body = rewritten }} + if code, _, _ := notifyRun(gh, "--push"); code != 2 || gh.prs[0].Body != rewritten || len(gh.bodies) != 0 { + t.Errorf("notify on a body rewritten meanwhile = %d; want 2 and the new body left as it is", code) + } + + // A body someone edited on the web comes back with CRLF line ends; the + // mark lands all the same. + gh = &fakeGH{prs: []pullRequest{notifyPR("20261026", strings.ReplaceAll(parkedBody(park), "\n", "\r\n"))}} + if code, _, stderr := notifyRun(gh, "--push"); code != 0 || !parked(gh)[0].Announced { + t.Errorf("notify on a CRLF body = %d, want #5 marked:\n%s", code, stderr) + } + + closed := notifyPR("20261026", parkedBody(park)) + at := "2026-10-26T12:00:00Z" + closed.State, closed.MergedAt = "closed", &at + gh = &fakeGH{prs: []pullRequest{closed}} + if code, stdout, _ := notifyRun(gh, "--push"); code != 0 || stdout != "" || len(gh.issueComments) != 0 || len(gh.bodies) != 0 { + t.Errorf("notify with no batch open = %d, %q, %d comments, %d edits; want nothing", code, stdout, len(gh.issueComments), len(gh.bodies)) + } + next := notifyPR("20261027", parkedBody(park)) + next.Number = 91 + gh.prs = append(gh.prs, next) + if code, _, _ := notifyRun(gh, "--push"); code != 0 || len(gh.issueComments) != 1 || !strings.Contains(gh.issueComments[0].Body, "[#5](") { + t.Errorf("the next batch's notify = %d, want #5 announced on it: %v", code, gh.issueComments) + } +} + +// A park carries its announcement into the next record only while it is +// the same park: the same merge, kind, prerequisites, commits and files. +func TestParkEventIdentity(t *testing.T) { + a, b := strings.Repeat("a", 40), strings.Repeat("b", 40) + was := parkedEntry{Original: 5, Merge: a, Kind: parkDependency, Commits: []string{a}, Announced: true} + carrier := &lineRecord{Parked: []parkedEntry{was}} + for name, tc := range map[string]struct { + now parkedEntry + announced bool + }{ + "the same park": {parkedEntry{Original: 5, Merge: a, Kind: parkDependency, Commits: []string{a}}, true}, + "another unnumbered commit": {parkedEntry{Original: 5, Merge: a, Kind: parkDependency, Commits: []string{b}}, false}, + "another kind": {parkedEntry{Original: 5, Merge: a, Kind: parkPartial, Files: []string{"x"}}, false}, + "another prerequisite": {parkedEntry{Original: 5, Merge: a, Kind: parkDependency, Commits: []string{a}, Needs: []int{3}}, false}, + "another merge": {parkedEntry{Original: 5, Merge: b, Kind: parkDependency, Commits: []string{a}}, false}, + "another original": {parkedEntry{Original: 6, Merge: a, Kind: parkDependency, Commits: []string{a}}, false}, + } { + got := carryAnnounced([]parkedEntry{tc.now}, carrier) + if got[0].Announced != tc.announced { + t.Errorf("%s: announced = %v, want %v", name, got[0].Announced, tc.announced) + } + } + if got := carryAnnounced([]parkedEntry{was}, nil); got[0].Announced { + t.Error("a park with no carrier came out announced") + } + unannounced := was + unannounced.Announced = false + if got := carryAnnounced([]parkedEntry{was}, &lineRecord{Parked: []parkedEntry{unannounced}}); got[0].Announced { + t.Error("a park the carrier holds unannounced came out announced") + } +} + +// A park keeps its announcement through a continuation and into the next +// batch, so notify does not name it again. +func TestRolloverKeepsTheAnnouncement(t *testing.T) { + f := featWorld(t) + gh := &fakeGH{} + openBatch(t, f, gh) + if code, _, stderr := f.exec(gh, "notify", "--line", "release-1.1", "--push"); code != 0 || !strings.Contains(notifyComment(gh), "[#5](") { + t.Fatalf("notify = %d, want #5 announced:\n%s", code, stderr) + } + if code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--push"); code != 0 || !strings.Contains(stdout, `"needs":[3],"announced":true`) { + t.Fatalf("run --continue = %d, want #5's park still announced:\n%s\n%s", code, stdout, stderr) + } + f.git("switch", "-q", "main") + reopen(f, gh) + mergeBatch(f, gh) + f.pr(8, "fix(app): eight", "", map[string]string{"app/eight.txt": "8\n"}) + gh.nextPR = 91 + f.now = f.now.Add(24 * time.Hour) + if code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--push"); code != 0 || !strings.Contains(stdout, `"needs":[3],"announced":true`) { + t.Fatalf("the next batch's run = %d, want #5's park announced from the merged batch:\n%s\n%s", code, stdout, stderr) + } + f.git("switch", "-q", "main") + gh.issueComments = nil + if code, stdout, _ := f.exec(gh, "notify", "--line", "release-1.1", "--push"); code != 0 || strings.Contains(stdout, "parked") || strings.Contains(notifyComment(gh), "[#5](") { + t.Errorf("notify on the next batch = %d, want nothing about #5:\n%s\n%s", code, stdout, notifyComment(gh)) + } +} + +// notifyComment is the notify comment on the fake, or "". +func notifyComment(gh *fakeGH) string { + for _, c := range slices.Backward(gh.issueComments) { + if strings.HasPrefix(c.Body, notifyMarker) { + return c.Body + } + } + return "" +} diff --git a/cmd/backport-batch/onto_test.go b/cmd/backport-batch/onto_test.go new file mode 100644 index 000000000..994059235 --- /dev/null +++ b/cmd/backport-batch/onto_test.go @@ -0,0 +1,140 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package main + +import ( + "slices" + "strings" + "testing" +) + +// pushed builds and pushes a batch for #5 and returns its head. +func pushed(t *testing.T, f *fixture) string { + t.Helper() + f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"}) + if code, _, stderr := f.exec(&fakeGH{}, "run", "--line", "release-1.1", "--push"); code != 0 { + t.Fatalf("run --push = %d\n%s", code, stderr) + } + head := f.git("rev-parse", "HEAD") + f.git("switch", "-q", "main") + return head +} + +// --onto continues the pushed head and nothing else: it keeps what the batch +// carries and picks only what is new. +func TestOntoContinues(t *testing.T) { + f := newFixture(t) + f.lines() + head := pushed(t, f) + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + code, _, stderr := f.exec(&fakeGH{}, "run", "--line", "release-1.1", "--onto", head, "--date", "2026-10-29") + if code != 2 || !strings.Contains(stderr, "not the head of backport-batch/release-1.1-20261029") { + t.Errorf("--onto with another date = %d (%s), want a refusal", code, stderr) + } + f.now = f.now.AddDate(0, 0, 3) + code, stdout, stderr := f.exec(&fakeGH{}, "run", "--line", "release-1.1", "--onto", head) + if code != 0 { + t.Fatalf("run --onto = %d\n%s", code, stderr) + } + if !strings.Contains(stderr, "title: fix(backport): batch for release-1.1, 2026-10-26\n") { + t.Errorf("the continued batch is not titled for the date it opened on:\n%s", stderr) + } + if got := f.subjects(head, "HEAD"); !slices.Equal(got, []string{"fix(app): six (#6)"}) { + t.Errorf("picked %q on top of the batch, want only #6", got) + } + if !descends(t, head, f.git("rev-parse", "HEAD")) { + t.Error("the new head does not descend from --onto") + } + if listed, _, _ := strings.Cut(stdout, "### Skipped"); !strings.Contains(listed, "[#5]") || !strings.Contains(listed, "[#6]") { + t.Errorf("the body does not list what the batch carries and what it picked:\n%s", stdout) + } +} + +// A head that is not the one the remote has now is refused, so work pushed +// since cannot be dropped. +func TestOntoRefusesAStaleHead(t *testing.T) { + f := newFixture(t) + f.lines() + head := pushed(t, f) + f.git("switch", "-q", "--detach", head) + f.write("app/fold.txt", "folded\n") + f.git("add", "-A") + f.git("commit", "-q", "-m", "fold") + f.git("push", "-q", "origin", "HEAD:refs/heads/"+batchBranch1) + f.git("switch", "-q", "main") + + code, _, stderr := f.exec(&fakeGH{}, "run", "--line", "release-1.1", "--onto", head) + if code != 2 || !strings.Contains(stderr, "is not the head of any batch branch") { + t.Errorf("run --onto a stale head = %d (%s), want a refusal", code, stderr) + } + for _, bad := range []string{head[:12], "-" + head[1:], strings.ToUpper(head), "HEAD", "--help"} { + if code, _, _ := f.exec(&fakeGH{}, "run", "--line", "release-1.1", "--onto", bad); code != 2 { + t.Errorf("--onto %q = %d, want 2", bad, code) + } + } +} + +// A rebuilt branch that does not descend from what the remote has is never +// pushed over it. +func TestPushRefusesANonFastForward(t *testing.T) { + f := newFixture(t) + f.lines() + head := pushed(t, f) + f.git("switch", "-q", "--detach", head) + f.write("app/fold.txt", "folded\n") + f.git("add", "-A") + f.git("commit", "-q", "-m", "fold") + folded := f.git("rev-parse", "HEAD") + f.git("push", "-q", "origin", "HEAD:refs/heads/"+batchBranch1) + f.git("switch", "-q", "main") + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + + code, _, stderr := f.exec(&fakeGH{}, "run", "--line", "release-1.1", "--push") + // git would refuse too, but only after trying; the tool refuses first. + if code != 2 || !strings.Contains(stderr, "refusing a non-fast-forward push") { + t.Errorf("a fresh rebuild pushed over the batch = %d (%s), want a refusal", code, stderr) + } + if got := f.remoteHead(batchBranch1); got != folded { + t.Errorf("the remote batch moved to %.12s, want it left at %.12s", got, folded) + } +} + +// A run that pushed its branch and stopped before opening the pull request +// leaves the branch behind. A run the same day builds the batch anew and +// refuses to push over it, naming the run that continues it, which then +// opens the pull request. +func TestOrphanBranchNamesItsRecovery(t *testing.T) { + f := newFixture(t) + f.lines() + head := pushed(t, f) + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + // A commit picked again gets a new committer date, so a new name. + t.Setenv("GIT_COMMITTER_DATE", "2026-10-26T07:00:00Z") + code, _, stderr := f.exec(&fakeGH{}, "run", "--line", "release-1.1", "--continue", "--push") + recovery := "backport-batch run --line release-1.1 --onto " + head + " --push" + if code != 2 || !strings.Contains(stderr, recovery) { + t.Fatalf("a same-day run over the left branch = %d (%s), want a refusal naming %q", code, stderr, recovery) + } + gh := &fakeGH{} + if code, _, stderr := f.exec(gh, strings.Fields(recovery)[1:]...); code != 0 { + t.Fatalf("%s = %d\n%s", recovery, code, stderr) + } + now := f.remoteHead(batchBranch1) + if !descends(t, head, now) || now == head || len(gh.created) != 1 { + t.Errorf("the recovery pushed %.12s over %.12s and opened %q; want a fast-forward with #6 and one pull request", now, head, gh.created) + } +} diff --git a/cmd/backport-batch/output_test.go b/cmd/backport-batch/output_test.go new file mode 100644 index 000000000..a094d4b75 --- /dev/null +++ b/cmd/backport-batch/output_test.go @@ -0,0 +1,385 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package main + +import ( + "errors" + "io" + "os" + "os/exec" + "reflect" + "strings" + "testing" + "time" +) + +type failingWriter struct{} + +func (failingWriter) Write([]byte) (int, error) { return 0, errors.New("broken pipe") } + +// Output that never reached its reader fails the command, and stderr says why. +func TestUnwritableOutputFailsTheCommand(t *testing.T) { + var stderr strings.Builder + a := &app{gh: &fakeGH{}, stdout: failingWriter{}, stderr: &stderr} + if code := a.main([]string{"help"}); code != 2 { + t.Fatalf("help with an unwritable stdout = %d, want 2", code) + } + if !strings.Contains(stderr.String(), "broken pipe") { + t.Errorf("stderr does not name the write failure:\n%s", stderr.String()) + } +} + +// A command that already failed keeps its own exit code when its output is +// lost as well: check still says something is missing. +func TestUnwritableOutputKeepsTheCommandsFailure(t *testing.T) { + f := newFixture(t) + f.lines() + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + var stderr strings.Builder + a := &app{gh: &fakeGH{remoteHead: f.remoteHead}, stdout: failingWriter{}, stderr: &stderr, now: func() time.Time { return f.now }, tool: f.tool} + if code := a.main([]string{"check", "--line", "release-1.1"}); code != 1 { + t.Fatalf("check with #6 missing and an unwritable stdout = %d, want 1\n%s", code, stderr.String()) + } + if !strings.Contains(stderr.String(), "broken pipe") { + t.Errorf("stderr does not name the write failure:\n%s", stderr.String()) + } +} + +// A closed pipe on stdout does not kill the run before it can say what +// already happened: the write fails like any other, and the run exits 2. +func TestClosedStdoutPipeIsReported(t *testing.T) { + if os.Getenv("BACKPORT_BATCH_CLOSED_STDOUT_HELPER") == "1" { + os.Args = []string{"backport-batch", "help"} + main() + return + } + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + _ = r.Close() + t.Cleanup(func() { _ = w.Close() }) + cmd := exec.Command(os.Args[0], "-test.run=^TestClosedStdoutPipeIsReported$") + cmd.Env = append(os.Environ(), "BACKPORT_BATCH_CLOSED_STDOUT_HELPER=1") + var stderr strings.Builder + cmd.Stdout, cmd.Stderr = w, &stderr + err = cmd.Run() + var exit *exec.ExitError + if !errors.As(err, &exit) || exit.ExitCode() != 2 { + t.Fatalf("help into a closed pipe = %v, want exit 2\nstderr:\n%s", err, stderr.String()) + } + if !strings.Contains(stderr.String(), "output was lost") { + t.Errorf("stderr does not say the output was lost:\n%s", stderr.String()) + } +} + +// failOn fails every write that contains want, and takes every other one. +type failOn struct { + want string + buf strings.Builder +} + +func (w *failOn) Write(p []byte) (int, error) { + if strings.Contains(string(p), w.want) { + return 0, errors.New("broken pipe") + } + return w.buf.Write(p) +} + +func runWith(f *fixture, gh *fakeGH, stdout, stderr io.Writer, args ...string) int { + f.t.Helper() + if gh.remoteHead == nil { + gh.remoteHead = f.remoteHead + } + a := &app{gh: gh, stdout: stdout, stderr: stderr, now: func() time.Time { return f.now }, tool: f.tool} + return a.main(args) +} + +// Output is written before the push; when it is lost, on either stream, +// nothing is pushed and no pull request is opened. +func TestLostOutputPushesNothing(t *testing.T) { + for _, stream := range []string{"stdout", "stderr"} { + t.Run(stream, func(t *testing.T) { + f := newFixture(t) + f.lines() + f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"}) + gh := &fakeGH{} + var stdout, stderr io.Writer = &strings.Builder{}, &strings.Builder{} + if stream == "stdout" { + stdout = failingWriter{} + } else { + stderr = failingWriter{} + } + if code := runWith(f, gh, stdout, stderr, "run", "--line", "release-1.1", "--push"); code != 2 { + t.Fatalf("run --push with a failing %s = %d, want 2", stream, code) + } + if head := f.remoteHead(batchBranch1); head != "" { + t.Errorf("the batch was pushed at %.12s", head) + } + if len(gh.prs) != 0 { + t.Errorf("a pull request was opened: %+v", gh.prs) + } + }) + } +} + +// A confirmation lost after the push fails the run: the pull request was +// opened, and the run does not exit 0 without having said so. +func TestLostConfirmationFailsTheRun(t *testing.T) { + f := newFixture(t) + f.lines() + f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"}) + gh := &fakeGH{} + if code := runWith(f, gh, &strings.Builder{}, &failOn{want: "opened draft"}, "run", "--line", "release-1.1", "--push"); code != 2 { + t.Fatalf("run --push losing its confirmation = %d, want 2", code) + } + if len(gh.prs) != 1 { + t.Errorf("%d pull requests, want the one the run opened", len(gh.prs)) + } + if len(gh.issueComments) != 0 { + t.Errorf("the report was posted after the confirmation was lost: %+v", gh.issueComments) + } +} + +// notify writes what it found before it comments; when that is lost, it +// does not comment. +func TestLostOutputCommentsNothing(t *testing.T) { + gh := &fakeGH{prs: []pullRequest{notifyPR("20261019", "")}} + var stderr strings.Builder + a := &app{gh: gh, stdout: failingWriter{}, stderr: &stderr, now: func() time.Time { return time.Date(2026, 10, 26, 6, 23, 0, 0, time.UTC) }} + if code := a.main([]string{"notify", "--line", "release-1.1", "--push"}); code != 2 { + t.Fatalf("notify --push with a failing stdout = %d, want 2\n%s", code, stderr.String()) + } + if len(gh.issueComments) != 0 { + t.Errorf("notify commented: %+v", gh.issueComments) + } +} + +// writesGitHub records the GitHub writes that reach it. +type writesGitHub struct { + github + writes []string +} + +func (g *writesGitHub) createPull(string, string, string, string) (int, string, error) { + g.writes = append(g.writes, "createPull") + return 1, "", nil +} +func (g *writesGitHub) editPull(int, string, string) error { + g.writes = append(g.writes, "editPull") + return nil +} +func (g *writesGitHub) editBody(int, string) error { + g.writes = append(g.writes, "editBody") + return nil +} +func (g *writesGitHub) closePull(int) error { + g.writes = append(g.writes, "closePull") + return nil +} +func (g *writesGitHub) createComment(int, string) error { + g.writes = append(g.writes, "createComment") + return nil +} +func (g *writesGitHub) editComment(int64, string) error { + g.writes = append(g.writes, "editComment") + return nil +} + +// Every GitHub write is refused once output was lost. Every method of +// github is either a read or in this table, so a write added later without +// a guard fails here. +func TestEveryGitHubWriteIsGuarded(t *testing.T) { + reads := map[string]bool{"openPulls": true, "recentPulls": true, "permission": true, "labelled": true, "pull": true, "comments": true, "batchBot": true} + inner := &writesGitHub{} + g := guardedGitHub{github: inner, a: &app{unwritten: errors.New("broken pipe")}} + writes := map[string]func() error{ + "createPull": func() error { _, _, err := g.createPull("b", "h", "t", "f"); return err }, + "editPull": func() error { return g.editPull(1, "t", "f") }, + "editBody": func() error { return g.editBody(1, "f") }, + "closePull": func() error { return g.closePull(1) }, + "createComment": func() error { return g.createComment(1, "f") }, + "editComment": func() error { return g.editComment(1, "f") }, + } + iface := reflect.TypeFor[github]() + for i := range iface.NumMethod() { + name := iface.Method(i).Name + if _, ok := writes[name]; !ok && !reads[name] { + t.Errorf("github.%s is neither a known read nor a guarded write", name) + } + } + for name, write := range writes { + if err := write(); err == nil || !strings.Contains(err.Error(), "output was lost") { + t.Errorf("%s with output lost = %v, want a refusal", name, err) + } + } + if len(inner.writes) != 0 { + t.Errorf("writes reached GitHub after output was lost: %q", inner.writes) + } +} + +// A warning lost while the open batch is being updated stops the update: +// nothing is pushed, posted or edited. +func TestLostWarningLeavesTheOpenBatchAlone(t *testing.T) { + f := newFixture(t) + f.lines() + f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"}) + gh := &fakeGH{} + mustRun(t, f, gh, "run", "--line", "release-1.1", "--push") + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + bad := issueComment{ID: 8, Body: reportMarker + "names none\n"} + bad.User.Login, bad.User.Type = "maintainer", "User" + gh.issueComments = append(gh.issueComments, bad) + head, comments, body := f.remoteHead(batchBranch1), len(gh.issueComments), gh.find(90).Body + f.now = f.now.AddDate(0, 0, 1) + if code := runWith(f, gh, &strings.Builder{}, &failOn{want: "does not count as a report"}, "run", "--line", "release-1.1", "--continue", "--push"); code != 2 { + t.Fatalf("run --continue --push losing a warning = %d, want 2", code) + } + if got := f.remoteHead(batchBranch1); got != head { + t.Errorf("the batch moved to %.12s", got) + } + if len(gh.issueComments) != comments { + t.Errorf("a comment was posted: %d comments, want %d", len(gh.issueComments), comments) + } + if gh.find(90).Body != body { + t.Error("the batch pull request was edited") + } +} + +// A warning lost while a batch is being closed leaves it open, with no +// closing record half written. +func TestLostWarningLeavesTheBatchUnclosed(t *testing.T) { + f := newFixture(t) + f.lines() + f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"}) + gh := &fakeGH{} + mustRun(t, f, gh, "run", "--line", "release-1.1", "--push") + bad := issueComment{ID: 8, Body: reportMarker + "names none\n"} + bad.User.Login, bad.User.Type = "maintainer", "User" + gh.issueComments = append(gh.issueComments, bad) + body := gh.find(90).Body + if code := runWith(f, gh, &strings.Builder{}, &failOn{want: "does not count as a report"}, "run", "--line", "release-1.1", "--defer", "5", "--reason", "x", "--push"); code != 2 { + t.Fatalf("run --defer losing a warning = %d, want 2", code) + } + if gh.find(90).Body != body { + t.Error("the batch pull request was edited") + } + if !gh.isOpen(90) { + t.Error("the batch pull request was closed") + } +} + +// The git and gh children keep the default SIGPIPE: catching it here must not +// leave it ignored in them, as signal.Ignore would through exec. +func TestChildrenKeepTheDefaultSIGPIPE(t *testing.T) { + catchSIGPIPE() + out, err := exec.Command("sh", "-c", "kill -PIPE $$; echo survived").Output() + if err == nil || strings.Contains(string(out), "survived") { + t.Fatalf("a child survived SIGPIPE: %q, %v", out, err) + } +} + +// The branch a close left is not deleted once output was lost: a deletion +// is a push like any other. +func TestLostOutputDeletesNoBranch(t *testing.T) { + f, gh, h1 := closeWorld(t) + f.git("switch", "-q", "main") + l, err := parseLine("release-1.1") + if err != nil { + t.Fatal(err) + } + a := &app{gh: gh, unwritten: errors.New("broken pipe")} + if err := a.deleteBranch(l, closing{PR: 90, Branch: batchBranch1, Head: h1}); err == nil || !strings.Contains(err.Error(), "output was lost") { + t.Fatalf("deleteBranch with output lost = %v, want a refusal", err) + } + if got := f.remoteHead(batchBranch1); got != h1 { + t.Errorf("the branch is at %q, want it left at %.12s", got, h1) + } +} + +// A park line lost on stdout stops notify before it writes: no comment, and +// the record is not marked as announced. +func TestLostParkLineWritesNothing(t *testing.T) { + park := parkedEntry{Original: 5, Merge: strings.Repeat("c", 40), Kind: parkDependency, Needs: []int{3}} + gh := &fakeGH{prs: []pullRequest{notifyPR("20261026", parkedBody(park))}} + body := gh.prs[0].Body + var stderr strings.Builder + a := &app{gh: gh, stdout: &failOn{want: "parked originals"}, stderr: &stderr, now: func() time.Time { return time.Date(2026, 10, 26, 6, 23, 0, 0, time.UTC) }} + if code := a.main([]string{"notify", "--line", "release-1.1", "--push"}); code != 2 { + t.Fatalf("notify --push losing the park line = %d, want 2\n%s", code, stderr.String()) + } + if len(gh.issueComments) != 0 { + t.Errorf("notify commented: %+v", gh.issueComments) + } + if gh.prs[0].Body != body { + t.Error("notify marked the park as announced") + } +} + +// The hint naming the commits a reset drops is the only way back to them, so +// the local branch is not reset when the hint is lost. +func TestLostResetHintKeepsTheBranch(t *testing.T) { + f := newFixture(t) + f.lines() + f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"}) + f.git("switch", "-q", "-C", batchBranch1, "origin/release-1.1") + f.write("app/mine.txt", "unpushed\n") + f.git("add", "-A") + f.git("commit", "-q", "-m", "an unpushed resolution") + tip := f.git("rev-parse", "HEAD") + f.git("switch", "-q", "main") + if code := runWith(f, &fakeGH{}, &strings.Builder{}, &failOn{want: "resetting the local"}, "run", "--line", "release-1.1"); code != 2 { + t.Fatalf("run losing the reset hint = %d, want 2", code) + } + if got := f.git("rev-parse", batchBranch1); got != tip { + t.Errorf("the local %s moved to %.12s, want it kept at %.12s", batchBranch1, got, tip) + } +} + +// Once output is lost the run moves no local branch, even one a reset would +// only fast-forward. +func TestLostOutputMovesNoLocalBranch(t *testing.T) { + f := newFixture(t) + f.lines() + f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"}) + f.git("branch", "-f", batchBranch1, "origin/release-1.1^") + before := f.git("rev-parse", batchBranch1) + if code := runWith(f, &fakeGH{}, &strings.Builder{}, &failOn{want: "prepared"}, "run", "--line", "release-1.1"); code != 2 { + t.Fatalf("run losing an early line = %d, want 2", code) + } + if got := f.git("rev-parse", batchBranch1); got != before { + t.Errorf("the local %s moved to %.12s, want it kept at %.12s", batchBranch1, got, before) + } +} + +// No new unit starts once output is lost: neither a pick nor a replay touches +// the branch. +func TestLostOutputStartsNoUnit(t *testing.T) { + f := newFixture(t) + f.lines() + before := f.git("rev-parse", "HEAD") + a := &app{unwritten: errors.New("broken pipe")} + if _, err := a.pickUnit(&verdict{}, nil); err == nil || !strings.Contains(err.Error(), "output was lost") { + t.Errorf("pickUnit with output lost = %v, want a refusal", err) + } + if _, _, err := a.replayNext(unit{}); err == nil || !strings.Contains(err.Error(), "output was lost") { + t.Errorf("replayNext with output lost = %v, want a refusal", err) + } + if got := f.git("rev-parse", "HEAD"); got != before { + t.Errorf("HEAD moved to %.12s", got) + } +} diff --git a/cmd/backport-batch/overrides_test.go b/cmd/backport-batch/overrides_test.go new file mode 100644 index 000000000..0bcdc426e --- /dev/null +++ b/cmd/backport-batch/overrides_test.go @@ -0,0 +1,275 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package main + +import ( + "fmt" + "os" + "path/filepath" + "slices" + "strings" + "testing" +) + +// overridden builds a line where backport/ labels decide: #5 a feature let in, +// #6 a fix kept out, #7 a breaking fix and #8 a migration let in, #9 carrying +// both labels, #10 a feature let in that the line already carries, adapted, so +// picking it again would conflict rather than come out empty. +func overridden(t *testing.T) (*fixture, *fakeGH) { + t.Helper() + f := newFixture(t) + f.lines() + f.pr(5, "feat(app): five", "", map[string]string{"app/five.txt": "5\n"}) + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + f.pr(7, "fix(app)!: seven", "", map[string]string{"app/seven.txt": "7\n"}) + f.pr(8, "fix(platform): eight", "", map[string]string{migrationsDir + "61": "#!/bin/sh\n"}) + f.pr(9, "fix(app): nine", "", map[string]string{"app/nine.txt": "9\n"}) + mc10 := f.pr(10, "feat(app): ten", "", map[string]string{"app/ten.txt": "10\n"}) + f.onLine("release-1.1", "feat(app): ten (#10)\n\n(cherry picked from commit "+mc10+")", map[string]string{"app/ten.txt": "10, adapted\n"}) + gh := &fakeGH{labels: map[string][]int{ + labelInclude: {5, 7, 8, 9, 10}, + labelSkip: {6, 9}, + }} + return f, gh +} + +func TestOverrides(t *testing.T) { + f, gh := overridden(t) + code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1") + if code != 0 { + t.Fatalf("run = %d\n%s", code, stderr) + } + want := []string{"feat(app): five (#5)", "fix(app)!: seven (#7)", "fix(platform): eight (#8)"} + if got := f.subjects("origin/release-1.1", "HEAD"); !slices.Equal(got, want) { + t.Errorf("picked %q, want %q", got, want) + } + section, _, _ := strings.Cut(stdout[strings.Index(stdout, "### Maintainer overrides"):], "### Skipped") + for n, outcome := range map[int]string{ + 5: "`backport/include`, on this branch", + 6: "`backport/skip`, left out", + 7: "`backport/include`, on this branch", + 8: "`backport/include`, on this branch", + 9: "`backport/skip`, left out", + 10: "`backport/include`, skipped by rule 1", + } { + if !strings.Contains(section, fmt.Sprintf("/pull/%d)", n)) || !strings.Contains(section, outcome) { + t.Errorf("the overrides section does not show #%d as %q:\n%s", n, outcome, section) + } + } + if skipped := stdout[strings.Index(stdout, "### Skipped"):]; strings.Contains(skipped, "/pull/6)") || strings.Contains(skipped, "/pull/9)") { + t.Errorf("a skipped-by-label original is listed under a rule:\n%s", skipped) + } +} + +// check holds the line to what the labels decide, and fold refuses an +// original kept out. +func TestOverridesInCheckAndFold(t *testing.T) { + f, gh := overridden(t) + code, stdout, _ := f.exec(gh, "check", "--line", "release-1.1") + if code != 1 { + t.Fatalf("check = %d, want 1:\n%s", code, stdout) + } + for _, n := range []int{5, 7, 8} { + if !strings.Contains(stdout, fmt.Sprintf("/pull/%d ", n)) { + t.Errorf("check does not list #%d:\n%s", n, stdout) + } + } + for _, n := range []int{6, 9, 10} { + if strings.Contains(stdout, fmt.Sprintf("/pull/%d ", n)) { + t.Errorf("check lists #%d:\n%s", n, stdout) + } + } + + f.git("push", "-q", "origin", "origin/release-1.1:refs/heads/"+batchBranch1) + f.git("fetch", "-q", "origin") + gh.prs = []pullRequest{f.batchPR(90, "release-1.1", batchBranch1, "")} + f.git("switch", "-q", "--detach", "origin/"+batchBranch1) + f.write("app/six.txt", "6\n") + f.git("add", "-A") + f.git("commit", "-q", "-m", "port\n\n(cherry picked from commit "+f.git("rev-parse", "origin/main~4")+")") + commit := f.git("rev-parse", "HEAD") + f.git("switch", "-q", "main") + code, stdout, _ = f.exec(gh, "fold", "--line", "release-1.1", "--original", "6", "--commit", commit) + if code != 1 || !strings.Contains(stdout, "#6 carries backport/skip") { + t.Errorf("fold of a skipped original = %d, %q; want a refusal", code, stdout) + } +} + +// backport/include lifts rules 2 to 4, not rule 6: an older line still waits +// for the newer one. +func TestIncludeKeepsRuleSix(t *testing.T) { + f, gh := overridden(t) + f.git("fetch", "-q", "origin") + l, _ := parseLine("release-1.0") + b, err := (&app{gh: gh, stderr: &strings.Builder{}}).prepare(l) + if err != nil { + t.Fatal(err) + } + if v := b.find(5); v == nil || v.rule != ruleNewer { + t.Errorf("#5 on release-1.0 = %+v, want rule 6", v) + } + if v := b.find(10); v == nil || v.rule != 0 { + t.Errorf("#10 on release-1.0 = %+v, want it to qualify: release-1.1 carries it", v) + } +} + +func TestOverridesUnreadable(t *testing.T) { + f, gh := overridden(t) + gh.listErr = errString("gh: HTTP 502") + if code, _, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 2 || !strings.Contains(stderr, "HTTP 502") { + t.Errorf("check with labels unreadable = %d (%s), want 2", code, stderr) + } +} + +// ghCLI against a stub gh on PATH: the exact argv, and a listing that fills +// GitHub search's cap is refused rather than read as complete. +func TestGHCLI(t *testing.T) { + bin := t.TempDir() + args, out := filepath.Join(bin, "args"), filepath.Join(bin, "out") + stub := "#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"" + args + "\"\ncat \"" + out + "\"\n" + if err := os.WriteFile(filepath.Join(bin, "gh"), []byte(stub), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) + write := func(s string) { + t.Helper() + if err := os.WriteFile(out, []byte(s), 0o644); err != nil { + t.Fatal(err) + } + _ = os.Remove(args) + } + called := func() string { + data, _ := os.ReadFile(args) + return strings.TrimSpace(string(data)) + } + + write(`[{"number":5},{"number":7}]`) + got, err := ghCLI{}.labelled(labelInclude) + if err != nil || !slices.Equal(got, []int{5, 7}) { + t.Errorf("labelled = %v, %v; want [5 7]", got, err) + } + if want := "pr list --base main --state merged --label backport/include --limit 1000 --json number"; called() != want { + t.Errorf("gh %q, want gh %q", called(), want) + } + + var full []string + for i := range searchResultCap { + full = append(full, fmt.Sprintf(`{"number":%d}`, i+1)) + } + write("[" + strings.Join(full, ",") + "]") + if _, err := (ghCLI{}).labelled(labelSkip); err == nil { + t.Error("a listing as long as the search cap was read as complete") + } + + write(`{"permission":"write"}`) + if p, err := (ghCLI{}).permission("maintainer"); err != nil || p != "write" { + t.Errorf("permission = %q, %v", p, err) + } + if want := "api repos/{owner}/{repo}/collaborators/maintainer/permission"; called() != want { + t.Errorf("gh %q, want gh %q", called(), want) + } + write(`{"permission":"admin"}`) + for _, login := range []string{"x/../../orgs/y", "-x", "a b", "github-actions[bot]", ""} { + if _, err := (ghCLI{}).permission(login); err == nil || called() != "" { + t.Errorf("permission(%q) = %v and called gh %q; want a refusal before gh", login, err, called()) + } + } + + write("[]") + if _, err := (ghCLI{}).openPulls("release-1.6"); err != nil { + t.Fatal(err) + } + if want := "api -X GET repos/{owner}/{repo}/pulls -f state=open -f base=release-1.6 -f per_page=100"; called() != want { + t.Errorf("gh %q, want gh %q", called(), want) + } + write("[]") + if _, err := (ghCLI{}).recentPulls("release-1.6", 2); err != nil { + t.Fatal(err) + } + if want := "api -X GET repos/{owner}/{repo}/pulls -f state=all -f base=release-1.6 -f sort=created -f direction=desc -f per_page=100 -f page=2"; called() != want { + t.Errorf("gh %q, want gh %q", called(), want) + } + var page []string + for i := range openPullsCap { + page = append(page, fmt.Sprintf(`{"number":%d}`, i+1)) + } + write("[" + strings.Join(page, ",") + "]") + if _, err := (ghCLI{}).openPulls("release-1.6"); err == nil { + t.Error("a full page of open pull requests was read as all of them") + } + + write(`[[{"id":1,"body":"a","user":{"login":"x","type":"User"}}],[{"id":2,"body":"b","user":{"login":"y","type":"Bot"}}]]`) + comments, err := ghCLI{}.comments(90) + if err != nil || len(comments) != 2 || comments[1].ID != 2 || comments[1].User.Type != "Bot" { + t.Errorf("comments = %+v, %v; want both pages", comments, err) + } + if want := "api --paginate --slurp repos/{owner}/{repo}/issues/90/comments"; called() != want { + t.Errorf("gh %q, want gh %q", called(), want) + } + write("{}") + if err := (ghCLI{}).createComment(90, "/tmp/body.md"); err != nil { + t.Fatal(err) + } + if want := "api --method POST repos/{owner}/{repo}/issues/90/comments -F body=@/tmp/body.md"; called() != want { + t.Errorf("gh %q, want gh %q", called(), want) + } + write("{}") + if err := (ghCLI{}).editComment(12345678901, "/tmp/body.md"); err != nil { + t.Fatal(err) + } + if want := "api --method PATCH repos/{owner}/{repo}/issues/comments/12345678901 -F body=@/tmp/body.md"; called() != want { + t.Errorf("gh %q, want gh %q", called(), want) + } + + // A batch pull request carries no label: the release workflows act on a + // pull request cozystack-ci[bot] opened only when it has the release label. + write("https://github.com/cozystack/cozystack/pull/5300\n") + if n, url, err := (ghCLI{}).createPull("release-1.7", batchBranch1, "fix(backport): batch", "/tmp/body.md"); err != nil || n != 5300 || url != "https://github.com/cozystack/cozystack/pull/5300" { + t.Errorf("createPull = %d, %q, %v; want the pull request gh printed", n, url, err) + } + if want := "pr create --draft --base release-1.7 --head " + batchBranch1 + " --title fix(backport): batch --body-file /tmp/body.md"; called() != want { + t.Errorf("gh %q, want gh %q", called(), want) + } + write("Warning: 1 uncommitted change\n") + if _, _, err := (ghCLI{}).createPull("release-1.7", batchBranch1, "fix(backport): batch", "/tmp/body.md"); err == nil { + t.Error("createPull took output that is no pull request URL") + } + write(`{"number":90,"state":"closed","merged_at":"2026-10-26T12:00:00Z","head":{"ref":"x","sha":"y"}}`) + if pr, err := (ghCLI{}).pull(90); err != nil || pr.State != "closed" || pr.MergedAt == nil { + t.Errorf("pull = %+v, %v; want #90 merged", pr, err) + } + if want := "api repos/{owner}/{repo}/pulls/90"; called() != want { + t.Errorf("gh %q, want gh %q", called(), want) + } + if _, err := (ghCLI{}).pull(91); err == nil { + t.Error("pull took GitHub's answer about another pull request") + } + write("") + if err := (ghCLI{}).closePull(90); err != nil { + t.Fatal(err) + } + if want := "pr close 90"; called() != want { + t.Errorf("gh %q, want gh %q", called(), want) + } + write("") + if err := (ghCLI{}).editPull(90, "fix(backport): batch", "/tmp/body.md"); err != nil { + t.Fatal(err) + } + if want := "pr edit 90 --title fix(backport): batch --body-file /tmp/body.md"; called() != want { + t.Errorf("gh %q, want gh %q", called(), want) + } +} diff --git a/cmd/backport-batch/park_test.go b/cmd/backport-batch/park_test.go new file mode 100644 index 000000000..94a06ada5 --- /dev/null +++ b/cmd/backport-batch/park_test.go @@ -0,0 +1,796 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package main + +import ( + "fmt" + "slices" + "strings" + "testing" +) + +var line11, _ = parseLine("release-1.1") + +// handBatch pushes a batch carrying merges in the batch's shape, as a run +// made one before the partial guard, and opens its pull request with a +// record that defers nothing. +func handBatch(f *fixture, gh *fakeGH, merges ...string) string { + f.t.Helper() + f.git("fetch", "-q", "origin") + f.git("switch", "-q", "--detach", "origin/release-1.1") + for _, mc := range merges { + if parents := strings.Fields(f.git("rev-list", "--parents", "-n", "1", mc)); len(parents) == 2 { + f.git("cherry-pick", "-x", mc) + continue + } + base := f.git("rev-parse", "HEAD") + for _, c := range strings.Fields(f.git("rev-list", "--reverse", "--no-merges", mc+"^1.."+mc+"^2")) { + f.git("cherry-pick", "-x", c) + } + merge := f.joined(base, "HEAD", f.git("log", "-1", "--format=%B", mc)+"\n\n"+batchTrailer+": "+mc) + f.git("update-ref", "HEAD", merge) + } + f.git("push", "-q", "origin", "HEAD:refs/heads/"+batchBranch1) + f.git("switch", "-q", "main") + gh.prs = []pullRequest{f.batchPR(90, "release-1.1", batchBranch1, "batch\n\n"+deferredBlock(line11, nil, nil, nil)+"\n")} + return f.remoteHead(batchBranch1) +} + +// policyWorld is #5088's shape: #3, a feat the line never gets, adds a +// policy and its test; #5 deletes both again and adds a test of its own. +func policyWorld(t *testing.T) (*fixture, string) { + t.Helper() + f := newFixture(t) + f.lines() + f.pr(3, "feat(chart): a network policy", "", map[string]string{"chart/templates/policy.yaml": "kind: NetworkPolicy\n", "chart/tests/policy_test.yaml": "suite: policy\n"}) + mc5 := f.pr(5, "fix(chart): remove the policy a rebase brought back", "```release-note\nfix(chart): the stray network policy is gone.\n```\n", + map[string]string{"chart/templates/policy.yaml": "", "chart/tests/policy_test.yaml": "", "chart/tests/values_test.yaml": "suite: values\n"}) + return f, mc5 +} + +// A clean pick that would delete files the line never had, and so carry only +// #5's test, is withheld: #5 is parked as partial, with the paths it would +// leave without effect, and its release note stays out of the body. +func TestPartialPickIsWithheld(t *testing.T) { + f, mc5 := policyWorld(t) + f.pr(6, "fix(app): six", "```release-note\nfix(app): six works.\n```\n", map[string]string{"app/six.txt": "6\n"}) + code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1") + if code != 0 { + t.Fatalf("run = %d\n%s", code, stderr) + } + if got := f.subjects("origin/release-1.1", "HEAD"); !slices.Equal(got, []string{"fix(app): six (#6)"}) { + t.Errorf("picked %q, want only #6", got) + } + want := `"parked":[{"original":5,"merge":"` + mc5 + `","kind":"partial","files":["chart/templates/policy.yaml","chart/tests/policy_test.yaml"]}]` + if !strings.Contains(stdout, want) { + t.Errorf("the record does not park #5 as partial (%s):\n%s", want, stdout) + } + if !strings.Contains(stdout, "### Parked") || !strings.Contains(stdout, "`chart/templates/policy.yaml`") { + t.Errorf("the body does not say #5 is parked and why:\n%s", stdout) + } + if strings.Contains(stdout, "stray network policy") || !strings.Contains(stdout, "six works") { + t.Errorf("the release notes are not #6's alone:\n%s", stdout) + } +} + +// A file the line removed itself, which no original added after the line +// branched, still leaves #5's deletion without effect: check finds it with no +// record and parks it, and run picks nothing. +func TestPartialWithoutAnAdder(t *testing.T) { + f := newFixture(t) + f.squash(2, "chore: add a policy", "", map[string]string{"app/policy.yaml": "allow: all\n"}) + f.lines() + f.onLine("release-1.1", "fix(app): the line drops the policy", map[string]string{"app/policy.yaml": ""}) + f.pr(5, "fix(app): drop the policy", "", map[string]string{"app/policy.yaml": "", "app/policy_test.txt": "gone\n"}) + code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1") + if code != 0 { + t.Fatalf("run = %d\n%s", code, stderr) + } + if got := f.subjects("origin/release-1.1", "HEAD"); len(got) != 0 { + t.Errorf("picked %q, want nothing", got) + } + if !strings.Contains(stdout, "### Parked") { + t.Errorf("the body does not park #5:\n%s", stdout) + } + f.git("switch", "-q", "main") + code, stdout, stderr = f.exec(nil, "check", "--line", "release-1.1") + if code != 0 || !strings.Contains(stderr, "note: #5 is parked: only part of it applies to release-1.1") { + t.Errorf("check = %d, want 0 with a parked-partial note:\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr) + } +} + +// The picker judges what its picks did, not what the original's merge did: +// #5's first commit deletes a file the line no longer has and comes out +// empty, its second adds a test, and the unit left would be the test alone. +func TestPartialByAnEmptyOwnCommit(t *testing.T) { + f := newFixture(t) + f.squash(2, "chore: add a policy", "", map[string]string{"app/policy.yaml": "allow: all\n"}) + f.lines() + f.onLine("release-1.1", "fix(app): the line drops the policy", map[string]string{"app/policy.yaml": ""}) + f.prCommits(5, "fix(app): drop the policy and test it", "```release-note\nfix(app): no more policy.\n```\n", + change{files: map[string]string{"app/policy.yaml": ""}}, + change{files: map[string]string{"app/policy_test.txt": "gone\n"}}) + code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1") + if code != 0 { + t.Fatalf("run = %d\n%s", code, stderr) + } + if got := f.subjects("origin/release-1.1", "HEAD"); len(got) != 0 { + t.Errorf("picked %q, want #5 withheld", got) + } + if strings.Contains(stdout, "no more policy") || !strings.Contains(stdout, "### Parked") { + t.Errorf("#5's note is in the body, or #5 is not parked:\n%s", stdout) + } +} + +// A batch built before the guard can already carry a partial unit. It fails +// the cut and verify whatever its label says, and --defer takes it off, +// closing a batch it was the last unit of. +func TestExistingPartialUnitFailsTheCut(t *testing.T) { + f, mc5 := policyWorld(t) + gh := &fakeGH{} + head := handBatch(f, gh, mc5) + code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1", "--cut") + if code != 1 || !strings.Contains(stdout, "#5 is on batch #90, but only part of it applies to release-1.1") { + t.Errorf("check --cut = %d, want 1 naming the partial unit:\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr) + } + code, stdout, stderr = f.exec(gh, "verify", "--line", "release-1.1", "--head", head) + if code != 1 || !strings.Contains(stdout, `#5 leaves "chart/templates/policy.yaml", "chart/tests/policy_test.yaml" without effect on release-1.1`) { + t.Errorf("verify = %d, want 1 naming what #5 leaves out:\n%s\n%s", code, stdout, stderr) + } + gh.labels = map[string][]int{labelSkip: {5}} + code, stdout, stderr = f.exec(gh, "check", "--line", "release-1.1", "--cut") + if code != 1 || !strings.Contains(stdout, "#5 is on batch #90, but only part of it applies to release-1.1") { + t.Errorf("check --cut with backport/skip = %d, want the partial unit to still fail it:\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr) + } + code, _, stderr = f.exec(gh, "run", "--line", "release-1.1", "--defer", "5", "--reason", "only part of it applies", "--push") + if code != 0 || prState(gh.find(90)) != "closed" || f.remoteHead(batchBranch1) != "" { + t.Errorf("run --defer 5 --push = %d, #90 %s, branch at %q; want the batch closed and its branch gone:\n%s", code, prState(gh.find(90)), f.remoteHead(batchBranch1), stderr) + } +} + +// An original whose first pick came out empty, because the line already had +// that change, is on the batch all the same: check does not call it missing, +// a continuation keeps it picked, and so does a rebuild without another +// original. +func TestOnBatchAfterAnEmptyFirstPick(t *testing.T) { + f := newFixture(t) + f.squash(2, "chore: a and b", "", map[string]string{"app/a.txt": "old\n", "app/b.txt": "old\n"}) + f.lines() + f.onLine("release-1.1", "fix(app): a, on the line first", map[string]string{"app/a.txt": "fixed\n"}) + f.prCommits(5, "fix(app): a and b", "", + change{files: map[string]string{"app/a.txt": "fixed\n"}}, + change{files: map[string]string{"app/b.txt": "fixed\n"}}) + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + gh := &fakeGH{} + head := openBatch(t, f, gh) + if got := f.subjects("origin/release-1.1", head); !slices.Equal(got, []string{"fix(app): a and b (#5)", "fix(app): six (#6)"}) { + t.Fatalf("the batch carries %q, want #5 and #6", got) + } + code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1") + if code != 0 { + t.Errorf("check = %d, want 0 with #5 on the batch:\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr) + } + code, stdout, _ = f.exec(gh, "check", "--line", "release-1.1", "--cut") + if code != 1 || !strings.Contains(stdout, "#5 is only on open batch PR #90") { + t.Errorf("check --cut = %d, want #5 only on the batch:\n%s", code, stdout) + } + code, stdout, stderr = f.exec(gh, "run", "--line", "release-1.1", "--continue") + if code != 0 || !strings.Contains(stdout, `"picked":[5,6]`) { + t.Errorf("run --continue = %d, want #5 and #6 picked:\n%s\n%s", code, stdout, stderr) + } + f.git("switch", "-q", "main") + code, stdout, stderr = f.exec(gh, "run", "--line", "release-1.1", "--defer", "6", "--reason", "fails the e2e") + if code != 0 || !strings.Contains(stdout, `"picked":[5]`) || !strings.Contains(stdout, `"missing":[]`) { + t.Errorf("run --defer 6 = %d, want #5 still picked:\n%s\n%s", code, stdout, stderr) + } +} + +// featWorld is #5071's shape: #3, a feat the line never gets, adds a file, +// and #5 fixes that file; #6 is a plain fix beside it. +func featWorld(t *testing.T) *fixture { + t.Helper() + f := newFixture(t) + f.lines() + f.pr(3, "feat(app): tap", "", map[string]string{"app/tap.go": appFile}) + f.pr(5, "fix(app): fix the tap", "```release-note\nfix(app): the tap works.\n```\n", map[string]string{"app/tap.go": strings.Replace(appFile, "two", "TWO", 1)}) + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + return f +} + +// A fix of a file a feat added on main, which the line never gets, is +// parked, not tried, and check takes the park as a note. +func TestParkAFixOfAFeatureTheLineLacks(t *testing.T) { + f := featWorld(t) + gh := &fakeGH{} + code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--push") + if code != 0 { + t.Fatalf("run --push = %d\n%s", code, stderr) + } + if strings.Contains(stdout, "### Deferred conflicts") || !strings.Contains(stdout, `"parked":[{"original":5,`) || !strings.Contains(stdout, `"kind":"dependency","needs":[3]`) { + t.Errorf("#5 is not parked on #3:\n%s", stdout) + } + if !strings.Contains(stdout, "### Parked") || !strings.Contains(stdout, "builds on [#3]") { + t.Errorf("the body does not say #5 builds on #3:\n%s", stdout) + } + f.git("switch", "-q", "main") + reopen(f, gh) + code, stdout, stderr = f.exec(gh, "check", "--line", "release-1.1") + if code != 0 || !strings.Contains(stderr, "note: #5 is parked: it builds on #3, which never reaches release-1.1") { + t.Errorf("check = %d, want 0 with a note that #5 is parked:\n%s\n%s", code, stdout, stderr) + } +} + +// backport/include lifts no park. +func TestIncludeDoesNotLiftThePark(t *testing.T) { + f := featWorld(t) + code, stdout, stderr := f.exec(&fakeGH{labels: map[string][]int{labelInclude: {5}}}, "run", "--line", "release-1.1") + if code != 0 || !strings.Contains(stdout, `"parked":[{"original":5,`) || !strings.Contains(stdout, "`backport/include`, parked: builds on") { + t.Errorf("run with backport/include on #5 = %d, want #5 still parked:\n%s\n%s", code, stdout, stderr) + } +} + +// A prerequisite that is itself parked, but adapted onto the batch by hand, +// satisfies what builds on it: #3 is parked on #2, a feat, and #5 changes a +// line #3 wrote. +func TestAdaptedPrerequisiteSatisfiesItsDependent(t *testing.T) { + f := newFixture(t) + f.squash(2, "chore: a and b", "", map[string]string{"app/a.txt": appFile, "app/b.txt": appFile}) + f.lines() + f.pr(20, "feat(app): a loud two", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO", 1)}) + mc3 := f.pr(3, "fix(app): an excited two, a loud three", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!", 1), "app/b.txt": strings.Replace(appFile, "three", "THREE", 1)}) + f.pr(5, "fix(app): an excited three", "", map[string]string{"app/b.txt": strings.Replace(appFile, "three", "THREE!", 1)}) + if code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1"); code != 0 || !strings.Contains(stdout, `"kind":"dependency","needs":[3]`) { + t.Fatalf("run = %d, want #5 parked as long as #3 is:\n%s\n%s", code, stdout, stderr) + } + f.git("switch", "-q", "main") + w := emptyBatch(f, &fakeGH{}, "batch\n\n"+deferredBlock(line11, nil, nil, nil)+"\n") + // #3 adapted by hand: every file it changes, changed, in the batch's + // shape. + pick := w.pick(w.head, f.git("rev-parse", mc3+"^2"), map[string]string{"app/a.txt": strings.Replace(appFile, "two", "two!", 1), "app/b.txt": strings.Replace(appFile, "three", "THREE", 1)}) + fold := w.merge(w.head, pick, "fix(app): an excited two, a loud three (#3)\n\n"+batchTrailer+": "+mc3) + f.git("push", "-q", "origin", fold+":refs/heads/"+batchBranch1) + w.gh.prs = []pullRequest{f.batchPR(90, "release-1.1", batchBranch1, w.gh.prs[0].Body)} + code, stdout, stderr := f.exec(w.gh, "check", "--line", "release-1.1") + if code != 1 || strings.Contains(stderr, "#5 is parked") || strings.Contains(stdout+stderr, "waits on") || !strings.Contains(stdout, "/pull/5 ") { + t.Errorf("check = %d, want #5 missing, not parked:\n%s\n%s", code, stdout, stderr) + } + code, stdout, stderr = f.exec(w.gh, "run", "--line", "release-1.1", "--continue") + if code != 0 || !strings.Contains(stdout, `"picked":[3,5]`) { + t.Errorf("run --continue = %d, want #5 picked after #3's adaptation:\n%s\n%s", code, stdout, stderr) + } +} + +// What an earlier unit of the batch brought counts: #3 writes the line #8 +// changes, a feat takes it back and another feat, #6, writes it again, so +// blame names #6, which never comes; once #3 is picked the branch has the +// line all the same. +func TestContentFromAnotherUnitSatisfies(t *testing.T) { + f := newFixture(t) + f.squash(2, "chore: a", "", map[string]string{"app/a.txt": appFile}) + f.lines() + f.pr(3, "fix(app): a loud two", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO", 1)}) + f.pr(4, "feat(app): a quiet two", "", map[string]string{"app/a.txt": appFile}) + f.pr(6, "feat(app): a loud two again", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO", 1)}) + f.pr(8, "fix(app): an excited two", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!", 1)}) + code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1") + if code != 0 { + t.Fatalf("run = %d\n%s", code, stderr) + } + if got := f.subjects("origin/release-1.1", "HEAD"); !slices.Equal(got, []string{"fix(app): a loud two (#3)", "fix(app): an excited two (#8)"}) { + t.Errorf("picked %q, want #3 and #8:\n%s", got, stdout) + } +} + +// auxWorld is #5142's shape: #3, a feat, adds a bats test; #5 fixes a +// workflow and that test, so all it builds on that never comes is a test; +// #6 is a plain fix. +func auxWorld(t *testing.T) *fixture { + t.Helper() + f := newFixture(t) + f.squash(2, "chore: a workflow", "", map[string]string{".github/workflows/release.yaml": "on: push\njobs: {}\n"}) + f.lines() + f.pr(3, "feat(ci): test the changelog", "", map[string]string{"hack/changelog.bats": "@test x {\n true\n}\n"}) + f.pr(5, "fix(ci): run the release on tags", "", map[string]string{".github/workflows/release.yaml": "on: [push, tag]\njobs: {}\n", "hack/changelog.bats": "@test x {\n false\n}\n"}) + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + return f +} + +// A workflow original whose only missing dependency is a test waits for a +// maintainer in the scheduled run, whose token cannot push workflows, and +// check holds the cut on it. A maintainer's own run parks it. With no batch +// open, or one whose body carries no record, it is missing; a record from +// before the mode was saved says the scheduled mode by listing a wait. +func TestWorkflowModeCarriesToCheck(t *testing.T) { + f := auxWorld(t) + gh := &fakeGH{} + if code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--no-workflow-files", "--push"); code != 0 || strings.Contains(stdout, `"parked":[{`) || !strings.Contains(stdout, `{"original":5,"files":[".github/workflows/release.yaml"],"workflows":true}`) { + t.Fatalf("scheduled run = %d, want #5 waiting, not parked:\n%s\n%s", code, stdout, stderr) + } + f.git("switch", "-q", "main") + reopen(f, gh) + if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1", "--cut"); code != 1 || !strings.Contains(stdout, "#5 changes .github/workflows/ and waits on batch PR #90") { + t.Errorf("check --cut = %d, want #5 waiting:\n%s\n%s", code, stdout, stderr) + } + v1 := "batch\n\n" + deferredBlock(line11, nil, nil, []pick{{v: &verdict{o: &original{number: 5}}, files: []string{".github/workflows/release.yaml"}}}) + "\n" + gh.prs = []pullRequest{f.batchPR(90, "release-1.1", batchBranch1, v1)} + if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1", "--cut"); code != 1 || !strings.Contains(stdout, "#5 changes .github/workflows/ and waits on batch PR #90") { + t.Errorf("check --cut with a version 1 record = %d, want #5 waiting:\n%s\n%s", code, stdout, stderr) + } + gh.prs = []pullRequest{f.batchPR(90, "release-1.1", batchBranch1, "a batch someone wrote")} + if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 1 || !strings.Contains(stdout, "/pull/5 ") || strings.Contains(stderr, "parked") { + t.Errorf("check under a batch with no record = %d, want #5 missing:\n%s\n%s", code, stdout, stderr) + } + + f = auxWorld(t) + if code, stdout, stderr := f.exec(nil, "check", "--line", "release-1.1"); code != 1 || !strings.Contains(stdout, "/pull/5 ") || strings.Contains(stderr, "parked") { + t.Errorf("check with no batch = %d, want #5 missing:\n%s\n%s", code, stdout, stderr) + } + gh = &fakeGH{} + if code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--push"); code != 0 || !strings.Contains(stdout, `"parked":[{"original":5,`) { + t.Fatalf("a maintainer's run = %d, want #5 parked:\n%s\n%s", code, stdout, stderr) + } + f.git("switch", "-q", "main") + reopen(f, gh) + if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 0 || !strings.Contains(stderr, "note: #5 is parked") { + t.Errorf("check after a maintainer's run = %d, want 0 with #5 parked:\n%s\n%s", code, stdout, stderr) + } +} + +// Evidence found only in a test file still parks an original that changes +// no workflow: #4973's shape. +func TestTestOnlyEvidenceParksOtherOriginals(t *testing.T) { + f := newFixture(t) + f.squash(2, "chore: nodes", "", map[string]string{"app/nodes.go": "package app\n", "app/nodes_test.go": "package app\n\nfunc a() {}\n"}) + f.lines() + f.pr(3, "feat(app): proxmox nodes", "", map[string]string{"app/nodes_test.go": "package app\n\nfunc a() { proxmox() }\n"}) + f.pr(5, "fix(app): nodes", "", map[string]string{"app/nodes.go": "package app\n\nvar fixed = true\n", "app/nodes_test.go": "package app\n\nfunc a() { proxmox(); fixed() }\n"}) + code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1") + if code != 0 || strings.Contains(stdout, "### Deferred conflicts") || !strings.Contains(stdout, `"parked":[{"original":5,`) { + t.Errorf("run = %d, want #5 parked on #3:\n%s\n%s", code, stdout, stderr) + } +} + +// What an original builds on through lines it adds is not seen: #4973's +// $isProxmox. The original is picked; CI on the batch is what catches it. +func TestAddedLinesDependencyIsNotSeen(t *testing.T) { + f := newFixture(t) + f.squash(2, "chore: nodes", "", map[string]string{"app/nodes.tpl": "a\nb\n"}) + f.lines() + f.pr(3, "feat(app): define isProxmox", "", map[string]string{"app/proxmox.tpl": "isProxmox\n"}) + f.pr(5, "fix(app): use isProxmox", "", map[string]string{"app/nodes.tpl": "a\nif isProxmox\nb\n"}) + if code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1"); code != 0 || strings.Contains(stdout, `"parked":[{`) || !strings.Contains(stdout, `"picked":[5]`) { + t.Errorf("run = %d, want #5 picked:\n%s\n%s", code, stdout, stderr) + } +} + +// With no batch open, check reads a closed record whatever its version and +// whatever mode it saved as the scheduled run's: the workflow original it +// left waiting is missing, not parked, while its drops and its other +// deferrals still count. +func TestClosedRecordModeFallback(t *testing.T) { + for _, version := range []int{2, 3} { + for _, saved := range []bool{false, true} { + t.Run(fmt.Sprintf("version %d, noWorkflowFiles %v", version, saved), func(t *testing.T) { + f := auxWorld(t) + mc6 := f.git("log", "--first-parent", "--format=%H", "-1", "--grep", "(#6)$", "main") + mc7 := f.pr(7, "fix(app): seven", "", map[string]string{"app/seven.txt": "7\n"}) + sha := f.git("rev-parse", "origin/main") + rec := lineRecord{Version: version, Line: "release-1.1", Report: strings.Repeat("b", 64), + Built: &builtFrom{Main: sha, Line: sha, Policy: sha, Batch: sha, At: "2026-10-26T06:00:00Z", Options: runOptions{NoWorkflowFiles: saved, Mode: modeContinue}}, + Deferred: []deferredEntry{{Original: 5, Files: []string{".github/workflows/release.yaml"}, Workflows: true}, {Original: 7, Commit: f.git("rev-parse", mc7+"^2"), Files: []string{"app/seven.txt"}}}, + Dropped: []droppedEntry{{Original: 6, Merge: mc6, Reason: "not for this line", On: 90, Date: "2026-10-26"}}, Stale: []int{}} + pr := f.batchPR(90, "release-1.1", batchBranch1, "batch\n\n"+recordBlock(rec)+"\n") + at := "2026-10-26T12:00:00Z" + pr.State, pr.MergedAt = "closed", &at + code, stdout, stderr := f.exec(&fakeGH{prs: []pullRequest{pr}}, "check", "--line", "release-1.1") + if code != 1 || !strings.Contains(stdout, "/pull/5 ") || strings.Contains(stderr, "#5 is parked") { + t.Errorf("check = %d, want #5 missing and not parked:\n%s\n%s", code, stdout, stderr) + } + if !strings.Contains(stderr, "note: #6 is dropped") || !strings.Contains(stderr, "warning: deferred conflict on #90 (merged): https://github.com/cozystack/cozystack/pull/7 ") { + t.Errorf("check lost the closed record's drop or deferral:\n%s", stderr) + } + }) + } + } +} + +// Withdrawing a drop puts the original back where the rules and the line +// put it: a partial original is parked again, in the record as in check. +func TestUndropRestoresThePark(t *testing.T) { + for name, world := range map[string]func(*testing.T) *fixture{ + "partial": func(t *testing.T) *fixture { + f, _ := policyWorld(t) + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + return f + }, + "dependency": featWorld, + } { + t.Run(name, func(t *testing.T) { + f := world(t) + gh := &fakeGH{} + openBatch(t, f, gh) + mustRun(t, f, gh, "run", "--line", "release-1.1", "--drop", "5", "--reason", "not for 1.1", "--push") + reopen(f, gh) + mustRun(t, f, gh, "run", "--line", "release-1.1", "--undrop", "5", "--push") + reopen(f, gh) + if rec := recordOf(t, gh); len(rec.Parked) != 1 || rec.Parked[0].Original != 5 || rec.Parked[0].Kind != name { + t.Errorf("after the undrop the record parks %+v, want #5 parked %s", rec.Parked, name) + } + if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 0 || !strings.Contains(stderr, "note: #5 is parked") { + t.Errorf("check = %d, want #5 parked:\n%s\n%s", code, stdout, stderr) + } + }) + } +} + +// A prerequisite the open batch carries is there for what builds on it, +// whatever its label now says: check and run agree that #7 is not parked. +func TestPrerequisiteStillOnTheBatchSatisfies(t *testing.T) { + f := newFixture(t) + f.squash(2, "chore: files", "", map[string]string{"app/a.txt": appFile}) + f.lines() + f.pr(5, "fix(app): five", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO", 1)}) + gh := &fakeGH{} + openBatch(t, f, gh) + f.pr(7, "fix(app): seven", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!", 1)}) + gh.labels = map[string][]int{labelSkip: {5}} + if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 1 || strings.Contains(stderr, "#7 is parked") || !strings.Contains(stdout, "/pull/7 ") { + t.Errorf("check = %d, want #7 missing, not parked:\n%s\n%s", code, stdout, stderr) + } + if code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue"); code != 0 || !strings.Contains(stdout, `"picked":[7]`) { + t.Errorf("run --continue = %d, want #7 picked:\n%s\n%s", code, stdout, stderr) + } +} + +// The picker judges what its picks did where the run has got to: #4 +// deletes the file #5 also deletes, so after #4 #5 would bring only its +// test, which the net merge at the line's head cannot see. +func TestPartialByAnEarlierPick(t *testing.T) { + f := newFixture(t) + f.squash(2, "chore: a policy", "", map[string]string{"app/policy.yaml": "allow: all\n"}) + f.lines() + f.pr(4, "fix(app): drop the policy", "", map[string]string{"app/policy.yaml": "", "app/four.txt": "4\n"}) + f.pr(40, "feat(app): the policy again", "", map[string]string{"app/policy.yaml": "allow: all\n"}) + f.pr(5, "fix(app): drop the policy and test it", "", map[string]string{"app/policy.yaml": "", "app/policy_test.txt": "gone\n"}) + code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1") + if code != 0 || !strings.Contains(stdout, `"picked":[4]`) || !strings.Contains(stdout, `"parked":[{"original":5,`) { + t.Errorf("run = %d, want #4 picked and #5 parked as partial:\n%s\n%s", code, stdout, stderr) + } +} + +// What an earlier pick brought clears a partial park the line's head +// gave: the line removed the policy, #4 brings it back, and #5's deletion +// then has something to delete. +func TestPartialClearedByAnEarlierPick(t *testing.T) { + f := newFixture(t) + f.squash(2, "chore: a policy", "", map[string]string{"app/policy.yaml": "allow: all\n"}) + f.lines() + f.onLine("release-1.1", "fix(app): the line drops the policy", map[string]string{"app/policy.yaml": ""}) + f.pr(3, "feat(app): no policy", "", map[string]string{"app/policy.yaml": ""}) + f.pr(4, "fix(app): the policy, back", "", map[string]string{"app/policy.yaml": "allow: some\n"}) + f.pr(5, "fix(app): drop the policy and test it", "", map[string]string{"app/policy.yaml": "", "app/policy_test.txt": "gone\n"}) + code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1") + if code != 0 || !strings.Contains(stdout, `"picked":[4,5]`) { + t.Errorf("run = %d, want #4 and #5 picked:\n%s\n%s", code, stdout, stderr) + } +} + +// A reason a person deferred an original for comes before its partial +// park. +func TestReasonComesBeforeThePartialPark(t *testing.T) { + f, _ := policyWorld(t) + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + gh := &fakeGH{} + openBatch(t, f, gh) + mustRun(t, f, gh, "run", "--line", "release-1.1", "--defer", "5", "--reason", "waits for the policy rework", "--push") + reopen(f, gh) + if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 0 || !strings.Contains(stderr, "warning: deferred on #90 to the next batch: https://github.com/cozystack/cozystack/pull/5 ") || strings.Contains(stderr, "#5 is parked") { + t.Errorf("check = %d, want #5 deferred for its reason:\n%s\n%s", code, stdout, stderr) + } +} + +// The workflow exception holds only while what never comes is tests or +// docs, and while the workflow lines build on nothing missing: a +// workflow original that also fixes a file a feat added, or whose workflow +// line another original still to come wrote, parks in the scheduled run too. +func TestWorkflowExceptionNeedsTestsOnly(t *testing.T) { + t.Run("a never dependency outside tests", func(t *testing.T) { + f := auxWorld(t) + f.pr(20, "feat(app): tap", "", map[string]string{"app/tap.go": appFile}) + f.pr(7, "fix(ci): test the tap, and fix it", "", map[string]string{".github/workflows/tap.yaml": "on: push\n", "app/tap.go": strings.Replace(appFile, "two", "TWO", 1)}) + if code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1", "--no-workflow-files"); code != 0 || !strings.Contains(stdout, `"parked":[{"original":7,`) { + t.Errorf("scheduled run = %d, want #7 parked:\n%s\n%s", code, stdout, stderr) + } + }) + t.Run("a workflow line still to come", func(t *testing.T) { + f := newFixture(t) + f.squash(2, "chore: a workflow", "", map[string]string{".github/workflows/release.yaml": "on: push\njobs: {}\n", "app/four.txt": "old\n"}) + f.lines() + f.onLine("release-1.1", "fix(app): four, the line's way", map[string]string{"app/four.txt": "line\n"}) + f.pr(3, "feat(ci): test the changelog", "", map[string]string{"hack/changelog.bats": "@test x {\n true\n}\n"}) + f.pr(4, "fix(ci): four", "", map[string]string{"app/four.txt": "four\n", ".github/workflows/release.yaml": "on: [push]\njobs: {}\n"}) + f.pr(5, "fix(ci): run the release on tags", "", map[string]string{".github/workflows/release.yaml": "on: [push, tag]\njobs: {}\n", "hack/changelog.bats": "@test x {\n false\n}\n"}) + if code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1", "--no-workflow-files"); code != 0 || !strings.Contains(stdout, `"parked":[{"original":5,`) { + t.Errorf("scheduled run = %d, want #5 parked:\n%s\n%s", code, stdout, stderr) + } + }) +} + +// What a rebuild takes off the batch is no longer there for what builds on +// it: deferring #5 makes #7, which merged after the batch was built, wait +// on it. +func TestRebuildTakesThePrerequisiteAway(t *testing.T) { + f := newFixture(t) + f.squash(2, "chore: files", "", map[string]string{"app/a.txt": appFile}) + f.lines() + f.pr(5, "fix(app): five", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO", 1)}) + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + gh := &fakeGH{} + openBatch(t, f, gh) + f.pr(7, "fix(app): seven", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!", 1)}) + if code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--defer", "5", "--reason", "fails the e2e"); code != 0 || !strings.Contains(stdout, `{"original":7,"files":[],"needs":[5]}`) { + t.Errorf("run --defer 5 = %d, want #7 waiting on #5:\n%s\n%s", code, stdout, stderr) + } +} + +// A file the line renamed the way the original does is the original's own +// rename, not a deletion left without effect. +func TestSameRenameOnBothSidesIsWhole(t *testing.T) { + const long = "l01\nl02\nl03\nl04\nl05\nl06\nl07\nl08\nl09\nl10\nl11\nl12\n" + f := newFixture(t) + f.squash(2, "chore: a file", "", map[string]string{"app/p.txt": long}) + f.lines() + f.onLine("release-1.1", "fix(app): the line renames p to q", map[string]string{"app/p.txt": "", "app/q.txt": long}) + f.pr(5, "fix(app): rename p to q, and fix l10", "", map[string]string{"app/p.txt": "", "app/q.txt": strings.Replace(long, "l10", "L10", 1)}) + if code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1"); code != 0 || !strings.Contains(stdout, `"picked":[5]`) { + t.Errorf("run = %d, want #5 picked whole:\n%s\n%s", code, stdout, stderr) + } +} + +// A partial park only the picker saw, where the net merge at the line's +// head looks whole, holds in check and in the operations that pick nothing +// as the open record keeps it: check does not call the original missing. +func TestPickerParkHoldsInCheck(t *testing.T) { + f := newFixture(t) + f.squash(2, "chore: a policy", "", map[string]string{"app/policy.yaml": "allow: all\n"}) + f.lines() + f.pr(4, "fix(app): drop the policy", "", map[string]string{"app/policy.yaml": "", "app/four.txt": "4\n"}) + f.pr(40, "feat(app): the policy again", "", map[string]string{"app/policy.yaml": "allow: all\n"}) + f.pr(5, "fix(app): drop the policy and test it", "", map[string]string{"app/policy.yaml": "", "app/policy_test.txt": "gone\n"}) + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + gh := &fakeGH{} + openBatch(t, f, gh) + if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 0 || !strings.Contains(stderr, "note: #5 is parked: only part of it applies") { + t.Errorf("check = %d, want #5 parked as the record says:\n%s\n%s", code, stdout, stderr) + } + if code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--defer", "6", "--reason", "fails the e2e"); code != 0 || !strings.Contains(stdout, `"parked":[{"original":5,`) { + t.Errorf("run --defer 6 = %d, want #5 still parked:\n%s\n%s", code, stdout, stderr) + } + // Deferring #4, which made #5 partial, ends the park: #5 applies whole + // on what the batch carries now. + f.git("switch", "-q", "main") + code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--defer", "4", "--reason", "fails the e2e", "--push") + if code != 0 || strings.Contains(stdout, `"parked":[{`) || !strings.Contains(stdout, `"missing":[5]`) { + t.Errorf("run --defer 4 = %d, want #5 missing, no longer parked:\n%s\n%s", code, stdout, stderr) + } + reopen(f, gh) + if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 1 || strings.Contains(stderr, "#5 is parked") || !strings.Contains(stdout, "/pull/5 ") { + t.Errorf("check after deferring #4 = %d, want #5 missing:\n%s\n%s", code, stdout, stderr) + } +} + +// A workflow original that waits for a maintainer only as the open record +// lists it: one merged since the batch was built is missing, and so is +// what waits on it. +func TestUnlistedWorkflowWaitIsMissing(t *testing.T) { + f := auxWorld(t) + gh := &fakeGH{} + mustRun(t, f, gh, "run", "--line", "release-1.1", "--no-workflow-files", "--push") + f.git("switch", "-q", "main") + reopen(f, gh) + f.pr(8, "fix(ci): run the new release on tags", "", map[string]string{".github/workflows/new.yaml": "on: tag\n", "hack/changelog.bats": "@test x {\n false\n}\n# eight\n", "app/eight.txt": appFile + "TWO\n"}) + f.pr(9, "fix(app): nine", "", map[string]string{"app/eight.txt": appFile + "TWO!\n"}) + if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 1 || !strings.Contains(stdout, "/pull/9 fix(app): nine (it waits on #8, which is not on the line either)") { + t.Errorf("check = %d, want #9 missing, waiting on #8:\n%s\n%s", code, stdout, stderr) + } +} + +// The line's own rename stands for the original's only with the original's +// change in it: a fold that leaves the renamed file as it was is refused. +func TestSameRenameStillNeedsItsFix(t *testing.T) { + const long = "l01\nl02\nl03\nl04\nl05\nl06\nl07\nl08\nl09\nl10\nl11\nl12\n" + f := newFixture(t) + f.squash(2, "chore: a file", "", map[string]string{"app/p.txt": long}) + f.lines() + f.onLine("release-1.1", "fix(app): the line renames p to q", map[string]string{"app/p.txt": "", "app/q.txt": long}) + mc5 := f.pr(5, "fix(app): rename p to q, fix l10, and five", "", map[string]string{"app/p.txt": "", "app/q.txt": strings.Replace(long, "l10", "L10", 1), "app/five.txt": "5\n"}) + w := emptyBatch(f, &fakeGH{}, "") + pick := w.pick(w.head, f.git("rev-parse", mc5+"^2"), map[string]string{"app/five.txt": "5\n"}) + fold := w.merge(w.head, pick, "fix(app): rename p to q, fix l10, and five (#5)\n\n"+batchTrailer+": "+mc5) + if code, out, stderr := f.exec(w.gh, "fold", "--line", "release-1.1", "--original", "5", "--commit", fold); code != 1 || !strings.Contains(out, `leaves "app/p.txt" without effect`) { + t.Errorf("fold without the fix in q = %d, %q\n%s", code, out, stderr) + } +} + +// A prerequisite the line carries is there, though the rules would keep it +// out: a feat carried by a hand adaptation does not park what builds on it. +func TestCarriedExcludedPrerequisiteSatisfies(t *testing.T) { + f := newFixture(t) + f.squash(2, "chore: a", "", map[string]string{"app/a.txt": appFile}) + f.lines() + mc3 := f.pr(3, "feat(app): a loud two", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO", 1)}) + f.onLine("release-1.1", "feat(app): a loud two, adapted\n\n(cherry picked from commit "+mc3+")", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "Two", 1)}) + f.pr(5, "fix(app): an excited two", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!", 1)}) + if code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1"); code != 0 || strings.Contains(stdout, `"parked":[{`) { + t.Errorf("run = %d, want #5 not parked on the carried #3:\n%s\n%s", code, stdout, stderr) + } + f.git("switch", "-q", "main") + if code, stdout, stderr := f.exec(nil, "check", "--line", "release-1.1"); code != 1 || strings.Contains(stderr, "#5 is parked") { + t.Errorf("check = %d, want #5 missing, not parked:\n%s\n%s", code, stdout, stderr) + } +} + +// With no batch open, a workflow wait a closed record keeps waits on +// nothing: the original is judged as the scheduled run judges it, so one +// that also builds on a feat the line lacks is parked, in check as in run. +func TestClosedWorkflowWaitIsJudgedAsRunJudgesIt(t *testing.T) { + f := auxWorld(t) + f.pr(20, "feat(app): tap", "", map[string]string{"app/tap.go": appFile}) + f.pr(7, "fix(ci): test the tap, and fix it", "", map[string]string{".github/workflows/tap.yaml": "on: push\n", "app/tap.go": strings.Replace(appFile, "two", "TWO", 1)}) + sha := f.git("rev-parse", "origin/main") + rec := lineRecord{Version: 2, Line: "release-1.1", Report: strings.Repeat("b", 64), + Built: &builtFrom{Main: sha, Line: sha, Policy: sha, Batch: sha, At: "2026-10-26T06:00:00Z", Options: runOptions{NoWorkflowFiles: true, Mode: modeContinue}}, + Deferred: []deferredEntry{{Original: 7, Files: []string{".github/workflows/tap.yaml"}, Workflows: true}}, Dropped: []droppedEntry{}, Stale: []int{}} + pr := f.batchPR(90, "release-1.1", batchBranch1, "batch\n\n"+recordBlock(rec)+"\n") + at := "2026-10-26T12:00:00Z" + pr.State, pr.MergedAt = "closed", &at + gh := &fakeGH{prs: []pullRequest{pr}} + if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1", "--cut"); strings.Contains(stdout, "/pull/7 ") || !strings.Contains(stderr, "note: #7 is parked: it builds on #20") { + t.Errorf("check --cut = %d, want #7 parked:\n%s\n%s", code, stdout, stderr) + } + if code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--no-workflow-files"); code != 0 || !strings.Contains(stdout, `"parked":[{"original":7,`) { + t.Errorf("scheduled run = %d, want #7 parked:\n%s\n%s", code, stdout, stderr) + } +} + +// A pick that comes out empty is judged too: #5's own commit did half its +// fix, which the line has, and a merge of main into its branch did the +// rest, which no pick carries; #5 is not on the line. +func TestEmptyPicksStillJudged(t *testing.T) { + f := newFixture(t) + f.squash(2, "chore: b", "", map[string]string{"app/b.txt": "old\n"}) + f.lines() + f.onLine("release-1.1", "fix(app): b, half of it", map[string]string{"app/b.txt": "middle\n"}) + f.git("switch", "-q", "-c", "pr-5", "main") + f.apply(map[string]string{"app/b.txt": "middle\n"}) + f.git("commit", "-q", "-m", "b, half of it") + f.git("switch", "-q", "main") + f.apply(map[string]string{"app/main.txt": "moved\n"}) + f.git("commit", "-q", "-m", "chore: move main along") + f.git("switch", "-q", "pr-5") + f.git("merge", "-q", "--no-ff", "--no-commit", "main") + f.apply(map[string]string{"app/b.txt": "fixed\n"}) + f.git("commit", "-q", "-m", "Merge branch 'main' into pr-5") + f.git("switch", "-q", "main") + f.git("merge", "-q", "--no-ff", "-m", "fix(app): b (#5)", "pr-5") + f.git("push", "-q", "origin", "main") + if code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1"); code != 0 || strings.Contains(stdout, `"on-line":[5]`) || !strings.Contains(stdout, `"parked":[{"original":5,`) { + t.Errorf("run = %d, want #5 parked as partial, not on the line:\n%s\n%s", code, stdout, stderr) + } +} + +// --defer takes off a unit that does only part of its original whatever +// rule now keeps that original out, as check tells it to. +func TestDeferTakesOffAPartialExcludedUnit(t *testing.T) { + f := newFixture(t) + f.lines() + f.pr(3, "feat(chart): a network policy", "", map[string]string{"chart/templates/policy.yaml": "kind: NetworkPolicy\n"}) + mc5 := f.pr(5, "feat(chart): remove the policy, and test values", "", map[string]string{"chart/templates/policy.yaml": "", "chart/tests/values_test.yaml": "suite: values\n"}) + gh := &fakeGH{} + handBatch(f, gh, mc5) + if code, stdout, _ := f.exec(gh, "check", "--line", "release-1.1", "--cut"); code != 1 || !strings.Contains(stdout, "only part of it applies") { + t.Fatalf("check --cut = %d, want the partial unit to fail it:\n%s", code, stdout) + } + if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--defer", "5", "--reason", "only part of it applies", "--push"); code != 0 || prState(gh.find(90)) != "closed" { + t.Errorf("run --defer 5 --push = %d, #90 %s; want the unit taken off and the batch closed:\n%s", code, prState(gh.find(90)), stderr) + } +} + +// A stored wait on an original merged after the one that waits cannot be +// what a run wrote. +func TestForwardWaitIsRefused(t *testing.T) { + f := newFixture(t) + f.lines() + f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"}) + f.pr(7, "fix(app): seven", "", map[string]string{"app/seven.txt": "7\n"}) + sha := f.git("rev-parse", "origin/main") + rec := lineRecord{Version: recordVersion, Line: "release-1.1", Report: strings.Repeat("b", 64), + Built: &builtFrom{Main: sha, Line: sha, Policy: sha, Batch: sha, At: "2026-10-26T06:00:00Z", Options: runOptions{Mode: modeContinue}}, + Deferred: []deferredEntry{{Original: 5, Files: []string{}, Needs: []int{7}}}, Dropped: []droppedEntry{}, Stale: []int{}} + f.git("push", "-q", "origin", "origin/release-1.1:refs/heads/"+batchBranch1) + gh := &fakeGH{prs: []pullRequest{f.batchPR(90, "release-1.1", batchBranch1, "batch\n\n"+recordBlock(rec)+"\n")}} + if code, _, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 2 || !strings.Contains(stderr, "#5 wait on #7") { + t.Errorf("check = %d, want 2 for a wait on a later original:\n%s", code, stderr) + } +} + +// The workflow exception looks only at what still keeps the original from +// the line: a workflow line its prerequisite wrote, which the open batch +// carries though that prerequisite is labelled backport/skip, does not +// stop it, in check as in run. +func TestWorkflowExceptionIgnoresWhatIsThere(t *testing.T) { + f := newFixture(t) + f.squash(2, "chore: a workflow", "", map[string]string{".github/workflows/release.yaml": "on: push\njobs: {}\n"}) + f.lines() + f.pr(3, "feat(ci): test the changelog", "", map[string]string{"hack/changelog.bats": "@test x {\n true\n}\n"}) + f.pr(4, "fix(ci): run the release on pushes", "", map[string]string{".github/workflows/release.yaml": "on: [push]\njobs: {}\n"}) + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + f.pr(7, "fix(ci): run the release on tags too", "", map[string]string{".github/workflows/release.yaml": "on: [push, tag]\njobs: {}\n", "hack/changelog.bats": "@test x {\n false\n}\n"}) + gh := &fakeGH{} + mustRun(t, f, gh, "run", "--line", "release-1.1", "--push") + f.git("switch", "-q", "main") + reopen(f, gh) + gh.labels = map[string][]int{labelSkip: {4}} + if code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--no-workflow-files", "--push"); code != 0 || !strings.Contains(stdout, `{"original":7,"files":[".github/workflows/release.yaml"],"workflows":true}`) { + t.Fatalf("scheduled run = %d, want #7 waiting for a maintainer:\n%s\n%s", code, stdout, stderr) + } + f.git("switch", "-q", "main") + reopen(f, gh) + if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1", "--cut"); code != 1 || !strings.Contains(stdout, "#7 changes .github/workflows/ and waits on batch PR #90") { + t.Errorf("check --cut = %d, want #7 waiting, as run has it:\n%s\n%s", code, stdout, stderr) + } +} + +// An empty pick leaves a deletion undone that only a merge of main into the +// original's branch made: the original is not on the line. +func TestEmptyPickLeavesADeletionUndone(t *testing.T) { + f := newFixture(t) + f.squash(2, "chore: a and b", "", map[string]string{"app/a.txt": "old feature\n", "app/b.txt": "old\n"}) + f.lines() + f.onLine("release-1.1", "fix(app): b, already", map[string]string{"app/b.txt": "fixed\n"}) + f.git("switch", "-q", "-c", "pr-5", "main") + f.apply(map[string]string{"app/b.txt": "fixed\n"}) + f.git("commit", "-q", "-m", "b") + f.git("switch", "-q", "main") + f.apply(map[string]string{"app/main.txt": "moved\n"}) + f.git("commit", "-q", "-m", "chore: move main along") + f.git("switch", "-q", "pr-5") + f.git("merge", "-q", "--no-ff", "--no-commit", "main") + f.git("rm", "-q", "app/a.txt") + f.git("commit", "-q", "-m", "Merge branch 'main' into pr-5") + f.git("switch", "-q", "main") + f.git("merge", "-q", "--no-ff", "-m", "fix(app): b, and a goes (#5)", "pr-5") + f.git("push", "-q", "origin", "main") + if code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1"); code != 0 || strings.Contains(stdout, `"on-line":[5]`) || !strings.Contains(stdout, `"parked":[{"original":5,`) { + t.Errorf("run = %d, want #5 parked as partial, not on the line:\n%s\n%s", code, stdout, stderr) + } +} + +// A file the line already has as the original makes it builds on nothing +// the line lacks: #5 fixes a.txt, which the line fixed the same way, and +// b.txt, so it picks whole and is not parked on the feat that wrote a.txt. +func TestAlreadyAppliedFileBuildsOnNothing(t *testing.T) { + f := newFixture(t) + f.squash(2, "chore: a and b", "", map[string]string{"app/a.txt": appFile, "app/b.txt": "old\n"}) + f.lines() + f.pr(3, "feat(app): a loud two", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO", 1)}) + f.onLine("release-1.1", "fix(app): two, the line's way", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!", 1)}) + f.pr(5, "fix(app): an excited two, and b", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!", 1), "app/b.txt": "fixed\n"}) + if code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1"); code != 0 || strings.Contains(stdout, `"parked":[{`) || !strings.Contains(stdout, `"picked":[5]`) { + t.Errorf("run = %d, want #5 picked, not parked:\n%s\n%s", code, stdout, stderr) + } +} diff --git a/cmd/backport-batch/policy.go b/cmd/backport-batch/policy.go new file mode 100644 index 000000000..ee74c76e8 --- /dev/null +++ b/cmd/backport-batch/policy.go @@ -0,0 +1,144 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package main + +import ( + "fmt" + "regexp" + "strconv" + "strings" + "time" +) + +// policyPage is the policy the batch applies. The block in it that names when +// each line started under the policy is read from the page itself, on the ref +// the run pins, so the page and the batch cannot drift apart. +const policyPage = "docs/release/backports.md" + +const policyFence = "```backport-policy" + +var ( + policyLineRE = regexp.MustCompile(`^(release-\d+\.\d+|` + batchOnlyKey + `):[ \t]*(\d{4}-\d{2}-\d{2})[ \t]*$`) + policyReleasedRE = regexp.MustCompile(`^` + releasedKey + `:[ \t]*(\d+)[ \t]*$`) +) + +const ( + // batchOnlyKey names the day from which the batch is the only way onto a + // line, so that from then on only its picks show what a line carries. + batchOnlyKey = "batch-only" + // releasedKey names how many of the lines that have shipped a stable + // release the batch runs for, the newest of them; defaultReleased when + // the block does not say. + releasedKey = "released-lines" + defaultReleased = 2 +) + +// The rule 2 types and the scopes that never go into a patch release, as the +// policy page lists them; policy_test.go holds the page to these. +var ( + takenTypes = []string{"fix", "security"} + excludedScopes = []string{"deps"} +) + +// starts maps a release line to the day it started under the policy. A line +// that is not listed started at its fork point from main. +type starts map[string]time.Time + +// policy is what the backport-policy block says: when each line started, the +// batch-only day, and how many released lines the batch runs for. +type policy struct { + starts starts + batchOnly time.Time + released int +} + +// parsePolicy reads the one backport-policy block of the page: a line per +// release line, `release-X.Y: YYYY-MM-DD`, exactly one `batch-only: +// YYYY-MM-DD`, at most one `released-lines: N`, and comments starting with #. +func parsePolicy(page string) (*policy, error) { + var blocks [][]string + var cur []string + in := false + for _, ln := range strings.Split(strings.ReplaceAll(page, "\r\n", "\n"), "\n") { + t := strings.TrimSpace(ln) + switch { + case !in && t == policyFence: + in, cur = true, nil + case in && t == "```": + in = false + blocks = append(blocks, cur) + case in: + cur = append(cur, t) + } + } + if in { + return nil, fmt.Errorf("%s: the %s block is not closed", policyPage, policyFence) + } + if len(blocks) != 1 { + return nil, fmt.Errorf("%s holds %d %s blocks, not one", policyPage, len(blocks), policyFence) + } + out := &policy{starts: starts{}, released: defaultReleased} + seen := map[string]bool{} + for _, t := range blocks[0] { + if t == "" || strings.HasPrefix(t, "#") { + continue + } + if m := policyReleasedRE.FindStringSubmatch(t); m != nil { + n, err := strconv.Atoi(m[1]) + switch { + case err != nil || n < 1: + return nil, fmt.Errorf("%s: %s is %q, not a number of lines", policyPage, releasedKey, m[1]) + case seen[releasedKey]: + return nil, fmt.Errorf("%s: %s is listed twice", policyPage, releasedKey) + } + seen[releasedKey], out.released = true, n + continue + } + m := policyLineRE.FindStringSubmatch(t) + if m == nil { + return nil, fmt.Errorf("%s: %q in the %s block is not `release-X.Y: YYYY-MM-DD`, `%s: YYYY-MM-DD` or `%s: N`", policyPage, t, policyFence, batchOnlyKey, releasedKey) + } + day, err := time.Parse(time.DateOnly, m[2]) + if err != nil { + return nil, fmt.Errorf("%s: %q is not a date: %w", policyPage, m[2], err) + } + if seen[m[1]] { + return nil, fmt.Errorf("%s: %s is listed twice", policyPage, m[1]) + } + seen[m[1]] = true + if m[1] == batchOnlyKey { + out.batchOnly = day + continue + } + if _, err := parseLine(m[1]); err != nil { + return nil, fmt.Errorf("%s: %w", policyPage, err) + } + out.starts[m[1]] = day + } + if !seen[batchOnlyKey] { + return nil, fmt.Errorf("%s: the %s block gives no %s day", policyPage, policyFence, batchOnlyKey) + } + return out, nil +} + +func readPolicy(commit string) (*policy, error) { + page, err := git("show", "--end-of-options", commit+":"+policyPage) + if err != nil { + return nil, fmt.Errorf("reading the policy at %.12s: %w", commit, err) + } + return parsePolicy(page) +} diff --git a/cmd/backport-batch/policy_test.go b/cmd/backport-batch/policy_test.go new file mode 100644 index 000000000..2cd7d20f3 --- /dev/null +++ b/cmd/backport-batch/policy_test.go @@ -0,0 +1,212 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package main + +import ( + "os" + "regexp" + "slices" + "strings" + "testing" + "time" +) + +func TestParsePolicy(t *testing.T) { + got, err := parsePolicy("text\n\n" + policyFence + "\n# comment\n\nrelease-1.6: 2026-10-26\nrelease-1.5:2026-01-02\nbatch-only: 2026-10-20\n```\n") + if err != nil { + t.Fatal(err) + } + if len(got.starts) != 2 || !got.starts["release-1.6"].Equal(time.Date(2026, 10, 26, 0, 0, 0, 0, time.UTC)) { + t.Errorf("parsePolicy = %v", got) + } + if !got.batchOnly.Equal(time.Date(2026, 10, 20, 0, 0, 0, 0, time.UTC)) { + t.Errorf("the batch-only day = %v, want 2026-10-20", got.batchOnly) + } + if got.released != 2 { + t.Errorf("released lines with none given = %d, want 2", got.released) + } + if got, err := parsePolicy(policyFence + "\nbatch-only: 2026-10-20\n```\n"); err != nil || len(got.starts) != 0 { + t.Errorf("a block with no line = %v, %v; want no starts", got, err) + } + if got, err := parsePolicy(policyFence + "\nbatch-only: 2026-10-20\nreleased-lines: 3\n```\n"); err != nil || got.released != 3 { + t.Errorf("released-lines: 3 = %v, %v; want 3", got, err) + } + for name, page := range map[string]string{ + "no batch-only day": policyFence + "\nrelease-1.6: 2026-10-26\n```\n", + "two batch-only days": policyFence + "\nbatch-only: 2026-10-26\nbatch-only: 2026-10-27\n```\n", + "a bad batch-only day": policyFence + "\nbatch-only: soon\n```\n", + "no block": "## Backports\n", + "two blocks": policyFence + "\n```\n" + policyFence + "\n```\n", + "unclosed": policyFence + "\nrelease-1.6: 2026-10-26\n", + "a bad line": policyFence + "\nrelease 1.6 on 2026-10-26\n```\n", + "a bad date": policyFence + "\nrelease-1.6: 2026-13-40\n```\n", + "a padded line": policyFence + "\nrelease-01.6: 2026-10-26\n```\n", + "listed twice": policyFence + "\nrelease-1.6: 2026-10-26\nrelease-1.6: 2026-10-27\n```\n", + "not a line": policyFence + "\nmain: 2026-10-26\n```\n", + "trailing words": policyFence + "\nrelease-1.6: 2026-10-26 or so\n```\n", + "no released lines": policyFence + "\nbatch-only: 2026-10-26\nreleased-lines: 0\n```\n", + "released lines twice": policyFence + "\nbatch-only: 2026-10-26\nreleased-lines: 2\nreleased-lines: 3\n```\n", + "released lines words": policyFence + "\nbatch-only: 2026-10-26\nreleased-lines: two\n```\n", + "released lines huge": policyFence + "\nbatch-only: 2026-10-26\nreleased-lines: 99999999999999999999\n```\n", + } { + if _, err := parsePolicy(page); err == nil { + t.Errorf("%s: parsePolicy accepted it", name) + } + } +} + +// A line listed in the policy takes nothing merged before its start, unless a +// maintainer lets an original in; any other line starts at its fork point. +func TestPolicyStart(t *testing.T) { + f := newFixture(t) + f.lines() + f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"}) + f.pr(6, "feat(app): six", "", map[string]string{"app/six.txt": "6\n"}) + f.pr(7, "fix(app): seven", "", map[string]string{"app/seven.txt": "7\n"}) + gh := &fakeGH{labels: map[string][]int{labelInclude: {6, 7}}} + + verdicts := func() map[int]*verdict { + t.Helper() + f.git("fetch", "-q", "origin") + l, _ := parseLine("release-1.1") + b, err := (&app{gh: gh, stderr: &strings.Builder{}}).prepare(l) + if err != nil { + t.Fatal(err) + } + return map[int]*verdict{5: b.find(5), 6: b.find(6), 7: b.find(7)} + } + if v := verdicts(); v[5].rule != 0 || v[6].rule != 0 || v[7].rule != 0 { + t.Errorf("with no start every original qualifies: %d %d %d", v[5].rule, v[6].rule, v[7].rule) + } + + f.setPolicy("release-1.1: 2099-01-01\n") + v := verdicts() + if v[5].rule != ruleBeforeStart { + t.Errorf("#5 = rule %d (%s), want merged before the start", v[5].rule, v[5].reason) + } + if v[6].rule != 0 || v[7].rule != 0 { + t.Errorf("backport/include lifts the start: #6 = rule %d, #7 = rule %d", v[6].rule, v[7].rule) + } + + f.setPolicy("release-1.0: 2099-01-01\n") + if v := verdicts(); v[5].rule != 0 { + t.Errorf("a start for another line kept #5 out of release-1.1: rule %d", v[5].rule) + } + + f.setPolicy("release-1.1: 2000-01-01\n") + if v := verdicts(); v[5].rule != 0 { + t.Errorf("a start before the fork point kept #5 out: rule %d", v[5].rule) + } +} + +// The policy is read from main as the run pins it, or from the ref --policy +// names, and a run without a readable policy stops. Only the commands that +// read the policy take --policy. +func TestPolicyRef(t *testing.T) { + f := newFixture(t) + f.lines() + f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"}) + f.git("switch", "-q", "-c", "proposal") + f.write(policyPage, policyWith("release-1.1: 2099-01-01\n"+releasedKey+": 1\n")) + f.git("commit", "-q", "-am", "docs: start release-1.1 later") + f.git("switch", "-q", "main") + + code, stdout, stderr := f.exec(nil, "check", "--line", "release-1.1") + if code != 1 || !strings.Contains(stdout, "/pull/5 ") { + t.Errorf("check against main's policy = %d, %q, %s; want #5 missing", code, stdout, stderr) + } + code, stdout, stderr = f.exec(nil, "check", "--line", "release-1.1", "--policy", "proposal") + if code != 0 { + t.Errorf("check against the proposal's policy = %d, %q, %s; want #5 before the start", code, stdout, stderr) + } + if code, _, _ := f.exec(nil, "check", "--line", "release-1.1", "--policy", "--upload-pack=x"); code != 2 { + t.Errorf("--policy with an option = %d, want 2", code) + } + if code, stdout, stderr := f.exec(nil, "lines", "--policy", "proposal"); code != 0 || stdout != "release-1.1\n" { + t.Errorf("lines against the proposal's policy = %d, %q (%s); want release-1.1 alone", code, stdout, stderr) + } + for _, cmd := range []string{"verify", "notify"} { + if code, _, stderr := f.exec(&fakeGH{}, cmd, "--line", "release-1.1", "--policy", "proposal"); code != 2 || !strings.Contains(stderr, "flag provided but not defined: -policy") { + t.Errorf("%s --policy = %d (%s); want it refused, as %s reads no policy", cmd, code, stderr, cmd) + } + } + + f.squash(9001, "docs: drop the page", "", map[string]string{policyPage: ""}) + if code, _, stderr := f.exec(nil, "check", "--line", "release-1.1"); code != 2 || !strings.Contains(stderr, "reading the policy") { + t.Errorf("check without a policy page = %d (%s), want 2", code, stderr) + } +} + +// The policy page and the code say the same thing: the start block parses as +// the batch reads it, rule 2 names the types the code takes, the page names +// the scopes the code keeps out, and both override labels. +func TestPolicyPageMatchesCode(t *testing.T) { + data, err := os.ReadFile("../../" + policyPage) + if err != nil { + t.Fatal(err) + } + page := string(data) + pol, err := parsePolicy(page) + if err != nil { + t.Fatalf("the page's policy block does not parse: %v", err) + } + if day, ok := pol.starts["release-1.6"]; !ok || day.Format(time.DateOnly) != "2026-10-26" { + t.Errorf("release-1.6 starts %v, want 2026-10-26", pol.starts["release-1.6"]) + } + if day := pol.batchOnly.Format(time.DateOnly); day != "2026-10-26" { + t.Errorf("the batch-only day is %s, want 2026-10-26", day) + } + // The page says how many released lines the batch runs for, rather than + // leaving it to the default. + if !regexp.MustCompile("(?m)^"+releasedKey+":").MatchString(page) || pol.released != 2 { + t.Errorf("the page's block gives %d released lines, want 2 written out", pol.released) + } + + rule2 := regexp.MustCompile(`(?m)^2\. Its title type is (.*)$`).FindStringSubmatch(page) + if rule2 == nil { + t.Fatal("the page has no rule 2") + } + var types []string + for _, m := range regexp.MustCompile("`([a-z]+)`").FindAllStringSubmatch(rule2[1], -1) { + types = append(types, m[1]) + } + if !slices.Equal(types, takenTypes) { + t.Errorf("rule 2 on the page takes %v, the code %v", types, takenTypes) + } + never := regexp.MustCompile(`(?m)^### What waits for the next minor\n\n(.*)$`).FindStringSubmatch(page) + if never == nil { + t.Fatal("the page has no list of what never goes into a patch release") + } + for _, scope := range excludedScopes { + if !strings.Contains(never[1], "(scope `"+scope+"`)") { + t.Errorf("the page does not keep scope %s out", scope) + } + } + if scopes := regexp.MustCompile("scope `([a-z]+)`").FindAllStringSubmatch(never[1], -1); len(scopes) != len(excludedScopes) { + t.Errorf("the page keeps %d scopes out, the code %d", len(scopes), len(excludedScopes)) + } + for i := 1; i <= 6; i++ { + if !regexp.MustCompile("(?m)^" + string(rune('0'+i)) + "\\. ").MatchString(page) { + t.Errorf("the page has no rule %d", i) + } + } + for _, label := range []string{labelInclude, labelSkip} { + if !strings.Contains(page, "`"+label+"`") { + t.Errorf("the page does not describe %s", label) + } + } +} diff --git a/cmd/backport-batch/record.go b/cmd/backport-batch/record.go new file mode 100644 index 000000000..37dd7946a --- /dev/null +++ b/cmd/backport-batch/record.go @@ -0,0 +1,682 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package main + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "maps" + "regexp" + "slices" + "strings" + "time" +) + +// A line's record is the backport-batch block of its newest batch pull +// request, read whatever that pull request's state and written only while it +// is open: a merged or closed pull request is never written again, so what it +// recorded stays what the line's later commands act on until a newer batch +// carries a record of its own. + +// lineRecord is the one line of JSON in the block. Version 1, the block +// before it had a version, holds only line and deferred; version 3 adds what +// is parked and which units on the batch do only part of their original. +type lineRecord struct { + Version int `json:"version"` + Line string `json:"line"` + Built *builtFrom `json:"built,omitempty"` + Report string `json:"report,omitempty"` + Closing *closing `json:"closing"` + Deferred []deferredEntry `json:"deferred"` + Dropped []droppedEntry `json:"dropped"` + Stale []int `json:"stale"` + Parked []parkedEntry `json:"parked,omitempty"` + Partial []int `json:"partial,omitempty"` + // Changed are the picks that differ from their originals. + Changed []int `json:"changed,omitempty"` +} + +// recordVersion is the version a run writes. +const recordVersion = 3 + +// lineRecordV2 is version 2, which has none of version 3's keys. +type lineRecordV2 struct { + Version int `json:"version"` + Line string `json:"line"` + Built *builtFrom `json:"built,omitempty"` + Report string `json:"report,omitempty"` + Closing *closing `json:"closing"` + Deferred []deferredEntry `json:"deferred"` + Dropped []droppedEntry `json:"dropped"` + Stale []int `json:"stale"` +} + +// The kinds of park: an original that builds on what never reaches the +// line, and one whose clean pick would leave part of it without effect. +const ( + parkDependency = "dependency" + parkPartial = "partial" +) + +// parkedEntry is an original the batch leaves out because it cannot land on +// the line whole: what it needs that never comes, or the paths it would +// leave without effect. announced says notify has named it on the open +// batch, for exactly this entry. +type parkedEntry struct { + Original int `json:"original"` + Merge string `json:"merge"` + Kind string `json:"kind"` + Needs []int `json:"needs,omitempty"` + Commits []string `json:"commits,omitempty"` + Files []string `json:"files,omitempty"` + Announced bool `json:"announced,omitempty"` +} + +// parkEvent is what makes a park the same park from one record to the +// next: its merge, kind, prerequisites, commits and files. A park whose +// event changed is news, and notify names it again. +func parkEvent(p parkedEntry) string { + data, _ := json.Marshal(struct { + Merge string `json:"merge"` + Kind string `json:"kind"` + Needs []int `json:"needs"` + Commits []string `json:"commits"` + Files []string `json:"files"` + }{p.Merge, p.Kind, p.Needs, p.Commits, p.Files}) + return string(data) +} + +// carryAnnounced marks each park announced that the carrier's record holds +// announced as the same event, a closed carrier's too, so a new batch does +// not name again what an earlier one named. +func carryAnnounced(parked []parkedEntry, carrier *lineRecord) []parkedEntry { + out := slices.Clone(parked) + for i := range out { + out[i].Announced = false + } + if carrier == nil { + return out + } + for i := range out { + out[i].Announced = slices.ContainsFunc(carrier.Parked, func(c parkedEntry) bool { + return c.Announced && c.Original == out[i].Original && parkEvent(c) == parkEvent(out[i]) + }) + } + return out +} + +// validate holds a parked entry to what a run writes. Its errors read after +// "the block" or "report ". +func (p parkedEntry) validate() error { + sortedUnique := func(n int, less func(i int) bool) bool { + for i := 1; i < n; i++ { + if !less(i) { + return false + } + } + return true + } + switch { + case checkSHA(p.Merge) != nil: + return fmt.Errorf("parks #%d by merge %q", p.Original, p.Merge) + case !sortedUnique(len(p.Needs), func(i int) bool { return p.Needs[i-1] < p.Needs[i] }) || slices.ContainsFunc(p.Needs, func(n int) bool { return n <= 0 || n == p.Original }): + return fmt.Errorf("parks #%d for originals %v, which are not what a run writes", p.Original, p.Needs) + case !sortedUnique(len(p.Commits), func(i int) bool { return p.Commits[i-1] < p.Commits[i] }) || slices.ContainsFunc(p.Commits, func(c string) bool { return checkSHA(c) != nil }): + return fmt.Errorf("parks #%d for commits %q, which are not what a run writes", p.Original, p.Commits) + case !sortedUnique(len(p.Files), func(i int) bool { return p.Files[i-1] < p.Files[i] }) || !slices.Equal(p.Files, cleanFiles(p.Files)): + return fmt.Errorf("parks #%d for files %q, which are not what a run writes", p.Original, p.Files) + } + switch p.Kind { + case parkPartial: + if len(p.Files) == 0 || len(p.Needs)+len(p.Commits) > 0 { + return fmt.Errorf("parks #%d as partial with no files it leaves without effect, or with what it needs", p.Original) + } + case parkDependency: + if len(p.Needs)+len(p.Commits) == 0 || len(p.Files) > 0 { + return fmt.Errorf("parks #%d for a dependency it does not name, or with files", p.Original) + } + default: + return fmt.Errorf("parks #%d as %q, which is no kind of park", p.Original, p.Kind) + } + return nil +} + +// builtFrom is what a classification was made of; batch is the head it +// describes. +type builtFrom struct { + Main string `json:"main"` + Line string `json:"line"` + Newer string `json:"newer"` + Policy string `json:"policy"` + Batch string `json:"batch"` + Tool string `json:"tool"` + Run string `json:"run"` + At string `json:"at"` + Options runOptions `json:"options"` +} + +type runOptions struct { + NoWorkflowFiles bool `json:"noWorkflowFiles"` + Mode string `json:"mode"` +} + +// The operations a record is written by: a run that assembles the batch, and +// the ones that only change what the record says about it. +const ( + modeNew = "new" + modeContinue = "continue" + modeDefer = "defer" + modeDrop = "drop" + modeUndrop = "undrop" + modeClose = "close" +) + +var modes = []string{modeNew, modeContinue, modeDefer, modeDrop, modeUndrop, modeClose} + +// closing is written into the record of an open batch that the run is about +// to close: the head it froze, which the close and the branch's deletion are +// leased on. +type closing struct { + PR int `json:"pr"` + Branch string `json:"branch"` + Head string `json:"head"` +} + +// droppedEntry is a maintainer's decision that an original stays off the +// line, bound to its merge commit on main. +type droppedEntry struct { + Original int `json:"original"` + Merge string `json:"merge"` + Reason string `json:"reason"` + On int `json:"on"` + Date string `json:"date"` +} + +var ( + toolRE = regexp.MustCompile(`^[0-9a-f]{40}(\+dirty)?$`) + reportIDRE = regexp.MustCompile(`^[0-9a-f]{64}$`) +) + +// oneLineText is s as a run writes a reason: one line, cleaned and capped. +// A record holding anything else was not written by a run, and its text +// would reach a terminal, a body or a comment as someone else wrote it. +func oneLineText(s string) string { return capped(oneLine(clean(s, false)), titleLimit) } + +// fencedLines lists the one line of each block that fence opens. +func fencedLines(body, fence string) ([]string, error) { + var blocks []string + lines := strings.Split(strings.ReplaceAll(body, "\r\n", "\n"), "\n") + for i := 0; i < len(lines); i++ { + if strings.TrimSpace(lines[i]) != fence { + continue + } + if i+2 >= len(lines) || strings.TrimSpace(lines[i+2]) != "```" { + return nil, fmt.Errorf("the %s block is not one line of JSON", fence) + } + blocks = append(blocks, lines[i+1]) + i += 2 + } + return blocks, nil +} + +// decodeStrict reads exactly one JSON value into v, refusing a key v does not +// have and anything after the value. +func decodeStrict(data string, v any) error { + dec := json.NewDecoder(strings.NewReader(data)) + dec.DisallowUnknownFields() + if err := dec.Decode(v); err != nil { + return err + } + var rest json.RawMessage + if dec.More() || dec.Decode(&rest) != io.EOF { + return errors.New("something follows the JSON value") + } + return nil +} + +// parseRecord reads the line's record from a batch body: nil when the body +// has no block, an error when it has more than one or one it cannot vouch +// for whole. +func parseRecord(body string, l line) (*lineRecord, error) { + blocks, err := fencedLines(body, deferredFence) + switch { + case err != nil: + return nil, err + case len(blocks) == 0: + return nil, nil + case len(blocks) > 1: + return nil, fmt.Errorf("the body holds %d %s blocks", len(blocks), deferredFence) + } + var head struct { + Version *int `json:"version"` + } + if err := json.Unmarshal([]byte(blocks[0]), &head); err != nil { + return nil, fmt.Errorf("reading the %s block: %w", deferredFence, err) + } + version := 1 + if head.Version != nil { + version = *head.Version + } + var rec lineRecord + switch version { + case 1: + var v1 struct { + Version int `json:"version"` + Line string `json:"line"` + Deferred []deferredEntry `json:"deferred"` + } + err = decodeStrict(blocks[0], &v1) + rec = lineRecord{Version: 1, Line: v1.Line, Deferred: v1.Deferred} + case 2: + var v2 lineRecordV2 + err = decodeStrict(blocks[0], &v2) + rec = lineRecordWithout(v2) + case 3: + err = decodeStrict(blocks[0], &rec) + default: + return nil, fmt.Errorf("the %s block is version %d, which this backport-batch does not read; it reads 1 to %d", deferredFence, version, recordVersion) + } + if err == nil && version < 3 && slices.ContainsFunc(rec.Deferred, func(d deferredEntry) bool { return d.Needs != nil }) { + err = fmt.Errorf("version %d has no waits on other originals", version) + } + if err != nil { + return nil, fmt.Errorf("reading the %s block: %w", deferredFence, err) + } + if err := rec.validate(l); err != nil { + return nil, fmt.Errorf("the %s block %w", deferredFence, err) + } + return &rec, nil +} + +// validate holds the record to what a run writes. Its errors read after +// "the block". +func (rec *lineRecord) validate(l line) error { + if rec.Line != l.branch() { + return fmt.Errorf("is for %q, not %s", rec.Line, l.branch()) + } + seen := map[int]bool{} + once := func(n int) error { + if n <= 0 { + return fmt.Errorf("names original %d", n) + } + if seen[n] { + return fmt.Errorf("names #%d twice", n) + } + seen[n] = true + return nil + } + for _, d := range rec.Deferred { + if err := once(d.Original); err != nil { + return err + } + if d.Commit != "" && checkSHA(d.Commit) != nil { + return fmt.Errorf("names commit %q for #%d", d.Commit, d.Original) + } + // A conflict names the commit that failed and its files, a deferral + // its reason, and a wait its workflow files. + kinds := 0 + for _, is := range []bool{d.Commit != "" || len(d.Files) > 0 && !d.Workflows && d.Reason == "" && len(d.Needs) == 0, d.Reason != "", d.Workflows, len(d.Needs) > 0} { + if is { + kinds++ + } + } + switch { + case d.Workflows && (d.Commit != "" || d.Reason != ""): + return fmt.Errorf("has #%d wait for a maintainer and defers it as well", d.Original) + case kinds != 1: + return fmt.Errorf("does not say whether #%d is a conflict, deferred for a reason or waiting", d.Original) + case d.Reason != "" && strings.TrimSpace(d.Reason) == "": + return fmt.Errorf("defers #%d for an empty reason", d.Original) + case d.Reason != oneLineText(d.Reason): + return fmt.Errorf("defers #%d for %q, which is no reason a run writes", d.Original, d.Reason) + case !slices.Equal(d.Files, cleanFiles(d.Files)): + return fmt.Errorf("names files of #%d that are not as a run writes them: %q", d.Original, d.Files) + case d.More < 0: + return fmt.Errorf("counts %d more files for #%d", d.More, d.Original) + case len(d.Needs) > 0 && (len(d.Files) > 0 || d.More != 0): + return fmt.Errorf("has #%d wait on other originals with files of its own", d.Original) + } + for i, n := range d.Needs { + if n <= 0 || n == d.Original || i > 0 && d.Needs[i-1] >= n { + return fmt.Errorf("has #%d wait on %v, which is not what a run writes", d.Original, d.Needs) + } + } + } + for _, d := range rec.Dropped { + if err := once(d.Original); err != nil { + return err + } + if _, err := time.Parse(time.DateOnly, d.Date); err != nil || checkSHA(d.Merge) != nil || strings.TrimSpace(d.Reason) == "" || d.On <= 0 { + return fmt.Errorf("drops #%d with a merge, reason, pull request or date it cannot have", d.Original) + } + if d.Reason != oneLineText(d.Reason) { + return fmt.Errorf("drops #%d for %q, which is no reason a run writes", d.Original, d.Reason) + } + } + for _, p := range rec.Parked { + if err := once(p.Original); err != nil { + return err + } + if err := p.validate(); err != nil { + return err + } + } + staleSeen := map[int]bool{} + for _, n := range rec.Stale { + if n <= 0 || staleSeen[n] { + return fmt.Errorf("lists %d as still on the batch more than once or not at all", n) + } + staleSeen[n] = true + } + changedSeen := map[int]bool{} + for _, n := range rec.Changed { + if n <= 0 || changedSeen[n] { + return fmt.Errorf("lists %d as a changed pick more than once or not at all", n) + } + changedSeen[n] = true + } + if err := rec.waitsHold(); err != nil { + return err + } + // What is on the batch is neither deferred nor parked. + left := map[int]bool{} + for _, d := range rec.Deferred { + left[d.Original] = true + } + for _, p := range rec.Parked { + left[p.Original] = true + if slices.Contains(p.Commits, p.Merge) { + return fmt.Errorf("parks #%d for its own merge", p.Original) + } + } + for _, list := range [][]int{rec.Partial, rec.Changed} { + for _, n := range list { + if left[n] { + return fmt.Errorf("has #%d on the batch and left off it at once", n) + } + } + } + partialSeen := map[int]bool{} + for _, n := range rec.Partial { + // A unit that does only part of its original is still on the batch. + if !staleSeen[n] || partialSeen[n] { + return fmt.Errorf("lists #%d as a partial unit more than once, or not as still on the batch", n) + } + partialSeen[n] = true + } + if rec.Version < 2 { + return nil + } + if b := rec.Built; b == nil { + return errors.New("does not say what it was built from") + } else if err := b.validate(); err != nil { + return err + } + if !reportIDRE.MatchString(rec.Report) { + return fmt.Errorf("names report %q", rec.Report) + } + if c := rec.Closing; c != nil { + m := batchBranchRE.FindStringSubmatch(c.Branch) + if c.PR <= 0 || m == nil || m[1] != l.branch() || checkSHA(c.Head) != nil { + return fmt.Errorf("closes #%d on %q at %q, which is no batch of %s", c.PR, c.Branch, c.Head, l.branch()) + } + } + return nil +} + +func (b *builtFrom) validate() error { + for _, sha := range []string{b.Main, b.Line, b.Policy, b.Batch} { + if checkSHA(sha) != nil { + return fmt.Errorf("says it was built from %q", sha) + } + } + if b.Newer != "" && checkSHA(b.Newer) != nil { + return fmt.Errorf("says it was built from %q", b.Newer) + } + if b.Tool != "" && !toolRE.MatchString(b.Tool) { + return fmt.Errorf("names tool %q", b.Tool) + } + if b.Run != "" && !runURLRE.MatchString(b.Run) { + return fmt.Errorf("names run %q", b.Run) + } + if _, err := time.Parse(time.RFC3339, b.At); err != nil { + return fmt.Errorf("was built at %q", b.At) + } + if !slices.Contains(modes, b.Options.Mode) { + return fmt.Errorf("was written by %q, which is no operation of backport-batch", b.Options.Mode) + } + return nil +} + +var runURLRE = regexp.MustCompile(`^https://[^/\s]+/[^/\s]+/[^/\s]+/actions/runs/[0-9]+(/attempts/[0-9]+)?$`) + +// waitsHold holds what waits and parks need to what the record says of the +// originals they need: a wait needs ones still to come, so none parked or +// dropped, a park ones that never come, so none deferred, and no wait ends +// up waiting on itself. Its errors read after "the block". +func (rec *lineRecord) waitsHold() error { + deferred, never := map[int][]int{}, map[int]bool{} + for _, d := range rec.Deferred { + deferred[d.Original] = d.Needs + } + for _, p := range rec.Parked { + never[p.Original] = true + } + for _, d := range rec.Dropped { + never[d.Original] = true + } + for _, d := range rec.Deferred { + for _, n := range d.Needs { + if never[n] { + return fmt.Errorf("has #%d wait on #%d, which never comes", d.Original, n) + } + } + } + for _, p := range rec.Parked { + for _, n := range p.Needs { + if _, ok := deferred[n]; ok { + return fmt.Errorf("parks #%d for #%d, which is still to come", p.Original, n) + } + } + } + needs := map[int][]int{} + for _, d := range rec.Deferred { + needs[d.Original] = d.Needs + } + for _, p := range rec.Parked { + needs[p.Original] = p.Needs + } + return waitCycle(needs) +} + +// waitCycle refuses waits that lead back to where they started, which no +// run writes: a prerequisite merged before what needs it. +func waitCycle(needs map[int][]int) error { + state := map[int]int{} // 1 on the path, 2 done + var visit func(n int) error + visit = func(n int) error { + switch state[n] { + case 1: + return fmt.Errorf("has #%d wait on itself through what it waits on", n) + case 2: + return nil + } + state[n] = 1 + for _, f := range needs[n] { + if err := visit(f); err != nil { + return err + } + } + state[n] = 2 + return nil + } + for _, n := range slices.Sorted(maps.Keys(needs)) { + if err := visit(n); err != nil { + return err + } + } + return nil +} + +// lineRecordWithout is a version 2 record as the newest version holds it. +func lineRecordWithout(v2 lineRecordV2) lineRecord { + return lineRecord{Version: v2.Version, Line: v2.Line, Built: v2.Built, Report: v2.Report, Closing: v2.Closing, Deferred: v2.Deferred, Dropped: v2.Dropped, Stale: v2.Stale} +} + +// recordBlock is the block that holds rec. One line of JSON: encoding/json +// escapes newlines and <, > and &, so nothing in a file name or a reason can +// end the fence or open HTML. +func recordBlock(rec lineRecord) string { + data, _ := json.Marshal(rec) + return deferredFence + "\n" + string(data) + "\n```" +} + +// savedNoWorkflowFiles is the --no-workflow-files the open batch was last +// assembled with, which an operation that only changes the record keeps. A +// record from before it was saved says so by listing a wait. +func (s recordSource) savedNoWorkflowFiles() bool { + if !s.open || s.rec == nil { + return false + } + if s.rec.Built != nil { + return s.rec.Built.Options.NoWorkflowFiles + } + return slices.ContainsFunc(s.rec.Deferred, func(d deferredEntry) bool { return d.Workflows }) +} + +// dropped is what the record drops, which every later record keeps. +func (rec *lineRecord) dropped() []droppedEntry { + if rec == nil { + return nil + } + return slices.Clone(rec.Dropped) +} + +// deferred maps the originals the record defers to their entries. +func (rec *lineRecord) deferred() map[int]deferredEntry { + out := map[int]deferredEntry{} + if rec != nil { + for _, d := range rec.Deferred { + out[d.Original] = d + } + } + return out +} + +// recordSource is where a line's record was found. +type recordSource struct { + // carrier is the pull request whose block is the record, nil when the + // line has none. + carrier *pullRequest + // open says the carrier is the open batch, so the record may be written. + open bool + rec *lineRecord + // code is the open batch pull request, if any. One whose body someone + // wrote by hand is the batch the line builds on but carries no record. + code *pullRequest +} + +// closingOpen is the close the record says is under way on a batch that is +// still open, or nil. +func (s recordSource) closingOpen() *closing { + if !s.open || s.rec == nil { + return nil + } + return s.rec.Closing +} + +func prState(pr *pullRequest) string { + switch { + case pr.MergedAt != nil: + return "merged" + case pr.State == "" || pr.State == "open": + return "open" + case pr.State == "closed": + return "closed" + } + return fmt.Sprintf("in state %q", pr.State) +} + +func hasRecord(body string) bool { + return slices.ContainsFunc(strings.Split(body, "\n"), func(ln string) bool { return strings.TrimSpace(ln) == deferredFence }) +} + +// findLineRecord finds the line's record: the block of the newest pull +// request opened from a batch branch of this repository for the line by an +// author the batch trusts, open, merged or closed. open is the open batch +// pull request batchPull chose, or nil. Anything that leaves in doubt which +// record is the newest is an error, never a fall back to an older one: a +// newer block by an author the batch does not trust, a block the bot wrote +// and someone removed, a record it cannot read, a closed record newer than +// the open batch, or more pull requests than it reads. +func findLineRecord(gh github, l line, open *pullRequest) (recordSource, error) { + src := recordSource{code: open} + for page := 1; src.carrier == nil; page++ { + if page > recentPullsPages { + return src, fmt.Errorf("none of the %d newest pull requests against %s is a batch pull request with a record, so the line's record cannot be told apart from none", recentPullsPages*recentPullsPage, l.branch()) + } + prs, err := gh.recentPulls(l.branch(), page) + if err != nil { + return src, err + } + for i := range prs { + pr := &prs[i] + m := batchBranchRE.FindStringSubmatch(pr.Head.Ref) + if m == nil || m[1] != l.branch() || pr.Base.Ref != l.branch() || pr.Head.Repo == nil || pr.Head.Repo.FullName != pr.Base.Repo.FullName { + continue + } + if open != nil && pr.Number == open.Number { + pr = open + } + if !hasRecord(pr.Body) { + if pr.User.Type == "Bot" && gh.batchBot() != "" && pr.User.Login == gh.batchBot() { + return src, fmt.Errorf("batch pull request #%d (%s) was opened by %s but carries no %s block; someone removed it, so the line's record is unknown", pr.Number, prState(pr), pr.User.Login, deferredFence) + } + continue + } + why, err := trusted(gh, *pr) + if err != nil { + return src, fmt.Errorf("batch pull request #%d: %w", pr.Number, err) + } + if why != "" { + return src, fmt.Errorf("batch pull request #%d (%s) carries a %s block but was %s; an older record is not taken in its place", pr.Number, prState(pr), deferredFence, why) + } + rec, err := parseRecord(pr.Body, l) + if err != nil { + return src, fmt.Errorf("batch pull request #%d (%s): %w", pr.Number, prState(pr), err) + } + src.carrier, src.rec = pr, rec + break + } + if len(prs) < recentPullsPage { + break + } + } + switch c := src.carrier; { + case open != nil && hasRecord(open.Body) && (c == nil || c.Number < open.Number): + return src, fmt.Errorf("GitHub does not list the open batch pull request #%d among the pull requests against %s; run again", open.Number, l.branch()) + case open != nil && hasRecord(open.Body) && c.Number > open.Number: + return src, fmt.Errorf("batch pull request #%d (%s) carries a record newer than the open batch pull request #%d; close one of them by hand", c.Number, prState(c), open.Number) + case open != nil && c == open: + src.open = true + case c != nil && prState(c) == "open": + return src, fmt.Errorf("batch pull request #%d carries the line's record and is open, but is not the batch this run builds on", c.Number) + } + return src, nil +} diff --git a/cmd/backport-batch/record_test.go b/cmd/backport-batch/record_test.go new file mode 100644 index 000000000..4bbddc58c --- /dev/null +++ b/cmd/backport-batch/record_test.go @@ -0,0 +1,433 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package main + +import ( + "fmt" + "slices" + "strings" + "testing" +) + +// The records the live batches carried before records had a version, as +// GitHub returned them on 2026-11-09, read as version 1. +func TestRecordReadsVersion1(t *testing.T) { + for line, block := range map[string]string{ + "release-1.7": `{"line":"release-1.7","deferred":[{"original":4756,"commit":"647407545d630291cfe2a20880cce45af22edf0c","files":["packages/system/backupstrategy-controller/values.yaml"]},{"original":4867,"commit":"813c6180861efe1896c26d62a7afcbc1ff590ebc","files":[".github/renovate.json"]},{"original":5082,"commit":"e93db8848027450c2e23d21348409efa641cb6f1","files":["pkg/registry/core/tap/rest.go"]},{"original":4888,"files":[".github/workflows/cut-prerelease.yaml"],"workflows":true},{"original":4971,"files":[".github/workflows/e2e-proxmox.yaml"],"workflows":true}]}`, + "release-1.6": `{"line":"release-1.6","deferred":[{"original":5071,"commit":"3fa534f3cf6cb5774a183f0202f7f5c13e9ae211","files":["internal/operator/tapmaterializer_reconciler.go","internal/operator/tapmaterializer_reconciler_test.go"]},{"original":5086,"commit":"5265ee662c591db409c8ef1ed8bb457cf29f5c22","files":["packages/apps/tenant/templates/gateway.yaml"]},{"original":5087,"commit":"8d8179f20a2c10de03face1472435d5083cde38d","files":["internal/controller/applicationdefinition_helmreconciler.go","internal/controller/applicationdefinition_helmreconciler_test.go"]},{"original":5142,"files":[".github/workflows/pull-requests-release.yaml",".github/workflows/update-releasenotes.yaml"],"workflows":true}]}`, + } { + l, _ := parseLine(line) + rec, err := parseRecord("## What this PR does\n\ntext\n\n"+deferredFence+"\n"+block+"\n```\n\n### Release note\n", l) + if err != nil { + t.Fatalf("%s: parseRecord = %v", line, err) + } + waits, conflicts := 0, 0 + for _, e := range rec.Deferred { + switch { + case e.Workflows: + waits++ + case e.Commit != "": + conflicts++ + } + } + if rec.Version != 1 || rec.Line != line || rec.Closing != nil || len(rec.Dropped) != 0 || waits+conflicts != len(rec.Deferred) || waits == 0 || conflicts == 0 { + t.Errorf("%s: record = %+v; want version 1 with its conflicts and waits", line, rec) + } + } +} + +// v2 is a version 2 record with each value it may hold. +func v2(extra string) string { + sha := strings.Repeat("a", 40) + return `{"version":2,"line":"release-1.1","built":{"main":"` + sha + `","line":"` + sha + `","newer":"","policy":"` + sha + `","batch":"` + sha + `","tool":"` + sha + `+dirty","run":"","at":"2026-10-26T06:00:00Z","options":{"noWorkflowFiles":true,"mode":"continue"}},` + + `"report":"` + strings.Repeat("b", 64) + `","closing":null,"deferred":[{"original":5,"commit":"` + sha + `","files":["app/five.txt"]},{"original":6,"files":[],"reason":"fails the e2e"},{"original":7,"files":[".github/workflows/x.yaml"],"workflows":true}],` + + `"dropped":[{"original":8,"merge":"` + sha + `","reason":"needs #4","on":90,"date":"2026-10-26"}],"stale":[9]` + extra + `}` +} + +// A record is read whole or not at all: anything it cannot vouch for stops +// the command rather than being half believed. +func TestRecordRefuses(t *testing.T) { + l, _ := parseLine("release-1.1") + block := func(json string) string { return "text\n\n" + deferredFence + "\n" + json + "\n```\n" } + if rec, err := parseRecord(block(v2("")), l); err != nil || rec.Version != 2 || len(rec.Dropped) != 1 || rec.Built.Options.Mode != "continue" { + t.Fatalf("parseRecord of a whole v2 record = %+v, %v", rec, err) + } + sha := strings.Repeat("a", 40) + for name, json := range map[string]string{ + "version 4": strings.Replace(v2(""), `"version":2`, `"version":4`, 1), + "trailing data": v2("") + `{}`, + "trailing text": v2("") + ` x`, + "an original listed twice": strings.Replace(v2(""), `"original":8`, `"original":5`, 1), + "a needs entry with a commit": strings.Replace(v2(""), `{"original":6,"files":[],"reason":"fails the e2e"}`, `{"original":6,"commit":"`+sha+`","files":[],"needs":[4]}`, 1), + "an empty reason": strings.Replace(v2(""), `"reason":"fails the e2e"`, `"reason":""`, 1), + "an empty drop reason": strings.Replace(v2(""), `"reason":"needs #4"`, `"reason":" "`, 1), + "a bad tool": strings.Replace(v2(""), `+dirty"`, `-dirty"`, 1), + "an unknown mode": strings.Replace(v2(""), `"mode":"continue"`, `"mode":"rebase"`, 1), + "a reason with a commit": strings.Replace(v2(""), `"reason":"fails the e2e"`, `"reason":"x","commit":"`+sha+`"`, 1), + "a short merge": strings.Replace(v2(""), `"merge":"`+sha+`"`, `"merge":"abc"`, 1), + "a bad date": strings.Replace(v2(""), `"date":"2026-10-26"`, `"date":"26.10.2026"`, 1), + "a bad time": strings.Replace(v2(""), `"at":"2026-10-26T06:00:00Z"`, `"at":"yesterday"`, 1), + "a short report": strings.Replace(v2(""), strings.Repeat("b", 64), "bbbb", 1), + "a closing on another line": strings.Replace(v2(""), `"closing":null`, `"closing":{"pr":90,"branch":"backport-batch/release-1.0-20261026","head":"`+sha+`"}`, 1), + "a closing without a head": strings.Replace(v2(""), `"closing":null`, `"closing":{"pr":90,"branch":"`+batchBranch1+`","head":""}`, 1), + "a negative stale": strings.Replace(v2(""), `"stale":[9]`, `"stale":[-9]`, 1), + "an unknown key": v2(`,"parked":[]`), + "an entry of no kind": strings.Replace(v2(""), `{"original":6,"files":[],"reason":"fails the e2e"}`, `{"original":6,"files":[]}`, 1), + "another line": strings.Replace(v2(""), `"line":"release-1.1"`, `"line":"release-1.0"`, 1), + "an escape in a reason": strings.Replace(v2(""), `"reason":"fails the e2e"`, `"reason":"fails\u001b[2J the e2e"`, 1), + "a newline in a reason": strings.Replace(v2(""), `"reason":"fails the e2e"`, `"reason":"fails\nwarning: forged"`, 1), + "an escape in a drop": strings.Replace(v2(""), `"reason":"needs #4"`, `"reason":"needs\u001b]0;x\u0007 #4"`, 1), + "a newline in a drop": strings.Replace(v2(""), `"reason":"needs #4"`, `"reason":"needs #4\nnote: forged"`, 1), + "a reason past its length": strings.Replace(v2(""), `"reason":"needs #4"`, `"reason":"`+strings.Repeat("x", titleLimit+1)+`"`, 1), + "a bidi file name": strings.Replace(v2(""), `"files":["app/five.txt"]`, `"files":["app/\u202efive.txt"]`, 1), + } { + if _, err := parseRecord(block(json), l); err == nil { + t.Errorf("%s: parseRecord accepted it", name) + } + } + closing := strings.Replace(v2(""), `"closing":null`, `"closing":{"pr":90,"branch":"`+batchBranch1+`","head":"`+sha+`"}`, 1) + if rec, err := parseRecord(block(closing), l); err != nil || rec.Closing == nil || rec.Closing.PR != 90 { + t.Errorf("a record that is closing = %+v, %v", rec, err) + } +} + +// recordPR is a batch pull request on release-1.1 carrying body, numbered n, +// in state, opened by login. +func recordPR(n int, state, login, body string) pullRequest { + pr := notifyPR("20261026", body) + pr.Number, pr.State = n, state + pr.Head.Ref = fmt.Sprintf("backport-batch/release-1.1-202610%02d", n%30+1) + pr.User.Login = login + if strings.HasSuffix(login, "[bot]") { + pr.User.Type = "Bot" + } + return pr +} + +func recordBody(conflict int) string { + return "text\n\n" + deferredFence + "\n" + fmt.Sprintf(`{"line":"release-1.1","deferred":[{"original":%d,"commit":"%s","files":["a"]}]}`, conflict, strings.Repeat("a", 40)) + "\n```\n" +} + +// The record is the block of the newest batch pull request that carries one, +// whatever its state, among those a trusted author opened from a batch branch +// of this repository; anything that leaves the newest record in doubt stops +// the command rather than falling back to an older one. +func TestFindLineRecord(t *testing.T) { + const bot = defaultBatchBot + other := func(n int) pullRequest { + pr := recordPR(n, "closed", "maintainer", "") + pr.Head.Ref = fmt.Sprintf("fix-%d", n) + return pr + } + fork := recordPR(92, "closed", "maintainer", recordBody(92)) + fork.Head.Repo = &struct { + FullName string `json:"full_name"` + }{"someone/cozystack"} + cases := []struct { + name string + prs []pullRequest + open int // the open batch the caller found, or 0 + bot string + carrier int // 0 for none + isOpen bool + refusal string + pages int + }{ + {name: "the open batch first", prs: []pullRequest{recordPR(92, "open", "maintainer", recordBody(92)), recordPR(91, "closed", "maintainer", recordBody(91))}, open: 92, carrier: 92, isOpen: true}, + {name: "the newest closed record", prs: []pullRequest{recordPR(91, "closed", bot, recordBody(91)), recordPR(90, "closed", bot, recordBody(90))}, bot: bot, carrier: 91}, + {name: "a person's batch without a block is passed over", prs: []pullRequest{recordPR(92, "closed", "maintainer", "picked by hand"), recordPR(91, "closed", "maintainer", recordBody(91))}, carrier: 91}, + {name: "the bot's batch without a block", prs: []pullRequest{recordPR(92, "closed", bot, "edited away"), recordPR(91, "closed", bot, recordBody(91))}, bot: bot, refusal: "carries no ```backport-batch block"}, + {name: "a fork is no batch", prs: []pullRequest{fork, recordPR(91, "closed", "maintainer", recordBody(91))}, carrier: 91}, + {name: "a newer record by someone untrusted", prs: []pullRequest{recordPR(92, "closed", "someone", recordBody(92)), recordPR(91, "closed", "maintainer", recordBody(91))}, refusal: "#92"}, + {name: "a closed record newer than the open batch", prs: []pullRequest{recordPR(92, "closed", "maintainer", recordBody(92)), recordPR(91, "open", "maintainer", recordBody(91))}, open: 91, refusal: "newer than the open batch pull request #91"}, + {name: "a record on the second page", prs: append(func() (out []pullRequest) { + for n := 1000; n < 1000+recentPullsPage; n++ { + out = append(out, other(n)) + } + return out + }(), recordPR(91, "closed", "maintainer", recordBody(91))), carrier: 91, pages: 2}, + {name: "ten full pages without a record", prs: func() (out []pullRequest) { + for n := 1000; n < 1000+10*recentPullsPage+1; n++ { + out = append(out, other(n)) + } + return out + }(), refusal: "pull requests", pages: 10}, + {name: "the bot's record when no bot is trusted", prs: []pullRequest{recordPR(91, "closed", bot, recordBody(91))}, refusal: "#91"}, + {name: "a hand-written open batch beside a closed record", prs: []pullRequest{recordPR(92, "open", "maintainer", "picked by hand"), recordPR(91, "closed", "maintainer", recordBody(91))}, open: 92, carrier: 91}, + {name: "no batch ever", prs: []pullRequest{other(5)}}, + {name: "an unreadable record", prs: []pullRequest{recordPR(91, "closed", "maintainer", "text\n\n"+deferredFence+"\n{\n```\n")}, refusal: "#91 (closed)"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + l, _ := parseLine("release-1.1") + gh := &fakeGH{prs: tc.prs, bot: tc.bot} + var open *pullRequest + for i := range tc.prs { + if tc.prs[i].Number == tc.open { + open = &tc.prs[i] + } + } + src, err := findLineRecord(gh, l, open) + switch { + case tc.refusal != "": + if err == nil || !strings.Contains(err.Error(), tc.refusal) { + t.Errorf("findLineRecord = %+v, %v; want a refusal with %q", src, err, tc.refusal) + } + case err != nil: + t.Errorf("findLineRecord: %v", err) + case tc.carrier == 0 && (src.carrier != nil || src.rec != nil): + t.Errorf("found #%d, want no record", src.carrier.Number) + case tc.carrier != 0 && (src.carrier == nil || src.carrier.Number != tc.carrier || src.rec == nil || src.open != tc.isOpen || src.rec.Deferred[0].Original != tc.carrier): + t.Errorf("found %+v, want #%d open=%v", src, tc.carrier, tc.isOpen) + } + if tc.pages != 0 && gh.listed != tc.pages { + t.Errorf("read %d pages, want %d", gh.listed, tc.pages) + } + if tc.open != 0 && src.code != open { + t.Errorf("the batch to build on is %+v, want #%d", src.code, tc.open) + } + }) + } +} + +// A run that picks nothing while no batch is open writes nothing, since +// merged and closed batches are never written: it says its classification is +// not kept, and check still reads the merged batch's record. +func TestZeroPickRunLeavesNoRecord(t *testing.T) { + f := newFixture(t) + f.lines() + f.onLine("release-1.1", "fix(app): a line-only five", map[string]string{"app/five.txt": "line\n", "app/seven.txt": "line\n"}) + f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"}) + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + gh := &fakeGH{} + openBatch(t, f, gh) + mergeBatch(f, gh) + f.pr(7, "fix(app): seven", "", map[string]string{"app/seven.txt": "7\n"}) + edits, comments := len(gh.edited), len(gh.issueComments) + + code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--push") + if code != 0 || !strings.Contains(stderr, "no batch pull request is open on release-1.1; this run's classification is not retained") { + t.Errorf("run = %d, want 0 saying nothing is retained:\n%s", code, stderr) + } + if len(gh.created) != 1 || len(gh.edited) != edits || len(gh.issueComments) != comments || f.remoteHead(batchBranch1) != "" { + t.Errorf("created %q, edited %q, %d comments, branch at %q; want nothing written", gh.created, gh.edited, len(gh.issueComments), f.remoteHead(batchBranch1)) + } + f.git("switch", "-q", "main") + code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1") + if code != 1 || !strings.Contains(stdout, "/pull/7 ") || strings.Contains(stdout, "/pull/5 ") || !strings.Contains(stderr, "deferred conflict on #90 (merged)") { + t.Errorf("check = %d, want 1 for #7 alone and #5 still a deferred conflict:\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr) + } +} + +// The open batch's author is asked for once although both the open batch and +// its record are read. +func TestRecordAsksForAPermissionOnce(t *testing.T) { + f := newFixture(t) + f.lines() + f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"}) + gh := &fakeGH{} + openBatch(t, f, gh) + gh.asked = nil + if code, _, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 0 { + t.Fatalf("check = %d\n%s", code, stderr) + } + if len(gh.asked) != 1 { + t.Errorf("asked GitHub for %q, want the author once", gh.asked) + } +} + +// The record and the report name what the classification was made of: the +// heads it read, the policy, the tool, the job, the time and the flags. +func TestRecordNamesItsInputs(t *testing.T) { + f := newFixture(t) + f.lines() + mc5 := f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"}) + f.onLine("release-1.1", "fix(app): five\n\n(cherry picked from commit "+mc5+")", map[string]string{"app/five.txt": "5\n"}) + f.tool = strings.Repeat("c", 40) + "+dirty" + t.Setenv("GITHUB_SERVER_URL", "https://github.com") + t.Setenv("GITHUB_REPOSITORY", "cozystack/cozystack") + t.Setenv("GITHUB_RUN_ID", "123") + t.Setenv("GITHUB_RUN_ATTEMPT", "2") + gh := &fakeGH{} + stdout := mustRun(t, f, gh, "run", "--line", "release-1.0", "--no-workflow-files", "--push") + l, _ := parseLine("release-1.0") + const branch = "backport-batch/release-1.0-20261026" + rec, err := parseRecord(stdout, l) + if err != nil { + t.Fatal(err) + } + want := builtFrom{Main: f.git("rev-parse", "origin/main"), Line: f.git("rev-parse", "origin/release-1.0"), Newer: f.git("rev-parse", "origin/release-1.1"), + Policy: f.git("rev-parse", "origin/main"), Batch: f.remoteHead(branch), Tool: f.tool, Run: "https://github.com/cozystack/cozystack/actions/runs/123/attempts/2", + At: "2026-10-26T06:00:00Z", Options: runOptions{NoWorkflowFiles: true, Mode: modeNew}} + if rec.Version != recordVersion || *rec.Built != want || bodyReportOf(t, stdout, l).doc.Built != want || rec.Report != bodyReportOf(t, stdout, l).doc.ID { + t.Errorf("record = %+v, built %+v; want built %+v and the report it names", rec, rec.Built, want) + } + + // A policy from another ref, a run by hand that continues the batch. + f.git("push", "-q", "origin", "origin/main:refs/heads/policy-draft") + f.git("fetch", "-q", "origin") + t.Setenv("GITHUB_RUN_ID", "") + gh.prs = []pullRequest{f.batchPR(90, "release-1.0", branch, stdout)} + mc6 := f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + f.onLine("release-1.1", "fix(app): six\n\n(cherry picked from commit "+mc6+")", map[string]string{"app/six.txt": "6\n"}) + stdout = mustRun(t, f, gh, "run", "--line", "release-1.0", "--continue", "--policy", "origin/policy-draft", "--push") + if rec, err = parseRecord(stdout, l); err != nil { + t.Fatal(err) + } + if b := rec.Built; b.Policy != f.git("rev-parse", "origin/policy-draft") || b.Main != f.git("rev-parse", "origin/main") || b.Run != "" || b.Options != (runOptions{Mode: modeContinue}) || b.Batch != f.remoteHead(branch) { + t.Errorf("built %+v; want the draft's policy, no job and a continuation without the flag", b) + } +} + +// What a run assembled with --no-workflow-files stays saved through the +// operations that only change the record, which take no such flag: check +// keeps failing the cut on the wait they leave in place. +func TestMetadataOperationsKeepTheMode(t *testing.T) { + for _, v1 := range []bool{false, true} { + t.Run(fmt.Sprintf("an open record of version 1: %v", v1), func(t *testing.T) { + f := workflowWorld(t) + f.onLine("release-1.1", "fix(app): a line-only nine", map[string]string{"app/nine.txt": "line\n"}) + f.pr(7, "fix(app): seven", "", map[string]string{"app/seven.txt": "7\n"}) + f.pr(8, "fix(app): eight", "", map[string]string{"app/eight.txt": "8\n"}) + f.pr(9, "fix(app): nine", "", map[string]string{"app/nine.txt": "9\n"}) + gh := &fakeGH{} + stdout := mustRun(t, f, gh, "run", "--line", "release-1.1", "--no-workflow-files", "--push") + reopen(f, gh) + if v1 { + waits := []pick{{v: &verdict{o: &original{number: 5}}, files: []string{".github/workflows/five.yaml"}}} + gh.prs[0].Body = strings.Replace(stdout, strings.Split(strings.Split(stdout, deferredFence+"\n")[1], "\n")[0], strings.Split(deferredBlock(notifyLine, nil, nil, waits), "\n")[1], 1) + } else if rec, err := parseRecord(stdout, notifyLine); err != nil || !rec.Built.Options.NoWorkflowFiles { + t.Fatalf("the scheduled run saved %+v, %v", rec, err) + } + for _, op := range []struct { + args []string + mode string + }{ + {[]string{"--drop", "9", "--reason", "needs #4"}, modeDrop}, + {[]string{"--undrop", "9"}, modeUndrop}, + {[]string{"--defer", "7", "--reason", "fails the e2e"}, modeDefer}, + } { + stdout = mustRun(t, f, gh, append(append([]string{"run", "--line", "release-1.1"}, op.args...), "--push")...) + rec, err := parseRecord(stdout, notifyLine) + if err != nil || rec.Built.Options != (runOptions{NoWorkflowFiles: true, Mode: op.mode}) { + t.Errorf("after %q the record is %+v, %v; want the flag kept", op.args, rec.Built, err) + } + reopen(f, gh) + } + var rec *lineRecord + var err error + reopen(f, gh) + if code, stdout, _ := f.exec(gh, "check", "--line", "release-1.1", "--cut"); code != 1 || !strings.Contains(stdout, "#5 changes .github/workflows/") { + t.Errorf("check --cut = %d, want #5 still waiting:\n%s", code, stdout) + } + + // Deferring the last picks closes the batch, and its record + // still says how the batch was assembled. + mustRun(t, f, gh, "run", "--line", "release-1.1", "--defer", "6,8", "--reason", "fails the e2e", "--push") + rec, err = parseRecord(gh.find(90).Body, notifyLine) + if err != nil || gh.find(90).State != "closed" || rec.Closing == nil || rec.Built.Options != (runOptions{NoWorkflowFiles: true, Mode: modeClose}) { + t.Errorf("after the close the record is %+v, %v; want the flag kept", rec.Built, err) + } + if code, stdout, _ := f.exec(gh, "check", "--line", "release-1.1", "--cut"); code != 1 || !strings.Contains(stdout, "/pull/5 ") { + t.Errorf("check --cut = %d, want #5 missing once no batch lists it:\n%s", code, stdout) + } + }) + } +} + +// A state is named only when it is one GitHub uses; anything else is quoted. +func TestPRStateNamesOnlyKnownStates(t *testing.T) { + at := "2026-10-26T12:00:00Z" + for _, tc := range []struct { + pr pullRequest + want string + }{ + {pullRequest{State: "open"}, "open"}, + {pullRequest{State: ""}, "open"}, + {pullRequest{State: "closed"}, "closed"}, + {pullRequest{State: "closed", MergedAt: &at}, "merged"}, + {pullRequest{State: "open\n\x1b[2Jforged"}, `in state "open\n\x1b[2Jforged"`}, + } { + if got := prState(&tc.pr); got != tc.want { + t.Errorf("prState(%q) = %q, want %q", tc.pr.State, got, tc.want) + } + } +} + +// v3 is v2 as version 3, with extra after the stale list. +func v3(extra string) string { + return strings.Replace(v2(extra), `"version":2`, `"version":3`, 1) +} + +// Version 3 adds what is parked and which units do only part of their +// original, each held to what a run writes, and version 2 has neither. +func TestRecordVersion3(t *testing.T) { + l, _ := parseLine("release-1.1") + block := func(json string) string { return "text\n\n" + deferredFence + "\n" + json + "\n```\n" } + sha, other := strings.Repeat("a", 40), strings.Repeat("c", 40) + parked := `,"parked":[{"original":10,"merge":"` + sha + `","kind":"partial","files":["a","b"]},{"original":11,"merge":"` + sha + `","kind":"dependency","needs":[3,4],"commits":["` + other + `"],"announced":true}],"partial":[9]` + waits := strings.Replace(v3(parked), `{"original":6,"files":[],"reason":"fails the e2e"}`, `{"original":6,"files":[],"needs":[3,5]}`, 1) + rec, err := parseRecord(block(waits), l) + if err != nil || rec.Version != 3 || len(rec.Parked) != 2 || !rec.Parked[1].Announced || !slices.Equal(rec.Partial, []int{9}) || !slices.Equal(rec.deferred()[6].Needs, []int{3, 5}) { + t.Fatalf("parseRecord of a whole v3 record = %+v, %v", rec, err) + } + for name, json := range map[string]string{ + "version 1 with a wait": `{"line":"release-1.1","deferred":[{"original":6,"files":[],"needs":[3,5]}]}`, + "a wait with files": strings.Replace(waits, `"files":[],"needs":[3,5]`, `"files":["a"],"needs":[3,5]`, 1), + "a wait that is a conflict": strings.Replace(waits, `"files":[],"needs":[3,5]`, `"commit":"`+sha+`","files":[],"needs":[3,5]`, 1), + "a wait on itself": strings.Replace(waits, `"needs":[3,5]`, `"needs":[3,6]`, 1), + "an unsorted wait": strings.Replace(waits, `"needs":[3,5]`, `"needs":[5,3]`, 1), + "a wait on nothing": strings.Replace(waits, `"needs":[3,5]`, `"needs":[0]`, 1), + "a wait cycle": strings.Replace(strings.Replace(waits, `"needs":[3,5]`, `"needs":[12]`, 1), `"deferred":[`, `"deferred":[{"original":12,"files":[],"needs":[6]},`, 1), + "a wait on a parked one": strings.Replace(waits, `"needs":[3,5]`, `"needs":[10]`, 1), + "a wait on a dropped one": strings.Replace(waits, `"needs":[3,5]`, `"needs":[8]`, 1), + "a park on a deferred one": strings.Replace(waits, `"needs":[3,4]`, `"needs":[3,5]`, 1), + "a partial unit also deferred": strings.Replace(strings.Replace(waits, `"stale":[9]`, `"stale":[9,5]`, 1), `"partial":[9]`, `"partial":[9,5]`, 1), + "a changed pick also parked": v3(parked + `,"changed":[10]`), + "a changed pick also deferred": v3(parked + `,"changed":[5]`), + "a park on its own merge": strings.Replace(waits, `"commits":["`+other+`"]`, `"commits":["`+sha+`"]`, 1), + "a park cycle": strings.Replace(strings.Replace(waits, `"needs":[3,4]`, `"needs":[3,13]`, 1), `"parked":[`, `"parked":[{"original":13,"merge":"`+sha+`","kind":"dependency","needs":[11]},`, 1), + } { + if _, err := parseRecord(block(json), l); err == nil { + t.Errorf("%s: parseRecord accepted it", name) + } + } + for name, json := range map[string]string{ + "version 2 with a park": v2(parked), + "version 4": strings.Replace(v3(""), `"version":3`, `"version":4`, 1), + "a park of a deferred original": v3(strings.Replace(parked, `"original":10`, `"original":5`, 1)), + "a park of a dropped original": v3(strings.Replace(parked, `"original":10`, `"original":8`, 1)), + "a partial park with no files": v3(strings.Replace(parked, `"files":["a","b"]`, `"files":[]`, 1)), + "a partial park that needs": v3(strings.Replace(parked, `"files":["a","b"]`, `"files":["a"],"needs":[3]`, 1)), + "unsorted files": v3(strings.Replace(parked, `"files":["a","b"]`, `"files":["b","a"]`, 1)), + "a file that drives a terminal": v3(strings.Replace(parked, `"files":["a","b"]`, `"files":["a\u001b[2J"]`, 1)), + "a dependency park with no need": v3(strings.Replace(strings.Replace(parked, `"needs":[3,4],`, ``, 1), `"commits":["`+other+`"],`, ``, 1)), + "unsorted needs": v3(strings.Replace(parked, `"needs":[3,4]`, `"needs":[4,3]`, 1)), + "a park that needs itself": v3(strings.Replace(parked, `"needs":[3,4]`, `"needs":[3,11]`, 1)), + "a short commit": v3(strings.Replace(parked, `"commits":["`+other+`"]`, `"commits":["abc"]`, 1)), + "a short merge": v3(strings.Replace(parked, `"merge":"`+sha+`","kind":"partial"`, `"merge":"abc","kind":"partial"`, 1)), + "an unknown kind": v3(strings.Replace(parked, `"kind":"partial"`, `"kind":"later"`, 1)), + "a partial unit not on the batch": v3(strings.Replace(parked, `"partial":[9]`, `"partial":[10]`, 1)), + "a partial unit twice": v3(strings.Replace(parked, `"partial":[9]`, `"partial":[9,9]`, 1)), + "a changed pick twice": v3(parked + `,"changed":[4,4]`), + "a changed pick that is none": v3(parked + `,"changed":[0]`), + } { + if _, err := parseRecord(block(json), l); err == nil { + t.Errorf("%s: parseRecord accepted it", name) + } + } +} diff --git a/cmd/backport-batch/report.go b/cmd/backport-batch/report.go new file mode 100644 index 000000000..27fd8860c --- /dev/null +++ b/cmd/backport-batch/report.go @@ -0,0 +1,885 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package main + +import ( + "cmp" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "maps" + "os" + "regexp" + "runtime/debug" + "slices" + "strconv" + "strings" + "time" +) + +// A report is one classification of a line: where every original merged into +// main since the line branched stands, and what it was made of. The batch +// pull request's body carries the latest one beside the record, and an issue +// comment the tool never edits keeps each one, so a later run that replaces +// the body loses none of them. Its ID hashes the classification, not the pull +// request it lands on, which a new batch does not have yet when the report is +// made. + +const ( + reportFence = "```backport-batch-report" + reportMarker = "\n" + + "
Backport batch report for " + s.doc.Line + ", " + date + " (" + s.doc.ID[:12] + ")\n\n" + + reportBlock(s.raw) + "\n
\n" + if len(c) > reportLimit { + return "", fmt.Errorf("the report comment is %d bytes, over the %d it may have", len(c), reportLimit) + } + return c, nil +} + +var reportMarkerRE = regexp.MustCompile(`^` + regexp.QuoteMeta(reportMarker) + `([0-9a-f]{64}) -->\n`) + +// findReports reads the report comments on batch pull request n, against l, +// by authors the batch trusts, as it trusts a record's author, by ID. One +// whose content does not match the ID its marker gives, or is not what a run +// writes, is returned apart, with why; a look-alike by anyone else is not +// read, whatever it says. +func findReports(gh github, n int, l line) (map[string]storedReport, map[string]string, error) { + comments, err := gh.comments(n) + if err != nil { + return nil, nil, err + } + found, bad := map[string]storedReport{}, map[string]string{} + for _, c := range comments { + if !strings.HasPrefix(c.Body, reportMarker) { + continue + } + why, err := trustedAuthor(gh, c.User.Login, c.User.Type) + if err != nil { + return nil, nil, err + } + if why != "" { + continue + } + m := reportMarkerRE.FindStringSubmatch(c.Body) + if m == nil { + bad[strconv.FormatInt(c.ID, 10)] = fmt.Sprintf("comment %d starts like a report but names none", c.ID) + continue + } + blocks, err := fencedLines(c.Body, reportFence) + if err == nil && len(blocks) != 1 { + err = fmt.Errorf("it holds %d reports", len(blocks)) + } + var doc reportDoc + if err == nil { + doc, err = parseReport(blocks[0], l) + } + if err == nil && doc.ID != m[1] { + err = fmt.Errorf("its marker names %.12s", m[1]) + } + if err != nil { + bad[m[1]] = fmt.Sprintf("comment %d: %v", c.ID, err) + continue + } + found[m[1]] = storedReport{doc: doc, raw: blocks[0]} + } + return found, bad, nil +} + +// toolVersion is the commit this binary was built from, with +dirty when its +// tree had changes, or "" when the build did not record it, as go run does +// not. +func toolVersion() string { + info, ok := debug.ReadBuildInfo() + if !ok { + return "" + } + rev, dirty := "", false + for _, s := range info.Settings { + switch s.Key { + case "vcs.revision": + rev = s.Value + case "vcs.modified": + dirty = s.Value == "true" + } + } + if checkSHA(rev) != nil { + return "" + } + if dirty { + rev += "+dirty" + } + return rev +} + +// runURL is the Actions run the command runs in, from the variables GitHub +// sets for it, or "" outside one. +func runURL(lookup func(string) (string, bool)) string { + get := func(key string) string { v, _ := lookup(key); return v } + url := get("GITHUB_SERVER_URL") + "/" + get("GITHUB_REPOSITORY") + "/actions/runs/" + get("GITHUB_RUN_ID") + if attempt := get("GITHUB_RUN_ATTEMPT"); attempt != "" && attempt != "1" { + url += "/attempts/" + attempt + } + if !runURLRE.MatchString(url) { + return "" + } + return url +} + +// report prints a report a batch pull request keeps, writing nothing, so it +// works on merged and closed batches too. It reads GitHub, and for a report +// that keeps drops also this clone's history at the heads the report was +// made from, which it never fetches. +func (a *app) report(args []string) int { + fs := a.flags("report") + number := fs.Int("pr", 0, "the batch pull request") + id := fs.String("id", "", "the report, by its ID (default: the one the body carries)") + asJSON := fs.Bool("json", false, "print the report's JSON") + if err := parse(fs, args); err != nil { + return 2 + } + if *number <= 0 { + return a.fail(fmt.Errorf("--pr %d is not a pull request number", *number)) + } + if *id != "" && !reportIDRE.MatchString(*id) { + return a.fail(fmt.Errorf("--id %q is not a report ID", *id)) + } + pr, err := a.gh.pull(*number) + if err != nil { + return a.fail(err) + } + l, err := parseLine(pr.Base.Ref) + if m := batchBranchRE.FindStringSubmatch(pr.Head.Ref); err != nil || m == nil || m[1] != l.branch() || pr.Head.Repo == nil || pr.Head.Repo.FullName != pr.Base.Repo.FullName { + return a.fail(fmt.Errorf("#%d is not a batch pull request of this repository", pr.Number)) + } + why, err := trusted(a.gh, pr) + if err != nil { + return a.fail(err) + } + if why != "" { + return a.fail(fmt.Errorf("batch pull request #%d was %s, so what it says is not the batch's", pr.Number, why)) + } + inBody, err := bodyReport(pr.Body, l) + if err != nil { + return a.fail(fmt.Errorf("batch pull request #%d: %w", pr.Number, err)) + } + if *id == "" { + if inBody == nil { + return a.fail(fmt.Errorf("batch pull request #%d carries no report in its body; name one with --id", pr.Number)) + } + *id = inBody.doc.ID + } + posted, bad, err := findReports(a.gh, pr.Number, l) + if err != nil { + return a.fail(err) + } + if why := bad[*id]; why != "" { + return a.fail(fmt.Errorf("batch pull request #%d: the report %.12s is not what its comment says: %s", pr.Number, *id, why)) + } + s, inComment := posted[*id] + switch { + case inComment: + case inBody != nil && inBody.doc.ID == *id: + s = *inBody + default: + return a.fail(fmt.Errorf("batch pull request #%d keeps no report %.12s", pr.Number, *id)) + } + if *asJSON { + _, _ = fmt.Fprintln(a.stdout, s.raw) + return 0 + } + a.printReport(&pr, s, inBody, inComment) + return 0 +} + +// printReport prints a report. It was checked when it was read, and every +// field still goes through terminalSafe, so nothing it carries spans lines +// or drives a terminal. +func (a *app) printReport(pr *pullRequest, s storedReport, inBody *storedReport, inComment bool) { + d, b := s.doc, s.doc.Built + safe := terminalSafe + _, _ = fmt.Fprintf(a.stdout, "report %s for %s, made %s by a %s run", safe(d.ID), safe(d.Line), safe(b.At), safe(b.Options.Mode)) + if b.Options.NoWorkflowFiles { + _, _ = fmt.Fprint(a.stdout, " with --no-workflow-files") + } + _, _ = fmt.Fprintln(a.stdout) + _, _ = fmt.Fprintf(a.stdout, " main %s, line %s, newer line %s, policy %s\n batch %s, tool %s, run %s\n", safe(b.Main), safe(b.Line), safe(or(b.Newer, "none")), safe(b.Policy), safe(b.Batch), safe(or(b.Tool, "unknown")), safe(or(b.Run, "none"))) + current := "none" + if inBody != nil { + current = safe(inBody.doc.ID) + } + switch { + case inBody != nil && inBody.doc.ID == d.ID: + _, _ = fmt.Fprintf(a.stdout, " #%d's body carries this report\n", pr.Number) + case pr.Head.SHA == b.Batch: + _, _ = fmt.Fprintf(a.stdout, " #%d's head is %.12s, the batch this report describes, but its body carries report %.12s\n", pr.Number, safe(b.Batch), current) + default: + _, _ = fmt.Fprintf(a.stdout, " publication unconfirmed: #%d's head is %.12s, not %.12s, and its body carries report %.12s\n", pr.Number, safe(pr.Head.SHA), safe(b.Batch), current) + } + if !inComment { + if prState(pr) == "open" { + _, _ = fmt.Fprintln(a.stdout, " comment not posted; the next backport-batch run --push posts it") + } else { + _, _ = fmt.Fprintf(a.stdout, " comment not posted; kept in the body only, since nothing is written to a %s pull request\n", prState(pr)) + } + } + type line struct { + n int + text string + } + var lines []line + for _, n := range d.Primary.Picked { + lines = append(lines, line{n, "picked"}) + } + for _, n := range d.Primary.Missing { + lines = append(lines, line{n, "missing"}) + } + for _, e := range d.Primary.Deferred { + text := "deferred: " + switch { + case e.Workflows: + text += "waits for a maintainer, changes " + strings.Join(e.Files, ", ") + case len(e.Needs) > 0: + var needs []string + for _, n := range e.Needs { + needs = append(needs, "#"+strconv.Itoa(n)) + } + text += "waits on " + strings.Join(needs, ", ") + case e.Reason != "": + text += e.Reason + default: + text += fmt.Sprintf("conflict at %.12s in %s", e.Commit, strings.Join(e.Files, ", ")) + } + if e.More > 0 { + text += fmt.Sprintf(" and %d more", e.More) + } + lines = append(lines, line{e.Original, text}) + } + for _, e := range d.Primary.Parked { + text := "parked: " + switch e.Kind { + case parkPartial: + text += "only part of it applies, it would leave " + strings.Join(e.Files, ", ") + " without effect" + default: + var needs []string + for _, n := range e.Needs { + needs = append(needs, "#"+strconv.Itoa(n)) + } + for _, c := range e.Commits { + needs = append(needs, c[:12]) + } + text += "builds on " + strings.Join(needs, ", ") + ", which never reaches the line" + } + lines = append(lines, line{e.Original, text}) + } + for _, l := range d.Primary.Skipped.lists() { + for _, n := range *l.list { + lines = append(lines, line{n, "skipped." + l.name}) + } + } + slices.SortFunc(lines, func(x, y line) int { return cmp.Compare(x.n, y.n) }) + for _, l := range lines { + _, _ = fmt.Fprintf(a.stdout, "#%d %s\n", l.n, terminalSafe(l.text)) + } + overlay := func(name string, list []int) { + if len(list) > 0 { + _, _ = fmt.Fprintf(a.stdout, "%s: %s\n", name, strings.Trim(fmt.Sprint(list), "[]")) + } + } + overlay("stale, still on the batch", d.Overlays.Stale) + overlay("only part of it applies, still on the batch", d.Overlays.Partial) + for _, e := range d.Overlays.Dropped { + _, _ = fmt.Fprintf(a.stdout, "dropped: #%d, merged as %.12s, on #%d: %s\n", e.Original, terminalSafe(e.Merge), e.On, terminalSafe(e.Reason)) + } + overlay("changed in the pick", d.Overlays.Changed) + for _, n := range slices.Sorted(maps.Keys(d.Diag)) { + for _, ln := range d.Diag[n] { + _, _ = fmt.Fprintf(a.stdout, "#%s: %s\n", terminalSafe(n), terminalSafe(ln)) + } + } + if len(d.Other) > 0 { + other := make([]string, len(d.Other)) + for i, sha := range d.Other { + other[i] = safe(sha) + } + _, _ = fmt.Fprintf(a.stdout, "commits on main that merged no pull request: %s\n", strings.Join(other, ", ")) + } +} + +func or(s, otherwise string) string { + if s == "" { + return otherwise + } + return s +} + +// postReport writes a report comment on pull request n, after GitHub says +// it is still open: nothing is written to a merged or closed one. +func (a *app) postReport(n int, s storedReport) error { + if err := a.stillOpen(n); err != nil { + return err + } + c, err := reportComment(s) + if err != nil { + return err + } + name, err := writeTemp("backport-batch-report-*.md", c) + if err != nil { + return err + } + defer func() { _ = os.Remove(name) }() + return a.gh.createComment(n, name) +} + +// stillOpen reads pull request n again and refuses to go on unless it is +// open. +func (a *app) stillOpen(n int) error { + pr, err := a.gh.pull(n) + if err != nil { + return err + } + if st := prState(&pr); st != "open" { + return fmt.Errorf("batch pull request #%d is %s now; nothing is written to it", n, st) + } + return nil +} + +func writeTemp(pattern, content string) (string, error) { + f, err := os.CreateTemp("", pattern) + if err != nil { + return "", err + } + if _, err := f.WriteString(content); err != nil { + _ = f.Close() + _ = os.Remove(f.Name()) + return "", err + } + if err := f.Close(); err != nil { + _ = os.Remove(f.Name()) + return "", err + } + return f.Name(), nil +} diff --git a/cmd/backport-batch/report_test.go b/cmd/backport-batch/report_test.go new file mode 100644 index 000000000..754b599bb --- /dev/null +++ b/cmd/backport-batch/report_test.go @@ -0,0 +1,780 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package main + +import ( + "fmt" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" + "unicode" +) + +// reportsPosted lists the report IDs the comments carry, in the order they +// were posted, whoever wrote them. +func reportsPosted(gh *fakeGH) []string { + var ids []string + for _, c := range gh.issueComments { + if m := reportMarkerRE.FindStringSubmatch(c.Body); m != nil { + ids = append(ids, m[1]) + } + } + return ids +} + +// bodyReportOf is the report a body on release-1.1, or on the line given, +// carries, failing the test without one. +func bodyReportOf(t *testing.T, body string, on ...line) storedReport { + t.Helper() + l := notifyLine + if len(on) > 0 { + l = on[0] + } + s, err := bodyReport(body, l) + if err != nil || s == nil { + t.Fatalf("the body carries no readable report: %v\n%s", err, body) + } + return *s +} + +// refusePushes makes the remote refuse every push, as a lost connection or +// a protected branch would, until it is called with false. +func (f *fixture) refusePushes(on bool) { + f.t.Helper() + hook := filepath.Join(f.remote, "hooks", "pre-receive") + if !on { + if err := os.Remove(hook); err != nil { + f.t.Fatal(err) + } + return + } + if err := os.WriteFile(hook, []byte("#!/bin/sh\necho refused >&2\nexit 1\n"), 0o755); err != nil { + f.t.Fatal(err) + } +} + +func mustRun(t *testing.T, f *fixture, gh *fakeGH, args ...string) string { + t.Helper() + code, stdout, stderr := f.exec(gh, args...) + if code != 0 { + t.Fatalf("%q = %d\n%s", args, code, stderr) + } + f.git("switch", "-q", "main") + return stdout +} + +// A report comment keeps each classification: one the next run replaced in +// the body is still read back by its ID, also once the batch merged, which +// nothing writes to. +func TestReportSurvivesContinuation(t *testing.T) { + f := newFixture(t) + f.lines() + f.onLine("release-1.1", "fix(app): a line-only five", map[string]string{"app/five.txt": "line\n"}) + mc5 := f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"}) + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + gh := &fakeGH{} + openBatch(t, f, gh) + r1 := bodyReportOf(t, gh.prs[0].Body).doc.ID + f.onLine("release-1.1", "fix(app): five, by hand\n\n(cherry picked from commit "+mc5+")", map[string]string{"app/five.txt": "5\n"}) + f.now = f.now.AddDate(0, 0, 1) + mustRun(t, f, gh, "run", "--line", "release-1.1", "--continue", "--push") + r2 := bodyReportOf(t, gh.find(90).Body).doc.ID + if r1 == r2 || !slices.Equal(reportsPosted(gh), []string{r1, r2}) { + t.Fatalf("reports %q; want R1 %.12s, then R2 %.12s", reportsPosted(gh), r1, r2) + } + read := func(id, want string) { + t.Helper() + code, stdout, stderr := f.exec(gh, "report", "--pr", "90", "--id", id) + if code != 0 || !strings.Contains(stdout, want) { + t.Errorf("report --id %.12s = %d, want %q:\n%s%s", id, code, want, stdout, stderr) + } + } + for _, merged := range []bool{false, true} { + if merged { + mergeBatch(f, gh) + } + read(r1, "#5 deferred: conflict at ") + read(r2, "#5 skipped.on-line") + read(r2, "#6 picked") + } +} + +// Two runs that find the same post one report, and the body carries the one +// kept, whatever time and job the second ran in. A look-alike someone else +// wrote is no report, and a kept report edited since stops the reader. +func TestReportDedupAndTrust(t *testing.T) { + f := newFixture(t) + f.lines() + f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"}) + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + gh := &fakeGH{} + openBatch(t, f, gh) + t.Setenv("GITHUB_SERVER_URL", "https://github.com") + t.Setenv("GITHUB_REPOSITORY", "cozystack/cozystack") + t.Setenv("GITHUB_RUN_ID", "100") + t.Setenv("GITHUB_RUN_ATTEMPT", "1") + + // The report the next run makes, read off a run that publishes nothing, + // planted by someone the batch does not trust. + preview := bodyReportOf(t, mustRun(t, f, gh, "run", "--line", "release-1.1", "--continue")) + planted, err := reportComment(preview) + if err != nil { + t.Fatal(err) + } + look := issueComment{ID: 7, Body: planted} + look.User.Login, look.User.Type = "someone", "User" + gh.issueComments = append(gh.issueComments, look) + + f.now = f.now.AddDate(0, 0, 1) + mustRun(t, f, gh, "run", "--line", "release-1.1", "--continue", "--push") + kept := bodyReportOf(t, gh.find(90).Body) + if kept.doc.ID != preview.doc.ID { + t.Fatalf("the run made %.12s, the preview %.12s", kept.doc.ID, preview.doc.ID) + } + f.now = f.now.AddDate(0, 0, 1) + t.Setenv("GITHUB_RUN_ID", "101") + mustRun(t, f, gh, "run", "--line", "release-1.1", "--continue", "--push") + posted := reportsPosted(gh) + if n := len(slices.DeleteFunc(slices.Clone(posted), func(id string) bool { return id != kept.doc.ID })); n != 2 || len(posted) != 3 { + t.Errorf("reports %q; want the first, the look-alike and the run's own once", posted) + } + body := gh.find(90).Body + again := bodyReportOf(t, body) + rec, err := parseRecord(body, notifyLine) + if err != nil || again.raw != kept.raw || rec.Report != again.doc.ID || !strings.Contains(again.raw, `"run":"https://github.com/cozystack/cozystack/actions/runs/100"`) { + t.Errorf("the second run's body carries %s with record report %v (%v); want the kept bytes of run 100", again.raw, rec, err) + } + + // The reader takes the run's own comment, not the look-alike. + if code, stdout, stderr := f.exec(gh, "report", "--pr", "90", "--id", kept.doc.ID); code != 0 || !strings.Contains(stdout, "#6 picked") { + t.Errorf("report = %d:\n%s%s", code, stdout, stderr) + } + for i := range gh.issueComments { + c := &gh.issueComments[i] + if c.User.Login == "maintainer" && strings.Contains(c.Body, kept.doc.ID) { + c.Body = strings.Replace(c.Body, `"picked":[5,6]`, `"picked":[5]`, 1) + } + } + if code, stdout, stderr := f.exec(gh, "report", "--pr", "90", "--id", kept.doc.ID); code != 2 || !strings.Contains(stderr, "does not match") { + t.Errorf("report of an edited comment = %d, want 2:\n%s%s", code, stdout, stderr) + } +} + +// The report holds no pull request number, so a new batch's report is whole +// before GitHub numbers the pull request, and the reader finds it on +// whatever number it got. +func TestFirstReportIDIsKnownBeforeTheNumber(t *testing.T) { + f := newFixture(t) + f.lines() + f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"}) + gh := &fakeGH{nextPR: 4242} + mustRun(t, f, gh, "run", "--line", "release-1.1", "--push") + inBody := bodyReportOf(t, gh.bodies[0]) + // Every list is one, empty or not, so equal reports are equal bytes: + // main here has no commit that merged no pull request. + if !strings.Contains(inBody.raw, `"other":[]`) { + t.Errorf("the report writes its empty list of other commits as something else:\n%s", inBody.raw) + } + if !slices.Equal(gh.commented, []int{4242}) || !slices.Equal(reportsPosted(gh), []string{inBody.doc.ID}) { + t.Fatalf("commented on %v with %q, want #4242 with %.12s", gh.commented, reportsPosted(gh), inBody.doc.ID) + } + found, bad, err := findReports(gh, 4242, notifyLine) + if err != nil || len(bad) != 0 || found[inBody.doc.ID].raw != inBody.raw { + t.Errorf("findReports = %v, %v, %v; want the body's report", found, bad, err) + } + if code, stdout, stderr := f.exec(gh, "report", "--pr", "4242"); code != 0 || !strings.Contains(stdout, "report "+inBody.doc.ID) || !strings.Contains(stdout, "#4242's body carries this report") { + t.Errorf("report --pr 4242 = %d:\n%s%s", code, stdout, stderr) + } +} + +// Every original main merged since the line branched is in exactly one +// category of the report, a commit that merged no pull request is counted +// apart, and the report says so whatever the run had to do. +func TestReportPartition(t *testing.T) { + f := newFixture(t) + f.lines() + gh := &fakeGH{labels: map[string][]int{labelSkip: {9}}} + // onNewer puts an original on release-1.1, as the newer line's batch + // would, so rule 6 lets it onto release-1.0. + onNewer := func(mc string, files map[string]string) { + f.onLine("release-1.1", "fix: by the newer batch\n\n(cherry picked from commit "+mc+")", files) + } + pr := func(n int, title string, files map[string]string, newer bool) { + mc := f.pr(n, title, "", files) + if newer { + onNewer(mc, files) + } + } + t.Setenv("GIT_COMMITTER_DATE", "2026-01-01T00:00:00Z") + f.pr(4, "fix(app): four, before the start", "", map[string]string{"app/four.txt": "4\n"}) + if err := os.Unsetenv("GIT_COMMITTER_DATE"); err != nil { + t.Fatal(err) + } + f.setPolicy("release-1.0: 2026-06-01\n") + f.onLine("release-1.0", "fix(app): a line-only eleven", map[string]string{"app/eleven.txt": "line\n"}) + pr(5, "fix(app): five", map[string]string{"app/five.txt": "5\n"}, true) + pr(6, "fix(app): six, not on the newer line", map[string]string{"app/six.txt": "6\n"}, false) + pr(7, "fix(app)!: seven", map[string]string{"app/seven.txt": "7\n"}, true) + pr(8, "fix(platform): eight", map[string]string{migrationsDir + "42": "#!/bin/sh\n"}, true) + pr(9, "fix(app): nine", map[string]string{"app/nine.txt": "9\n"}, true) + mc10 := f.pr(10, "fix(app): ten", "", map[string]string{"app/ten.txt": "10\n"}) + onNewer(mc10, map[string]string{"app/ten.txt": "10\n"}) + f.onLine("release-1.0", "fix(app): ten\n\n(cherry picked from commit "+mc10+")", map[string]string{"app/ten.txt": "10\n"}) + pr(11, "fix(app): eleven", map[string]string{"app/eleven.txt": "11\n"}, true) + pr(12, "fix(ci): twelve", map[string]string{".github/workflows/twelve.yaml": "on: push\n"}, true) + pr(13, "fix(app): thirteen", map[string]string{"app/thirteen.txt": "13\n"}, true) + f.git("switch", "-q", "main") + f.write("app/direct.txt", "pushed\n") + f.git("add", "-A") + f.git("commit", "-q", "-m", "chore: a direct push") + direct := f.git("rev-parse", "HEAD") + f.git("push", "-q", "origin", "main") + + stdout := mustRun(t, f, gh, "run", "--line", "release-1.0", "--no-workflow-files", "--push") + const branch = "backport-batch/release-1.0-20261026" + gh.prs = []pullRequest{f.batchPR(90, "release-1.0", branch, stdout)} + pr(14, "fix(app): fourteen, after the batch", map[string]string{"app/fourteen.txt": "14\n"}, true) + stdout = mustRun(t, f, gh, "run", "--line", "release-1.0", "--defer", "13", "--reason", "fails the e2e", "--push") + // An active drop, of #5, which the batch carries, and one of a feat, + // which rule 2 keeps out first. + gh.prs = []pullRequest{f.batchPR(90, "release-1.0", branch, stdout)} + stdout = mustRun(t, f, gh, "run", "--line", "release-1.0", "--drop", "5,1", "--reason", "not for 1.0", "--push") + + l, _ := parseLine("release-1.0") + s := bodyReportOf(t, stdout, l) + got, err := s.doc.categories() + if err != nil { + t.Fatal(err) + } + want := map[int]string{1: "skipped.type", 4: "skipped.before-start", 5: "skipped.dropped", 6: "skipped.newer", 7: "skipped.breaking", + 8: "skipped.touches", 9: "skipped.skip-label", 10: "skipped.on-line", 11: "deferred", 12: "deferred", 13: "deferred", + 14: "missing", 9000: "skipped.type"} + for n, category := range want { + if got[n] != category { + t.Errorf("#%d is %q, want %q", n, got[n], category) + } + delete(got, n) + } + if len(got) != 0 { + t.Errorf("the report also names %v", got) + } + if gh.find(90).State != "closed" || !strings.Contains(stdout, `"mode":"close"`) { + t.Errorf("dropping the batch's last pick left #90 %s; want it closed", gh.find(90).State) + } + if !slices.Equal(droppedNumbers(s.doc.Overlays.Dropped), []int{1, 5}) || len(s.doc.Primary.Picked) != 0 { + t.Errorf("the report drops %v and picks %v; want #1 and #5 dropped, nothing picked", s.doc.Overlays.Dropped, s.doc.Primary.Picked) + } + if !slices.Contains(s.doc.Other, direct) { + t.Errorf("the report does not count the direct push %.12s: %v", direct, s.doc.Other) + } + kinds := map[int]string{} + for _, e := range s.doc.Primary.Deferred { + kinds[e.Original] = fmt.Sprintf("commit=%v reason=%q workflows=%v", e.Commit != "", e.Reason, e.Workflows) + } + if kinds[11] != `commit=true reason="" workflows=false` || kinds[12] != `commit=false reason="" workflows=true` || kinds[13] != `commit=false reason="fails the e2e" workflows=false` { + t.Errorf("the deferred entries are %v", kinds) + } +} + +// A report too big for a comment is refused before anything is written: no +// push, no comment, no edit, and no replay of the earlier report either. +func TestReportTooLargeIsRefusedBeforePush(t *testing.T) { + f, gh, head := bigWaits(t, 7) + code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--no-workflow-files", "--push") + if code != 2 || !strings.Contains(stderr, "the report comment is") { + t.Errorf("run --push = %d, want a refusal of the report:\n%s", code, stderr) + } + if f.remoteHead(batchBranch1) != head || len(gh.issueComments) != 0 || len(gh.edited) != 0 { + t.Errorf("the refused run moved the batch to %.12s, wrote %d comments and edited %q", f.remoteHead(batchBranch1), len(gh.issueComments), gh.edited) + } +} + +// bigWaits opens a batch whose report comment failed, so its body keeps a +// report no comment does, and then merges n originals that each wait on 50 +// workflow files with long names, which both the record and the report list +// in full. +func bigWaits(t *testing.T, n int) (*fixture, *fakeGH, string) { + t.Helper() + f := newFixture(t) + f.lines() + f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"}) + gh := &fakeGH{fail: map[string]error{"createComment": errString("HTTP 502")}} + if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--no-workflow-files", "--push"); code != 2 || len(gh.created) != 1 { + t.Fatalf("the first run = %d, want its comment to fail after the pull request opened\n%s", code, stderr) + } + f.git("switch", "-q", "main") + for i := range n { + files := map[string]string{} + for j := range filesKept { + files[fmt.Sprintf(".github/workflows/%s-%02d-%02d.yaml", strings.Repeat("w", 170), i, j)] = "on: push\n" + } + f.pr(10+i, fmt.Sprintf("fix(ci): wait %d", i), "", files) + } + f.now = f.now.AddDate(0, 0, 1) + return f, gh, f.remoteHead(batchBranch1) +} + +// A failure between any two writes leaves what was written readable, and the +// next run, whatever changed meanwhile, replays a report the body kept but no +// comment did, byte for byte, and posts nothing twice. A batch closed in +// between is never written again. +func TestReportReplayAfterEachFailure(t *testing.T) { + setup := func(t *testing.T) (*fixture, *fakeGH) { + f := newFixture(t) + f.lines() + f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"}) + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + return f, &fakeGH{} + } + // change moves a label, main, the clock and the run's flags between + // the failure and the retry, so the retry's report is another one. + change := func(f *fixture, gh *fakeGH) []string { + gh.labels = map[string][]int{labelSkip: {6}} + f.pr(7, "fix(app): seven", "", map[string]string{"app/seven.txt": "7\n"}) + f.now = f.now.AddDate(0, 0, 1) + return []string{"run", "--line", "release-1.1", "--continue", "--no-workflow-files", "--push"} + } + once := func(t *testing.T, gh *fakeGH, ids ...string) { + t.Helper() + posted := reportsPosted(gh) + for _, id := range ids { + if n := len(slices.DeleteFunc(slices.Clone(posted), func(p string) bool { return p != id })); n != 1 { + t.Errorf("report %.12s is posted %d times: %q", id, n, posted) + } + } + } + + t.Run("a new batch whose pull request was not opened", func(t *testing.T) { + f, gh := setup(t) + gh.fail = map[string]error{"createPull": errString("HTTP 502")} + if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--push"); code != 2 { + t.Fatalf("run = %d\n%s", code, stderr) + } + f.git("switch", "-q", "main") + if len(gh.prs) != 0 || len(gh.issueComments) != 0 || f.remoteHead(batchBranch1) == "" { + t.Errorf("after the failure: %d pull requests, %d comments, branch %q; want the branch alone", len(gh.prs), len(gh.issueComments), f.remoteHead(batchBranch1)) + } + mustRun(t, f, gh, change(f, gh)...) + if len(gh.prs) != 1 || len(reportsPosted(gh)) != 1 || bodyReportOf(t, gh.prs[0].Body).doc.ID != reportsPosted(gh)[0] { + t.Errorf("the retry opened %d pull requests with reports %q", len(gh.prs), reportsPosted(gh)) + } + }) + t.Run("a new batch whose report comment failed", func(t *testing.T) { + f, gh := setup(t) + gh.fail = map[string]error{"createComment": errString("HTTP 502")} + if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--push"); code != 2 || !strings.Contains(stderr, "the body keeps it") { + t.Fatalf("run = %d\n%s", code, stderr) + } + f.git("switch", "-q", "main") + first := bodyReportOf(t, gh.find(90).Body) + mustRun(t, f, gh, change(f, gh)...) + second := bodyReportOf(t, gh.find(90).Body) + want, err := reportComment(first) + if err != nil || len(gh.issueComments) != 2 || gh.issueComments[0].Body != want || reportsPosted(gh)[1] != second.doc.ID || first.doc.ID == second.doc.ID { + t.Errorf("comments %q; want the first report replayed as it was, then the retry's", reportsPosted(gh)) + } + }) + t.Run("a continuation whose push failed", func(t *testing.T) { + f, gh := setup(t) + openBatch(t, f, gh) + first := reportsPosted(gh)[0] + f.pr(8, "fix(app): eight", "", map[string]string{"app/eight.txt": "8\n"}) + f.refusePushes(true) + if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--push"); code != 2 { + t.Fatalf("run = %d\n%s", code, stderr) + } + f.git("switch", "-q", "main") + f.refusePushes(false) + attempted := reportsPosted(gh)[1] + if bodyReportOf(t, gh.find(90).Body).doc.ID != first { + t.Error("the body moved on although the push failed") + } + mustRun(t, f, gh, change(f, gh)...) + once(t, gh, first, attempted) + if len(reportsPosted(gh)) != 3 { + t.Errorf("reports %q; want the first, the attempted and the retry's", reportsPosted(gh)) + } + }) + t.Run("a continuation whose body edit failed", func(t *testing.T) { + f, gh := setup(t) + openBatch(t, f, gh) + first := reportsPosted(gh)[0] + before := f.remoteHead(batchBranch1) + f.pr(8, "fix(app): eight", "", map[string]string{"app/eight.txt": "8\n"}) + gh.fail = map[string]error{"editPull": errString("HTTP 502")} + if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--push"); code != 2 { + t.Fatalf("run = %d\n%s", code, stderr) + } + f.git("switch", "-q", "main") + attempted := reportsPosted(gh)[1] + if f.remoteHead(batchBranch1) == before || bodyReportOf(t, gh.find(90).Body).doc.ID != first { + t.Error("the push or the body is not where the failure left them") + } + mustRun(t, f, gh, change(f, gh)...) + once(t, gh, first, attempted) + if last := reportsPosted(gh)[len(reportsPosted(gh))-1]; bodyReportOf(t, gh.find(90).Body).doc.ID != last || len(reportsPosted(gh)) != 3 { + t.Errorf("reports %q; want the body to carry the retry's, posted last", reportsPosted(gh)) + } + }) + t.Run("a batch closed while the run writes to it", func(t *testing.T) { + f, gh := setup(t) + openBatch(t, f, gh) + f.pr(8, "fix(app): eight", "", map[string]string{"app/eight.txt": "8\n"}) + gh.after = map[string]func(){"createComment": func() { gh.find(90).State = "closed" }} + code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--push") + if code != 2 || !strings.Contains(stderr, "batch pull request #90 is closed now; nothing is written to it") || len(gh.edited) != 0 { + t.Errorf("run = %d, edited %q; want 2 and no edit of the closed pull request:\n%s", code, gh.edited, stderr) + } + }) + t.Run("a batch closed before its report was posted", func(t *testing.T) { + f, gh := setup(t) + gh.fail = map[string]error{"createComment": errString("HTTP 502")} + if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--push"); code != 2 { + t.Fatalf("run = %d\n%s", code, stderr) + } + f.git("switch", "-q", "main") + kept := bodyReportOf(t, gh.find(90).Body) + gh.find(90).State = "closed" + gh.nextPR = 91 + mustRun(t, f, gh, change(f, gh)...) + if slices.Contains(gh.commented, 90) || slices.Contains(reportsPosted(gh), kept.doc.ID) { + t.Errorf("commented on %v, posting %q; want nothing on the closed #90", gh.commented, reportsPosted(gh)) + } + code, stdout, stderr := f.exec(gh, "report", "--pr", "90") + if code != 0 || !strings.Contains(stdout, "report "+kept.doc.ID) || !strings.Contains(stdout, "kept in the body only") { + t.Errorf("report --pr 90 = %d:\n%s%s", code, stdout, stderr) + } + }) + // Every comment is posted only after GitHub says the batch is still + // open, the replay's included, so a close between the two stops the + // second. + t.Run("a batch closed between the replay and the new report", func(t *testing.T) { + f, gh := setup(t) + gh.fail = map[string]error{"createComment": errString("HTTP 502")} + if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--push"); code != 2 { + t.Fatalf("run = %d\n%s", code, stderr) + } + f.git("switch", "-q", "main") + kept := bodyReportOf(t, gh.find(90).Body) + f.pr(8, "fix(app): eight", "", map[string]string{"app/eight.txt": "8\n"}) + gh.after = map[string]func(){"createComment": func() { gh.find(90).State = "closed" }} + code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--push") + if code != 2 || !strings.Contains(stderr, "batch pull request #90 is closed now; nothing is written to it") || !slices.Equal(reportsPosted(gh), []string{kept.doc.ID}) || len(gh.edited) != 0 { + t.Errorf("run = %d, posted %q, edited %q; want 2 after the replay alone:\n%s", code, reportsPosted(gh), gh.edited, stderr) + } + }) +} + +// The reader says how a report stands against the pull request as GitHub +// shows it now, and claims publication only when the head or the body shows +// it: a failed push, a push whose answer was lost, a body that was not +// updated and a rebuild since all read as they are. +func TestReportPublicationStatus(t *testing.T) { + setup := func(t *testing.T) (*fixture, *fakeGH, string) { + f := newFixture(t) + f.lines() + f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"}) + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + gh := &fakeGH{} + openBatch(t, f, gh) + return f, gh, reportsPosted(gh)[0] + } + status := func(t *testing.T, f *fixture, gh *fakeGH, id, want string) { + t.Helper() + code, stdout, stderr := f.exec(gh, "report", "--pr", "90", "--id", id) + if code != 0 || !strings.Contains(stdout, want) { + t.Errorf("report --id %.12s = %d, want %q:\n%s%s", id, code, want, stdout, stderr) + } + } + t.Run("a push the remote refused, and one it took whose answer was lost", func(t *testing.T) { + f, gh, first := setup(t) + f.pr(7, "fix(app): seven", "", map[string]string{"app/seven.txt": "7\n"}) + f.refusePushes(true) + if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--push"); code != 2 { + t.Fatalf("run = %d\n%s", code, stderr) + } + f.refusePushes(false) + attempted := reportsPosted(gh)[1] + status(t, f, gh, attempted, "publication unconfirmed: #90's head is ") + status(t, f, gh, attempted, "its body carries report "+first[:12]) + // The same head reaching the remote is what a push GitHub took looks + // like when its answer never came back. + f.git("push", "-q", "origin", "HEAD:refs/heads/"+batchBranch1) + f.git("switch", "-q", "main") + status(t, f, gh, attempted, "the batch this report describes, but its body carries report "+first[:12]) + }) + t.Run("a push followed by a failed body edit", func(t *testing.T) { + f, gh, first := setup(t) + f.pr(7, "fix(app): seven", "", map[string]string{"app/seven.txt": "7\n"}) + gh.fail = map[string]error{"editPull": errString("HTTP 502")} + if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--push"); code != 2 { + t.Fatalf("run = %d\n%s", code, stderr) + } + f.git("switch", "-q", "main") + status(t, f, gh, reportsPosted(gh)[1], "the batch this report describes, but its body carries report "+first[:12]) + status(t, f, gh, first, "#90's body carries this report") + }) + t.Run("a rebuild since", func(t *testing.T) { + f, gh, first := setup(t) + mustRun(t, f, gh, "run", "--line", "release-1.1", "--defer", "6", "--reason", "x", "--push") + second := reportsPosted(gh)[1] + status(t, f, gh, first, "publication unconfirmed: #90's head is ") + status(t, f, gh, second, "#90's body carries this report") + }) +} + +// forged is a report on release-1.1 with what change sets, under an ID that +// matches it: only checking what it says stands in its way. +func forged(change func(d *reportDoc)) storedReport { + sha := strings.Repeat("a", 40) + d := reportDoc{Format: reportFormat, Line: "release-1.1", Diag: map[string][]string{}, Other: []string{sha}, + Built: builtFrom{Main: sha, Line: sha, Policy: sha, Batch: sha, At: "2026-10-26T06:00:00Z", Options: runOptions{Mode: modeNew}}} + d.Primary.Picked = []int{5} + change(&d) + d.ID = reportID(d) + return storedReport{doc: d, raw: reportJSON(d)} +} + +// reportRun runs report with gh faked; it reads nothing but GitHub. +func reportRun(gh *fakeGH, args ...string) (int, string, string) { + var stdout, stderr strings.Builder + a := &app{gh: gh, stdout: &stdout, stderr: &stderr, now: func() time.Time { return time.Date(2026, 10, 26, 6, 0, 0, 0, time.UTC) }} + code := a.main(append([]string{"report"}, args...)) + return code, stdout.String(), stderr.String() +} + +// A report is read only when everything it says is what a run writes, and +// it is for the line of the pull request it sits on: an ID that matches its +// content proves only that nobody changed it since it was hashed. +func TestReportRefusesWhatItCannotVouchFor(t *testing.T) { + for name, change := range map[string]func(d *reportDoc){ + "a line that is no release line": func(d *reportDoc) { d.Line = "release-1.1\n\x1b[2Jpicked" }, + "another line": func(d *reportDoc) { d.Line = "release-1.0" }, + "a main that is no commit": func(d *reportDoc) { d.Built.Main = "main\n#5 picked" }, + "a time that is none": func(d *reportDoc) { d.Built.At = "2026-10-26T" }, + "an unknown operation": func(d *reportDoc) { d.Built.Options.Mode = "new\x1b[2J" }, + "a run that is no Actions run": func(d *reportDoc) { d.Built.Run = "javascript:alert(1)" }, + "a tool that is no commit": func(d *reportDoc) { d.Built.Tool = "v1\n" }, + "a commit on main that is none": func(d *reportDoc) { d.Other = []string{"HEAD\x1b]0;x\x07"} }, + "a deferred commit that is none": func(d *reportDoc) { + d.Primary.Deferred = []deferredEntry{{Original: 6, Commit: "-x", Files: []string{"a"}}} + }, + "an original named twice": func(d *reportDoc) { d.Primary.Missing = []int{5} }, + "an original that is none": func(d *reportDoc) { d.Primary.Skipped.Type = []int{-1} }, + "a diagnostic of two lines": func(d *reportDoc) { d.Diag = map[string][]string{"5": {"incomplete\n\x1b[2Jforged"}} }, + "a diagnostic of no original": func(d *reportDoc) { d.Diag = map[string][]string{"five": {"incomplete"}} }, + // Fields that speak of one another have to agree. + "a drop category with no drop": func(d *reportDoc) { d.Primary.Skipped.Dropped = []int{6} }, + "a stale original it has missing": func(d *reportDoc) { + d.Primary.Missing, d.Overlays.Stale = []int{7}, []int{7} + }, + "a stale original it puts nowhere": func(d *reportDoc) { d.Overlays.Stale = []int{8} }, + "a changed original it defers": func(d *reportDoc) { + d.Primary.Deferred = []deferredEntry{{Original: 9, Files: []string{}, Reason: "fails the e2e"}} + d.Overlays.Changed = []int{9} + }, + "a skip label on a picked original": func(d *reportDoc) { d.Overrides.Skip = []int{5} }, + "a skip-label category with no label": func(d *reportDoc) { d.Primary.Skipped.SkipLabel = []int{10} }, + "an include label on a rule 2 skip": func(d *reportDoc) { + d.Primary.Skipped.Type, d.Overrides.Include = []int{11}, []int{11} + }, + "both labels on one original": func(d *reportDoc) { + d.Primary.Skipped.SkipLabel, d.Overrides.Include, d.Overrides.Skip = []int{12}, []int{12}, []int{12} + }, + "a label on no original": func(d *reportDoc) { d.Overrides.Include = []int{13} }, + "a diagnostic of an original it puts nowhere": func(d *reportDoc) { d.Diag = map[string][]string{"14": {"incomplete"}} }, + "a workflow wait without the flag": func(d *reportDoc) { + d.Primary.Deferred = []deferredEntry{{Original: 15, Files: []string{".github/workflows/ci.yaml"}, Workflows: true}} + }, + "a close that still picks": func(d *reportDoc) { d.Built.Options.Mode = modeClose }, + "a park with no merge": func(d *reportDoc) { + d.Primary.Parked = []parkedEntry{{Original: 16, Kind: parkPartial, Files: []string{"a"}}} + }, + "a parked original it picks": func(d *reportDoc) { + d.Primary.Parked = []parkedEntry{{Original: 5, Merge: strings.Repeat("b", 40), Kind: parkPartial, Files: []string{"a"}}} + }, + "a park of an unknown kind": func(d *reportDoc) { + d.Primary.Parked = []parkedEntry{{Original: 16, Merge: strings.Repeat("b", 40), Kind: "later", Files: []string{"a"}}} + }, + "a partial park that needs an original": func(d *reportDoc) { + d.Primary.Parked = []parkedEntry{{Original: 16, Merge: strings.Repeat("b", 40), Kind: parkPartial, Files: []string{"a"}, Needs: []int{5}}} + }, + "a partial park of unsorted files": func(d *reportDoc) { + d.Primary.Parked = []parkedEntry{{Original: 16, Merge: strings.Repeat("b", 40), Kind: parkPartial, Files: []string{"b", "a"}}} + }, + "a partial park of a file that drives a terminal": func(d *reportDoc) { + d.Primary.Parked = []parkedEntry{{Original: 16, Merge: strings.Repeat("b", 40), Kind: parkPartial, Files: []string{"a\x1b[2J"}}} + }, + "a park announced in the report": func(d *reportDoc) { + d.Primary.Parked = []parkedEntry{{Original: 16, Merge: strings.Repeat("b", 40), Kind: parkPartial, Files: []string{"a"}, Announced: true}} + }, + "a park for an original it picks": func(d *reportDoc) { + d.Primary.Parked = []parkedEntry{{Original: 16, Merge: strings.Repeat("b", 40), Kind: parkDependency, Needs: []int{5}}} + }, + "a park that needs itself": func(d *reportDoc) { + d.Primary.Skipped.Type = []int{17} + d.Primary.Parked = []parkedEntry{{Original: 16, Merge: strings.Repeat("b", 40), Kind: parkDependency, Needs: []int{16, 17}}} + }, + "a park for a commit that merged a pull request": func(d *reportDoc) { + d.Primary.Parked = []parkedEntry{{Original: 16, Merge: strings.Repeat("b", 40), Kind: parkDependency, Commits: []string{strings.Repeat("c", 40)}}} + }, + "a partial unit not on the batch": func(d *reportDoc) { d.Overlays.Partial = []int{5} }, + "a wait on an original it picks": func(d *reportDoc) { + d.Primary.Deferred = []deferredEntry{{Original: 6, Files: []string{}, Needs: []int{5}}} + }, + "a wait on an original it puts nowhere": func(d *reportDoc) { + d.Primary.Deferred = []deferredEntry{{Original: 6, Files: []string{}, Needs: []int{19}}} + }, + "a park on its own merge as a commit": func(d *reportDoc) { + d.Other = append(d.Other, strings.Repeat("b", 40)) + d.Primary.Parked = []parkedEntry{{Original: 16, Merge: strings.Repeat("b", 40), Kind: parkDependency, Commits: []string{strings.Repeat("b", 40)}}} + }, + "a park cycle": func(d *reportDoc) { + d.Primary.Parked = []parkedEntry{{Original: 16, Merge: strings.Repeat("b", 40), Kind: parkDependency, Needs: []int{18}}, {Original: 18, Merge: strings.Repeat("b", 40), Kind: parkDependency, Needs: []int{16}}} + }, + "a wait cycle": func(d *reportDoc) { + d.Primary.Deferred = []deferredEntry{{Original: 6, Files: []string{}, Needs: []int{7}}, {Original: 7, Files: []string{}, Needs: []int{6}}} + }, + "format 1 with a wait": func(d *reportDoc) { + d.Format = 1 + d.Primary.Missing = []int{19} + d.Primary.Deferred = []deferredEntry{{Original: 6, Files: []string{}, Needs: []int{19}}} + }, + "format 1 with a park": func(d *reportDoc) { + d.Format = 1 + d.Primary.Parked = []parkedEntry{{Original: 16, Merge: strings.Repeat("b", 40), Kind: parkPartial, Files: []string{"a"}}} + }, + } { + s := forged(change) + c, _ := reportComment(storedReport{doc: forged(func(*reportDoc) {}).doc, raw: s.raw}) + comment := issueComment{ID: 1, Body: strings.Replace(c, forged(func(*reportDoc) {}).doc.ID, s.doc.ID, 1)} + comment.User.Login, comment.User.Type = "maintainer", "User" + for where, gh := range map[string]*fakeGH{ + "in the body": {prs: []pullRequest{notifyPR("20261026", "text\n\n"+reportBlock(s.raw)+"\n")}}, + "in a comment": {prs: []pullRequest{notifyPR("20261026", "text")}, issueComments: []issueComment{comment}}, + } { + if code, stdout, stderr := reportRun(gh, "--pr", "90", "--id", s.doc.ID); code != 2 || stdout != "" { + t.Errorf("%s, %s: report = %d, want 2 and nothing printed:\n%s%s", name, where, code, stdout, stderr) + } + } + } + if code, stdout, stderr := reportRun(&fakeGH{prs: []pullRequest{notifyPR("20261026", "text\n\n"+reportBlock(forged(func(*reportDoc) {}).raw)+"\n")}}, "--pr", "90"); code != 0 || !strings.Contains(stdout, "#5 picked") { + t.Errorf("report of a sound one = %d:\n%s%s", code, stdout, stderr) + } + // What a run wrote before anything was parked reads as it was written. + format1 := forged(func(d *reportDoc) { d.Format, d.Primary.Parked = 1, []parkedEntry{} }) + if code, stdout, stderr := reportRun(&fakeGH{prs: []pullRequest{notifyPR("20261026", "text\n\n"+reportBlock(format1.raw)+"\n")}}, "--pr", "90"); code != 0 || !strings.Contains(stdout, "#5 picked") { + t.Errorf("report of a sound format 1 one = %d:\n%s%s", code, stdout, stderr) + } + parked := forged(func(d *reportDoc) { + d.Primary.Skipped.Type = []int{17} + d.Other = append(d.Other, strings.Repeat("c", 40)) + d.Primary.Parked = []parkedEntry{ + {Original: 16, Merge: strings.Repeat("b", 40), Kind: parkPartial, Files: []string{"chart/templates/policy.yaml"}}, + {Original: 18, Merge: strings.Repeat("b", 40), Kind: parkDependency, Needs: []int{16, 17}, Commits: []string{strings.Repeat("c", 40)}}, + } + }) + if code, stdout, stderr := reportRun(&fakeGH{prs: []pullRequest{notifyPR("20261026", "text\n\n"+reportBlock(parked.raw)+"\n")}}, "--pr", "90"); code != 0 || !strings.Contains(stdout, "#16 parked: only part of it applies") || !strings.Contains(stdout, "#18 parked: builds on #16, #17, cccccccccccc") { + t.Errorf("report of sound parks = %d:\n%s%s", code, stdout, stderr) + } +} + +// What report prints stays one line per field and carries nothing a +// terminal acts on, whatever reached it. +func TestReportPrintsNothingThatDrivesATerminal(t *testing.T) { + const evil = "\n\x1b[2Jfake: #9 picked\u202e" + s := forged(func(d *reportDoc) { + d.Line, d.Built.At, d.Built.Options.Mode = "release-1.1"+evil, "2026-10-26"+evil, "new"+evil + d.Built.Main, d.Built.Tool, d.Built.Run, d.Built.Newer = "main"+evil, "tool"+evil, "run"+evil, "newer"+evil + d.Other = []string{"other" + evil} + d.Primary.Deferred = []deferredEntry{{Original: 6, Reason: "why" + evil}} + }) + var stdout strings.Builder + a := &app{stdout: &stdout} + pr := notifyPR("20261026", "") + a.printReport(&pr, s, nil, true) + for _, ln := range strings.Split(stdout.String(), "\n") { + if strings.HasPrefix(ln, "fake") || strings.ContainsFunc(ln, func(r rune) bool { return r != '\t' && unicode.IsControl(r) || unicode.Is(unicode.Cf, r) }) { + t.Errorf("report printed %q", ln) + } + } +} + +// The comment is made of what was checked: a line, a time and an ID that +// carry no markup into the summary GitHub renders. +func TestReportCommentIsBuiltFromCheckedFields(t *testing.T) { + for name, change := range map[string]func(d *reportDoc){ + "markup in the line": func(d *reportDoc) { d.Line = "release-1.1" }, + "markup in the time": func(d *reportDoc) { d.Built.At = "2026-10-26T06:00:00Z" }, + "a mention": func(d *reportDoc) { d.Line = "release-1.1 @cozystack/maintainers" }, + } { + if c, err := reportComment(forged(change)); err == nil { + t.Errorf("%s: reportComment made\n%s", name, c) + } + } + if _, err := reportComment(forged(func(*reportDoc) {})); err != nil { + t.Errorf("reportComment of a sound report: %v", err) + } +} + +// Anyone can comment on a public pull request: the reader takes a report +// from a comment only when the batch trusts its author, whatever ID it +// carries. +func TestReportReaderTakesOnlyTrustedComments(t *testing.T) { + s := forged(func(*reportDoc) {}) + c, err := reportComment(s) + if err != nil { + t.Fatal(err) + } + for _, tc := range []struct { + login, kind string + read bool + }{ + {"someone", "User", false}, + {"renovate[bot]", "Bot", false}, + {"github-actions[bot]", "Bot", false}, + {"maintainer", "User", true}, + {defaultBatchBot, "Bot", true}, + } { + comment := issueComment{ID: 1, Body: c} + comment.User.Login, comment.User.Type = tc.login, tc.kind + gh := &fakeGH{prs: []pullRequest{notifyPR("20261026", "text")}, issueComments: []issueComment{comment}, bot: defaultBatchBot} + code, stdout, stderr := reportRun(gh, "--pr", "90", "--id", s.doc.ID) + if read := code == 0 && strings.Contains(stdout, "#5 picked"); read != tc.read || !tc.read && (code != 2 || !strings.Contains(stderr, "keeps no report")) { + t.Errorf("a report by %s: report = %d, read %v, want %v:\n%s%s", tc.login, code, read, tc.read, stdout, stderr) + } + } +} + +// A report whose ID is not one says so without repeating it as written. +func TestReportErrorsRepeatNothingRaw(t *testing.T) { + s := forged(func(*reportDoc) {}) + // Short enough that a cut to 12 characters keeps the forged line. + raw := strings.Replace(s.raw, `"id":"`+s.doc.ID+`"`, `"id":"\nforged"`, 1) + code, _, stderr := reportRun(&fakeGH{prs: []pullRequest{notifyPR("20261026", "text\n\n"+reportBlock(raw)+"\n")}}, "--pr", "90") + for _, ln := range strings.Split(stderr, "\n") { + if strings.HasPrefix(ln, "forged") { + t.Errorf("report = %d, printed the forged line %q", code, ln) + } + } + if code != 2 { + t.Errorf("report = %d, want 2:\n%s", code, stderr) + } +} diff --git a/cmd/backport-batch/rules.go b/cmd/backport-batch/rules.go new file mode 100644 index 000000000..e7aa2740a --- /dev/null +++ b/cmd/backport-batch/rules.go @@ -0,0 +1,344 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package main + +import ( + "fmt" + "maps" + "path/filepath" + "regexp" + "slices" + "strings" + + "sigs.k8s.io/yaml" +) + +// Rule numbers as docs/release/backports.md numbers them. Rule 5, a clean +// pick, is decided while the batch is assembled. +const ( + ruleOnLine = 1 + ruleType = 2 + ruleBreaking = 3 + ruleTouches = 4 + ruleNewer = 6 + // Not a rule of the policy: the backport/skip override. + ruleSkipLabel = 100 + // Rule 1 for a line that started under the policy after it branched: + // merged before that start. + ruleBeforeStart = 101 + // Not a rule of the policy: a maintainer dropped the original from the + // line with run --drop. + ruleDropped = 102 +) + +const ( + // The numbered scripts run-migrations.sh walks; hack/check-migrations-target.sh + // reads the same directory. + migrationsDir = "packages/core/platform/images/migrations/migrations/" + // Where migrations.targetVersion is set; hack/check-migrations-target.sh + // reads it from here. + platformValues = "packages/core/platform/values.yaml" + // Only a file holding this text at either end of the change can hold a + // CRD document; crdDocs decides document by document. + crdKind = "CustomResourceDefinition" +) + +// The title grammar and the breaking footer are pr-labeler.yaml's, so that a +// pull request labelled kind/bug and kind/breaking-change reads the same here. +var ( + backportPrefixRE = regexp.MustCompile(`^(?:\[Backport [^\]]+\]\s+)+`) + conventionalRE = regexp.MustCompile(`^([a-z]+)(?:\(([^)]+)\))?(!)?:\s*\S`) + breakingFooterRE = regexp.MustCompile(`(?m)^BREAKING[ -]CHANGE:`) + htmlCommentRE = regexp.MustCompile(`(?s)`) + targetVersionRE = regexp.MustCompile(`(?m)^[+-][ \t]*targetVersion[ \t]*:`) +) + +// title is a parsed Conventional Commits title. +type title struct { + typ string + scopes []string + bang bool +} + +func parseTitle(s string) (title, bool) { + m := conventionalRE.FindStringSubmatch(backportPrefixRE.ReplaceAllString(s, "")) + if m == nil { + return title{}, false + } + t := title{typ: m[1], bang: m[3] == "!"} + for scope := range strings.SplitSeq(m[2], ",") { + if scope = strings.TrimSpace(scope); scope != "" { + t.scopes = append(t.scopes, scope) + } + } + return t, true +} + +// typeRule is rule 2 together with the policy's "never in a patch release": +// dependency bumps, scope deps, stay out whatever their type. +func typeRule(s string) string { + t, ok := parseTitle(s) + switch { + case !ok: + return "the title is not a Conventional Commits title" + case !slices.Contains(takenTypes, t.typ): + return "type " + t.typ + case slices.ContainsFunc(t.scopes, func(s string) bool { return slices.Contains(excludedScopes, s) }): + return "an excluded scope" + } + return "" +} + +// breakingRule is rule 3. The PR template quotes the footer inside an HTML +// comment, which a body merged with the template left in carries. +func breakingRule(s, body string) string { + if t, ok := parseTitle(s); ok && t.bang { + return "! in the title" + } + if breakingFooterRE.MatchString(htmlCommentRE.ReplaceAllString(body, "")) { + return "BREAKING CHANGE footer" + } + return "" +} + +// fileChange is one path a merge changes against its first parent. +type fileChange struct { + status byte + path string +} + +func changedFiles(from, to string) ([]fileChange, error) { + out, err := git("diff", "--no-ext-diff", "--no-textconv", "--name-status", "-z", "--no-renames", "--end-of-options", from, to) + if err != nil { + return nil, err + } + f := splitNUL(out) + if len(f)%2 != 0 { + return nil, fmt.Errorf("unreadable diff of %s..%s", from, to) + } + var changes []fileChange + for i := 0; i < len(f); i += 2 { + changes = append(changes, fileChange{status: f[i][0], path: f[i+1]}) + } + return changes, nil +} + +func paths(changes []fileChange) []string { + out := make([]string, 0, len(changes)) + for _, c := range changes { + out = append(out, c.path) + } + return out +} + +const ( + touchesMigrations = "platform migrations" + touchesTargetVersion = "targetVersion" + touchesAPI = "a sizeable API change" + touchesCRD = "a CRD" +) + +// touchesRule is rule 4: what of migrations, targetVersion, the API and CRDs +// the merge touches, or "" when it touches none of them. +func touchesRule(o *original, changes []fileChange) (string, error) { + hit := map[string]bool{} + for _, c := range changes { + p := c.path + switch { + case strings.HasPrefix(p, migrationsDir): + hit[touchesMigrations] = true + case p == platformValues: + diff, err := git("--literal-pathspecs", "diff", "-U0", "--no-ext-diff", "--no-textconv", "--end-of-options", o.merge+"^1", o.merge, "--", platformValues) + if err != nil { + return "", err + } + hit[touchesTargetVersion] = targetVersionRE.MatchString(diff) + } + } + var err error + if hit[touchesCRD], err = changesCRD(o.merge+"^1", o.merge, changes); err != nil { + return "", err + } + asks, err := readsAPI(o.merge+"^1", o.merge, changes) + if err != nil { + return "", err + } + apiDetail := "" + if asks { + if apiDetail, err = sizeableAPIChange(o); err != nil { + return "", err + } + hit[touchesAPI] = apiDetail != "" + } + var why []string + for _, r := range []string{touchesMigrations, touchesTargetVersion, touchesAPI, touchesCRD} { + switch { + case !hit[r]: + case r == touchesAPI: + why = append(why, r+" ("+apiDetail+")") + default: + why = append(why, r) + } + } + return strings.Join(why, ", "), nil +} + +// changesCRD reports whether the change adds, removes or modifies a +// CustomResourceDefinition document. It looks document by document: an edit to +// the DaemonSet beside a CRD in one manifest is not a CRD change, and a CRD in +// a test fixture changes nothing a cluster runs. +func changesCRD(parent, merge string, changes []fileChange) (bool, error) { + var files []string + for _, c := range changes { + if manifest(c.path) && !testFixture(c.path) { + files = append(files, c.path) + } + } + candidates := map[string]bool{} + for _, rev := range []string{parent, merge} { + found, err := grepFiles(rev, files, "-I", "-e", crdKind) + if err != nil { + return false, err + } + for _, f := range found { + candidates[f] = true + } + } + for _, c := range changes { + if !candidates[c.path] { + continue + } + var before, after map[string]string + if c.status != 'A' { + content, err := git("cat-file", "blob", parent+":"+c.path) + if err != nil { + return false, err + } + before = crdDocs(content) + } + if c.status != 'D' { + content, err := git("cat-file", "blob", merge+":"+c.path) + if err != nil { + return false, err + } + after = crdDocs(content) + } + if !maps.Equal(before, after) { + return true, nil + } + } + return false, nil +} + +// manifest reports whether path is a file a chart or a cluster can apply: YAML, +// JSON or a Helm template. A CRD quoted in documentation or code applies +// nothing. +func manifest(path string) bool { + switch filepath.Ext(path) { + case ".yaml", ".yml", ".json", ".tpl": + return true + } + dirs := strings.Split(path, "/") + return slices.ContainsFunc(dirs[:len(dirs)-1], func(d string) bool { return d == "templates" || d == "crds" }) +} + +func testFixture(path string) bool { + dirs := strings.Split(path, "/") + return slices.ContainsFunc(dirs[:len(dirs)-1], func(d string) bool { return d == "tests" || d == "testdata" }) +} + +// grepFiles lists which of files at rev hold any of the fixed strings that +// patterns give. Paths are passed literally, so a name such as ":(exclude)x" +// means only that file. +func grepFiles(rev string, files []string, patterns ...string) ([]string, error) { + const chunk = 500 + var found []string + for len(files) > 0 { + n := min(chunk, len(files)) + args := append([]string{"--literal-pathspecs", "grep", "-l", "-z", "-F"}, patterns...) + args = append(append(args, "--end-of-options", rev, "--"), files[:n]...) + stdout, stderr, code, err := gitStatus(args...) + switch { + case err != nil: + return nil, err + case code != 0 && code != 1: + return nil, fmt.Errorf("git grep at %s: exit %d: %s", rev, code, strings.TrimSpace(stderr)) + } + for _, hit := range splitNUL(stdout) { + if path, ok := strings.CutPrefix(hit, rev+":"); ok { + found = append(found, path) + } + } + files = files[n:] + } + return found, nil +} + +var ( + docSeparatorRE = regexp.MustCompile(`(?m)^---[ \t]*(?:#.*)?$`) + // A document that declares the kind on a line of its own, in YAML or in + // JSON, under a bare or quoted key, is a CRD even when it cannot be read; + // a sentence or a lookup call that names it declares nothing. + crdKindLineRE = regexp.MustCompile(`(?m)^[ \t]*(?:-[ \t]+)?(?:kind|"kind"|'kind')[ \t]*:[ \t]*["']?CustomResourceDefinition["']?[ \t]*,?[ \t]*(?:#.*)?$`) +) + +// crdDocs maps the CRD documents of a file to their text, keyed by +// metadata.name, so a CRD added, removed or edited changes the map. Every +// document that names the kind is read, so a CRD in compact JSON or under a +// quoted key counts as well. A document that declares the kind on a line of +// its own but cannot be read as an object, a CRD behind a Helm template guard +// for one, is kept under its own text, so that any change to it counts: the +// check fails closed. So does a list holding a CRD. +func crdDocs(content string) map[string]string { + docs := map[string]string{} + for _, doc := range docSeparatorRE.Split(content, -1) { + declares := crdKindLineRE.MatchString(doc) + if !declares && !strings.Contains(doc, crdKind) { + continue + } + var head struct { + Kind string `json:"kind"` + Metadata struct { + Name string `json:"name"` + } `json:"metadata"` + Items []struct { + Kind string `json:"kind"` + } `json:"items"` + } + key := "" + switch err := yaml.Unmarshal([]byte(doc), &head); { + case err != nil && declares: + key = "unreadable:" + doc + case err != nil: + continue + case head.Kind == crdKind && head.Metadata.Name != "": + key = "crd:" + head.Metadata.Name + case head.Kind == crdKind: + key = "unnamed:" + doc + case strings.HasSuffix(head.Kind, "List") && slices.ContainsFunc(head.Items, func(i struct { + Kind string `json:"kind"` + }) bool { + return i.Kind == crdKind + }): + key = "list:" + doc + default: + continue + } + docs[key] += doc + } + return docs +} diff --git a/cmd/backport-batch/rules_test.go b/cmd/backport-batch/rules_test.go new file mode 100644 index 000000000..ca1cd58a2 --- /dev/null +++ b/cmd/backport-batch/rules_test.go @@ -0,0 +1,461 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package main + +import ( + "maps" + "slices" + "strings" + "testing" +) + +func TestTypeRule(t *testing.T) { + cases := []struct { + title string + taken bool + }{ + {"fix(postgres): keep the replica count on resize", true}, + {"fix: typo in monitoring-agents values.yaml", true}, + {"security(dashboard): escape the tenant name", true}, + {"fix(ci): retry the flaky e2e step", true}, + {"[Backport release-1.6] fix(linstor): x", true}, + {"[Backport release-1.5] [Backport release-1.6] fix(linstor): x", true}, + {"fix(platform, dashboard): two scopes", true}, + {"feat(postgres): add a field", false}, + {"chore(release): promote", false}, + {"docs(release): split the page", false}, + {"refactor(api): move code", false}, + {"fix(deps): bump golang.org/x/net", false}, + {"fix(platform, deps): bump and fix", false}, + {"Fix(postgres): capitalised type", false}, + {"fix postgres without a colon", false}, + {"[postgres] bracket form", false}, + {"fixes(postgres): not the fix type", false}, + {"", false}, + } + for _, tc := range cases { + reason := typeRule(tc.title) + if (reason == "") != tc.taken { + t.Errorf("typeRule(%q) = %q, want taken=%v", tc.title, reason, tc.taken) + } + } +} + +func TestBreakingRule(t *testing.T) { + cases := []struct { + name, title, body string + breaking bool + }{ + {"plain fix", "fix(x): y", "## What this PR does\n\nFixes it.", false}, + {"bang", "fix(x)!: y", "", true}, + {"bang without scope", "fix!: y", "", true}, + {"bang behind a backport prefix", "[Backport release-1.6] fix(x)!: y", "", true}, + {"footer", "fix(x): y", "Body.\n\nBREAKING CHANGE: the field is gone", true}, + {"hyphenated footer", "fix(x): y", "BREAKING-CHANGE: the field is gone", true}, + {"footer quoted mid-line", "fix(x): y", "This is not a BREAKING CHANGE: nothing changes.", false}, + {"footer inside the template comment", "fix(x): y", "\nBody.", false}, + {"lower-case footer", "fix(x): y", "breaking change: no", false}, + } + for _, tc := range cases { + reason := breakingRule(tc.title, tc.body) + if (reason != "") != tc.breaking { + t.Errorf("%s: breakingRule = %q, want breaking=%v", tc.name, reason, tc.breaking) + } + } +} + +// Rule 4 reads the merge itself, so each case is a pull request merged into a +// real repository. +func TestTouchesRule(t *testing.T) { + cases := []struct { + name string + setup map[string]string // committed on main before the pull request + files map[string]string + want string + }{ + {name: "a chart change", files: map[string]string{"chart/values.yaml": "replicas: 2\nimage: app:1\n"}}, + {name: "a migration script", files: map[string]string{migrationsDir + "61": "#!/bin/sh\n"}, want: "platform migrations"}, + {name: "a migration library file", files: map[string]string{migrationsDir + "lib/common.sh": "x\n"}, want: "platform migrations"}, + {name: "the migration runner is not a migration", files: map[string]string{"packages/core/platform/images/migrations/run-migrations.sh": "x\n"}}, + { + name: "targetVersion moves", + setup: map[string]string{platformValues: "migrations:\n enabled: false\n targetVersion: 60\n"}, + files: map[string]string{platformValues: "migrations:\n enabled: false\n targetVersion: 61\n"}, + want: "targetVersion", + }, + { + name: "another key of the platform values", + setup: map[string]string{platformValues: "migrations:\n enabled: false\n targetVersion: 60\n"}, + files: map[string]string{platformValues: "migrations:\n enabled: true\n targetVersion: 60\n"}, + }, + {name: "api types the gate sees nothing in", setup: demoAPI, files: map[string]string{"api/apps/v1alpha1/types.go": "package v1alpha1\n"}}, + {name: "pkg/apis is not api/", files: map[string]string{"pkg/apis/apps/types.go": "package apps\n"}}, + {name: "a CRD added under crds/", files: map[string]string{"packages/system/x/charts/x/crds/a.yaml": crdDoc("as.x.io", "a") + "\n"}, want: "a CRD"}, + {name: "a ConfigMap under crds/ is not a CRD", files: map[string]string{"packages/system/x/charts/x/crds/a.yaml": "kind: ConfigMap\n"}}, + { + name: "a DaemonSet edit next to an unchanged CRD", + setup: map[string]string{"packages/system/x/templates/m.yaml": multiDoc(crdDoc("as.x.io", "a"), daemonSet("1"))}, + files: map[string]string{"packages/system/x/templates/m.yaml": multiDoc(crdDoc("as.x.io", "a"), daemonSet("2"))}, + }, + { + name: "a real CRD edit in a manifest with other documents", + setup: map[string]string{"packages/system/x/templates/m.yaml": multiDoc(crdDoc("as.x.io", "a"), daemonSet("1"))}, + files: map[string]string{"packages/system/x/templates/m.yaml": multiDoc(crdDoc("as.x.io", "b"), daemonSet("1"))}, + want: "a CRD", + }, + { + name: "a CRD renamed", + setup: map[string]string{"packages/system/x/templates/m.yaml": multiDoc(crdDoc("as.x.io", "a"), daemonSet("1"))}, + files: map[string]string{"packages/system/x/templates/m.yaml": multiDoc(crdDoc("bs.x.io", "a"), daemonSet("1"))}, + want: "a CRD", + }, + {name: "a CRD in a fixture under tests/", files: map[string]string{"packages/system/x/tests/render_test.yaml": crdDoc("as.x.io", "a")}}, + {name: "a CRD in a fixture under testdata/", files: map[string]string{"hack/testdata/crd.yaml": crdDoc("as.x.io", "a")}}, + { + name: "a templated CRD edited, which cannot be read", + setup: map[string]string{"packages/system/x/templates/m.yaml": multiDoc(templatedCRD("a"), daemonSet("1"))}, + files: map[string]string{"packages/system/x/templates/m.yaml": multiDoc(templatedCRD("b"), daemonSet("1"))}, + want: "a CRD", + }, + { + name: "a DaemonSet edit next to an unchanged templated CRD", + setup: map[string]string{"packages/system/x/templates/m.yaml": multiDoc(templatedCRD("a"), daemonSet("1"))}, + files: map[string]string{"packages/system/x/templates/m.yaml": multiDoc(templatedCRD("a"), daemonSet("2"))}, + }, + { + name: "an unparseable file that names the kind, changed", + setup: map[string]string{"x/broken.yaml": "kind: CustomResourceDefinition\nspec: [unclosed\n"}, + files: map[string]string{"x/broken.yaml": "kind: CustomResourceDefinition\nspec: [still unclosed\n"}, + want: "a CRD", + }, + { + name: "a lookup that names the kind in a Helm helper", + setup: map[string]string{"packages/system/x/templates/_helpers.tpl": "{{- $crd := lookup \"apiextensions.k8s.io/v1\" \"CustomResourceDefinition\" \"\" .crd -}}\n{{- if $crd }}a{{ end }}\n"}, + files: map[string]string{"packages/system/x/templates/_helpers.tpl": "{{- $crd := lookup \"apiextensions.k8s.io/v1\" \"CustomResourceDefinition\" \"\" .crd -}}\n{{- if $crd }}b{{ end }}\n"}, + }, + { + name: "a CRD example in documentation", + setup: map[string]string{"docs/crds.md": "Example:\n\n```yaml\nkind: CustomResourceDefinition\nmetadata:\n name: as.x.io\n```\n"}, + files: map[string]string{"docs/crds.md": "An example:\n\n```yaml\nkind: CustomResourceDefinition\nmetadata:\n name: bs.x.io\n```\n"}, + }, + {name: "a CRD in a template without a YAML extension", files: map[string]string{"packages/system/x/templates/crd.tmpl": crdDoc("as.x.io", "a")}, want: "a CRD"}, + {name: "a CRD added as JSON", files: map[string]string{"x/crd.json": `{"apiVersion": "apiextensions.k8s.io/v1",` + "\n" + ` "kind": "CustomResourceDefinition",` + "\n" + ` "metadata": {"name": "as.x.io"}}` + "\n"}, want: "a CRD"}, + {name: "a List of CRDs", files: map[string]string{"x/list.yaml": "kind: List\nitems:\n- kind: CustomResourceDefinition\n metadata:\n name: as.x.io\n"}, want: "a CRD"}, + {name: "a template declaring a CRD", files: map[string]string{"packages/system/x/templates/crd.yaml": "apiVersion: apiextensions.k8s.io/v1\nkind: CustomResourceDefinition\n"}, want: "a CRD"}, + {name: "a quoted declaration", files: map[string]string{"x/crd.yaml": " kind: \"CustomResourceDefinition\" # yes\n"}, want: "a CRD"}, + { + name: "a CRD changed in place", + setup: map[string]string{"x/crd.yaml": "kind: CustomResourceDefinition\nspec: {}\n"}, + files: map[string]string{"x/crd.yaml": "kind: CustomResourceDefinition\nspec: {a: 1}\n"}, + want: "a CRD", + }, + { + name: "a CRD deleted", + setup: map[string]string{"x/crd.yaml": "kind: CustomResourceDefinition\n"}, + files: map[string]string{"x/crd.yaml": ""}, + want: "a CRD", + }, + { + name: "a CRD turned into something else", + setup: map[string]string{"x/crd.yaml": "kind: CustomResourceDefinition\n"}, + files: map[string]string{"x/crd.yaml": "kind: ConfigMap\n"}, + want: "a CRD", + }, + {name: "a CRD list is not a CRD", files: map[string]string{"x/list.yaml": "kind: CustomResourceDefinitionList\n"}}, + {name: "a CRD as compact JSON", files: map[string]string{"x/crd.json": `{"apiVersion":"apiextensions.k8s.io/v1","kind":"CustomResourceDefinition","metadata":{"name":"as.x.io"}}` + "\n"}, want: "a CRD"}, + {name: "a CRD under a quoted kind key", files: map[string]string{"x/crd.yaml": "'kind': CustomResourceDefinition\nmetadata:\n name: as.x.io\n"}, want: "a CRD"}, + { + name: "a templated CRD under a quoted kind key, edited", + setup: map[string]string{"packages/system/x/templates/m.yaml": strings.Replace(templatedCRD("a"), "kind:", "'kind':", 1)}, + files: map[string]string{"packages/system/x/templates/m.yaml": strings.Replace(templatedCRD("b"), "kind:", "'kind':", 1)}, + want: "a CRD", + }, + {name: "a ConfigMap as compact JSON naming the kind", files: map[string]string{"x/cm.json": `{"kind":"ConfigMap","data":{"note":"kind: CustomResourceDefinition"}}` + "\n"}}, + {name: "a CRD mentioned in prose", files: map[string]string{"x/README.md": "Set kind: CustomResourceDefinition here.\n"}}, + {name: "a file named like an option declaring a CRD", files: map[string]string{"-e.yaml": "kind: CustomResourceDefinition\n"}, want: "a CRD"}, + // As pathspec magic, :(icase)... would match a file of that name in + // another case, and there is none. + {name: "a file named like pathspec magic declaring a CRD", files: map[string]string{":(icase)zz-crd.yaml": "kind: CustomResourceDefinition\n"}, want: "a CRD"}, + { + name: "a migration and a sizeable API change together", + setup: demoAPI, + files: map[string]string{migrationsDir + "61": "x\n", "api/x.go": "package x\n", demoRD: cozyrd("demo", `{"type":"object","properties":{}}`)}, + want: "platform migrations, a sizeable API change (breaking-change: [v1alpha1] spec: field \"size\" was removed)", + }, + } + for i, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + f := newFixture(t) + setup := maps.Clone(apiBase) + maps.Copy(setup, tc.setup) + f.squash(1000, "chore: setup", "", setup) + mc := f.pr(10+i, "fix(x): y", "", tc.files) + o := &original{number: 10 + i, merge: mc, parents: 2} + changes, err := changedFiles(mc+"^1", mc) + if err != nil { + t.Fatal(err) + } + got, err := touchesRule(o, changes) + if err != nil { + t.Fatal(err) + } + if got != tc.want { + t.Errorf("touchesRule = %q, want %q", got, tc.want) + } + }) + } +} + +// Rule 6: an older line takes only what the newer line already carries, and +// rule 1: neither line takes what it carries already. +func TestNewerLineAndOnLine(t *testing.T) { + f := newFixture(t) + f.lines() + f.pr(2, "fix(app): before nothing", "", map[string]string{"app/a.txt": "a\n"}) + f.pr(3, "fix(app): picked onto 1.1", "", map[string]string{"app/b.txt": "b\n"}) + mc3 := f.git("rev-parse", "HEAD") + f.pr(4, "fix(app): only on main", "", map[string]string{"app/c.txt": "c\n"}) + f.onLine("release-1.1", "fix(app): picked onto 1.1 (#3)\n\n(cherry picked from commit "+mc3+")", map[string]string{"app/b.txt": "b\n"}) + + for _, tc := range []struct { + line string + qualified []int + skipped map[int]int + }{ + {line: "release-1.1", qualified: []int{2, 4}, skipped: map[int]int{3: ruleOnLine}}, + // #1 is a feature; #2 and #4 are not on release-1.1 yet; #3 is. + {line: "release-1.0", qualified: []int{3}, skipped: map[int]int{1: ruleType, 2: ruleNewer, 4: ruleNewer}}, + } { + t.Run(tc.line, func(t *testing.T) { + f.git("fetch", "-q", "origin") + l, _ := parseLine(tc.line) + b, err := (&app{gh: &fakeGH{}, stderr: &strings.Builder{}}).prepare(l) + if err != nil { + t.Fatal(err) + } + var got []int + for _, v := range b.qualifying() { + got = append(got, v.o.number) + } + if !slices.Equal(got, tc.qualified) { + t.Errorf("qualifying = %v, want %v", got, tc.qualified) + } + for n, rule := range tc.skipped { + if v := b.find(n); v == nil || v.rule != rule { + t.Errorf("#%d: verdict %+v, want rule %d", n, v, rule) + } + } + }) + } +} + +// An original merged before the newer line branched is on it, even when the +// newer line has since changed the same lines and a pick would conflict. +func TestNewerLineCarriesWhatItBranchedWith(t *testing.T) { + f := newFixture(t) + f.release("release-1.0") + f.pr(2, "fix(app): two", "", map[string]string{"app/a.txt": "two\n"}) + f.release("release-1.1") + mc3 := f.pr(3, "fix(app): three", "", map[string]string{"app/a.txt": "three\n"}) + f.onLine("release-1.1", "fix(app): three (#3)\n\n(cherry picked from commit "+mc3+")", map[string]string{"app/a.txt": "three\n"}) + if v := verdictOn(t, f, nil, "release-1.0", 2); v.rule != 0 { + t.Errorf("#2 on release-1.0 = rule %d (%s), want it to qualify", v.rule, v.reason) + } +} + +// A line branched and not yet released is one the batch runs for, and rule 6 +// holds each older line to the next newer one. +func TestNewerLineInTheRCWindow(t *testing.T) { + f := newFixture(t) + f.lines() + f.release("release-1.2") + f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"}) + for _, tc := range []struct{ line, reason string }{ + {"release-1.2", ""}, + {"release-1.1", "not on release-1.2 yet"}, + {"release-1.0", "not on release-1.1 yet"}, + } { + v := verdictOn(t, f, nil, tc.line, 5) + if v.reason != tc.reason || (v.rule == 0) != (tc.reason == "") { + t.Errorf("#5 on %s = rule %d (%s), want %q", tc.line, v.rule, v.reason, tc.reason) + } + } +} + +func TestOnlySupportedLines(t *testing.T) { + f := newFixture(t) + f.release("release-0.9") + f.lines() + code, _, stderr := f.exec(nil, "check", "--line", "release-0.9") + if code != 2 || !strings.Contains(stderr, "not a line the batch runs for") { + t.Errorf("check on release-0.9 = %d (%s), want 2 and a refusal", code, stderr) + } +} + +// demoRD is an ApplicationDefinition where apigate looks for one, and demoAPI +// the tree the API cases start from. +const demoRD = "packages/system/demo-rd/cozyrds/demo.yaml" + +// apiBase is the least API a tree holds: apigate refuses a tree with none. +var apiBase = map[string]string{"packages/system/keep-rd/cozyrds/keep.yaml": cozyrd("keep", `{"type":"object"}`)} + +var demoAPI = map[string]string{ + demoRD: cozyrd("demo", `{"type":"object","properties":{"size":{"type":"string","description":"Size."}}}`), + "api/apps/v1alpha1/demo/types.go": "package demo\n\n// Size of it.\ntype Spec struct{ Size string }\n", +} + +func cozyrd(name, schema string) string { + return "apiVersion: cozystack.io/v1alpha1\nkind: ApplicationDefinition\nmetadata:\n name: " + name + + "\nspec:\n application:\n kind: " + strings.ToUpper(name[:1]) + name[1:] + "\n plural: " + name + "s\n singular: " + name + + "\n openAPISchema: '" + schema + "'\n" +} + +// Rule 4 holds back a change to the API only when the API review gate calls it +// sizeable: a new or removed resource or group, or a breaking schema change. +func TestAPIGateRule(t *testing.T) { + typesGo := "api/apps/v1alpha1/demo/types.go" + cases := []struct { + name string + files map[string]string + want string + }{ + {name: "a description reworded", files: map[string]string{ + demoRD: cozyrd("demo", `{"type":"object","properties":{"size":{"type":"string","description":"The size."}}}`), + typesGo: "package demo\n\n// The size.\ntype Spec struct{ Size string }\n", + }}, + {name: "an optional field added", files: map[string]string{ + demoRD: cozyrd("demo", `{"type":"object","properties":{"size":{"type":"string"},"zone":{"type":"string"}}}`), + typesGo: "package demo\n\ntype Spec struct{ Size, Zone string }\n", + }}, + {name: "a field removed", files: map[string]string{ + demoRD: cozyrd("demo", `{"type":"object","properties":{}}`), + typesGo: "package demo\n\ntype Spec struct{}\n", + }, want: "breaking-change"}, + {name: "a field's type changed", files: map[string]string{ + demoRD: cozyrd("demo", `{"type":"object","properties":{"size":{"type":"integer"}}}`), + typesGo: "package demo\n\ntype Spec struct{ Size int }\n", + }, want: "breaking-change"}, + {name: "a field made required", files: map[string]string{ + demoRD: cozyrd("demo", `{"type":"object","required":["size"],"properties":{"size":{"type":"string"}}}`), + typesGo: "package demo\n\n// +required\ntype Spec struct{ Size string }\n", + }, want: "breaking-change"}, + {name: "a resource added", files: map[string]string{ + "packages/system/other-rd/cozyrds/other.yaml": cozyrd("other", `{"type":"object"}`), + "api/apps/v1alpha1/other/types.go": "package other\n", + }, want: "new-resource"}, + {name: "a resource removed", files: map[string]string{ + demoRD: "", + typesGo: "", + }, want: "removed"}, + {name: "a breaking schema change that does not touch api/", files: map[string]string{ + demoRD: cozyrd("demo", `{"type":"object","properties":{}}`), + }, want: "breaking-change"}, + {name: "an aggregated group registered in a chart", files: map[string]string{ + "packages/system/extra/templates/apiservice.yaml": apiService("extra.cozystack.io"), + }, want: "new-api-group"}, + } + for i, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + f := newFixture(t) + setup := maps.Clone(apiBase) + maps.Copy(setup, demoAPI) + f.squash(1000, "chore: setup", "", setup) + mc := f.pr(10+i, "fix(x): y", "", tc.files) + o := &original{number: 10 + i, merge: mc, parents: 2} + changes, err := changedFiles(mc+"^1", mc) + if err != nil { + t.Fatal(err) + } + got, err := touchesRule(o, changes) + if err != nil { + t.Fatal(err) + } + if (got != "") != (tc.want != "") || !strings.Contains(got, tc.want) { + t.Errorf("touchesRule = %q, want %q", got, tc.want) + } + }) + } +} + +func apiService(group string) string { + return "apiVersion: apiregistration.k8s.io/v1\nkind: APIService\nmetadata:\n name: v1alpha1." + group + + "\nspec:\n group: " + group + "\n version: v1alpha1\n" +} + +// The API review gate is asked about exactly the changes that reach what +// apigate parses at either end of the merge. +func TestReadsAPI(t *testing.T) { + crd := crdDoc("as.x.io", "a") + cases := []struct { + name string + setup map[string]string + files map[string]string + want bool + }{ + {name: "the apiserver's registrations", files: map[string]string{apiserverGo: "package apiserver\n"}, want: true}, + {name: "an ApplicationDefinition, which carries no marker", files: map[string]string{demoRD: "kind: ApplicationDefinition\n"}, want: true}, + {name: "a CRD in a chart", files: map[string]string{"packages/system/x/crds/a.yaml": crd}, want: true}, + {name: "an APIService under internal/", files: map[string]string{"internal/x/apiservice.yml": apiService("x.cozystack.io")}, want: true}, + { + name: "a CRD turned into something else", + setup: map[string]string{"packages/system/x/crds/a.yaml": crd}, + files: map[string]string{"packages/system/x/crds/a.yaml": "kind: ConfigMap\n"}, + want: true, + }, + {name: "a binary file with a marker", files: map[string]string{"packages/system/x/a.yaml": "\x00kind: APIService\n"}, want: true}, + {name: "chart values", files: map[string]string{"packages/system/x/values.yaml": "replicas: 2\n"}}, + {name: "Go types under api/", files: map[string]string{"api/apps/v1alpha1/demo/types.go": "package demo\n"}}, + {name: "a CRD outside the roots apigate walks", files: map[string]string{"hack/crds/a.yaml": crd}}, + {name: "a CRD in a template without a YAML extension", files: map[string]string{"packages/system/x/templates/crd.tpl": crd}}, + {name: "a file beside the ApplicationDefinitions", files: map[string]string{"packages/system/demo-rd/cozyrds/sub/demo.yaml": "kind: ApplicationDefinition\n"}}, + } + for i, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + f := newFixture(t) + setup := maps.Clone(apiBase) + maps.Copy(setup, tc.setup) + f.squash(1000, "chore: setup", "", setup) + mc := f.pr(10+i, "fix(x): y", "", tc.files) + changes, err := changedFiles(mc+"^1", mc) + if err != nil { + t.Fatal(err) + } + got, err := readsAPI(mc+"^1", mc, changes) + if err != nil { + t.Fatal(err) + } + if got != tc.want { + t.Errorf("readsAPI = %v, want %v", got, tc.want) + } + }) + } +} + +func crdDoc(name, version string) string { + return "apiVersion: apiextensions.k8s.io/v1\nkind: CustomResourceDefinition\nmetadata:\n name: " + name + + "\nspec:\n group: x.io\n versions:\n - name: v1" + version + "\n" +} + +func daemonSet(replicas string) string { + return "apiVersion: apps/v1\nkind: DaemonSet\nmetadata:\n name: agent\nspec:\n template:\n spec:\n priority: {{ .Values.priority | default " + replicas + " }}\n" +} + +func templatedCRD(version string) string { + return "{{- if .Values.crds }}\n" + crdDoc("ts.x.io", version) + "{{- end }}\n" +} + +func multiDoc(docs ...string) string { return "---\n" + strings.Join(docs, "---\n") } diff --git a/cmd/backport-batch/shape.go b/cmd/backport-batch/shape.go new file mode 100644 index 000000000..b4a1e759c --- /dev/null +++ b/cmd/backport-batch/shape.go @@ -0,0 +1,530 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package main + +import ( + "errors" + "fmt" + "os" + "slices" + "strconv" + "strings" +) + +// A batch carries each original as one unit on its first-parent line. A +// merged pull request is a merge commit whose first parent is the batch before +// it and whose second parent ends a straight line of picks of the pull +// request's own commits, oldest first, each keeping its author and sign-offs; +// the merge says which merge commit on main it carries in a Backported-from +// trailer. A squash-merged original is one pick of its commit on main. + +// pickOriginal picks one original onto HEAD in that shape. A conflict on any +// of its commits takes the branch back to where it was before the original, +// so nothing of it is left half applied, and so does a clean pick validate +// finds leaving something of the original without effect: partial, with +// those paths. Hooks are off so that each commit carries its message and -x +// line as git writes them; signing is left to the user's configuration. +func pickOriginal(v *verdict, validate func(base, head string) ([]string, error)) (pick, error) { + p := pick{v: v} + base, err := resolve("HEAD") + if err != nil { + return p, err + } + for _, c := range v.commits { + status, files, err := applyPick("-c", "core.hooksPath=/dev/null", "cherry-pick", "-x", "--signoff", "--end-of-options", c) + if err != nil { + if rerr := resetTo(base); rerr != nil { + return p, rerr + } + return p, fmt.Errorf("cherry-pick of %.12s of #%d: %w", c, v.o.number, err) + } + if status == "conflict" { + p.status, p.files, p.failed = "conflict", files, c + return p, resetTo(base) + } + } + head, err := resolve("HEAD") + switch { + case err != nil: + return p, err + case head == base && validate != nil: + // Picks that change nothing carry the original only when the line + // already has its changes: a change made where its branch merged + // main is in no pick. + omitted, err := validate(base, head) + if err != nil { + return p, err + } + if len(omitted) > 0 { + p.status, p.files = "partial", omitted + return p, nil + } + p.status = "empty" + return p, nil + case head == base: + p.status = "empty" + return p, nil + } + if validate != nil { + omitted, err := validate(base, head) + if err == nil && len(omitted) > 0 { + p.status, p.files = "partial", omitted + } + if err != nil || len(omitted) > 0 { + return p, errors.Join(err, resetTo(base)) + } + } + if v.o.parents < 2 { + p.status, p.commit = "picked", head + return p, nil + } + msgs, err := commitMessages([]string{v.o.merge}) + if err != nil { + return p, err + } + if p.commit, err = commitMerge(base, head, mergeMessage(msgs[v.o.merge].message, v.o.merge)); err != nil { + if rerr := resetTo(base); rerr != nil { + return p, rerr + } + return p, err + } + p.status = "picked" + return p, nil +} + +// mergeMessage is the message of a batch merge: the one of the merge commit +// on main, which says which pull request it was, and a paragraph of its own +// naming that merge commit, so nothing the original's text ends with can pass +// for the trailer. +func mergeMessage(message, merge string) string { + return strings.TrimRight(message, " \t\r\n") + "\n\n" + batchTrailer + ": " + merge + "\n" +} + +// pickUnit and replayNext start the next unit only while the run's output is +// intact: once it was lost no new unit starts, and a unit already in flight +// still finishes its rollback. +func (a *app) pickUnit(v *verdict, validate func(base, head string) ([]string, error)) (pick, error) { + if err := a.mayAct(); err != nil { + return pick{}, err + } + return pickOriginal(v, validate) +} + +func (a *app) replayNext(u unit) (string, []string, error) { + if err := a.mayAct(); err != nil { + return "", nil, err + } + return replayUnit(u) +} + +// commitMerge makes the merge of tip onto base, whose tree is tip's since tip +// descends from base, and moves the current branch from tip to it. +func commitMerge(base, tip, message string) (string, error) { + f, err := os.CreateTemp("", "backport-batch-merge-*.txt") + if err != nil { + return "", err + } + defer func() { _ = os.Remove(f.Name()) }() + if _, err := f.WriteString(message); err != nil { + _ = f.Close() + return "", err + } + if err := f.Close(); err != nil { + return "", err + } + out, err := git("commit-tree", "-p", base, "-p", tip, "-F", f.Name(), tip+"^{tree}") + if err != nil { + return "", err + } + merge := strings.TrimSpace(out) + if err := checkSHA(merge); err != nil { + return "", fmt.Errorf("commit-tree: %w", err) + } + if _, err := git("update-ref", "-m", "backport-batch: merge", "HEAD", merge, tip); err != nil { + return "", err + } + return merge, nil +} + +// resetTo takes the current branch, its index and its tree back to commit, +// which run owns: it starts only in a clean tree. +func resetTo(commit string) error { + _, err := git("reset", "--quiet", "--hard", commit) + return err +} + +// unit is one original as a batch carries it: a commit on the batch's +// first-parent line, and for a merge the picks its second parent brings. +type unit struct { + commit string + parents []string + message string + // picks are the commits reachable from the second parent and not from the + // first, oldest first. + picks []string +} + +func (u unit) merge() bool { return len(u.parents) == 2 } + +func readUnit(commit string) (unit, error) { + msgs, err := commitMessages([]string{commit}) + if err != nil { + return unit{}, err + } + u := unit{commit: commit, parents: msgs[commit].parents, message: msgs[commit].message} + if u.merge() { + if u.picks, err = revList("--reverse", "--topo-order", "--end-of-options", u.parents[1], "^"+u.parents[0]); err != nil { + return unit{}, err + } + } + return u, nil +} + +// batchUnits lists the units of the batch from base to head, oldest first. +func batchUnits(head, base string) ([]unit, error) { + oids, err := revList("--reverse", "--first-parent", "--end-of-options", head, "^"+base) + if err != nil { + return nil, err + } + var units []unit + for _, oid := range oids { + u, err := readUnit(oid) + if err != nil { + return nil, err + } + units = append(units, u) + } + return units, nil +} + +// unitOriginal is the original a unit says it carries, or nil: the one its +// Backported-from trailer names, or the one its appended -x line picks. +func (b *batch) unitOriginal(u unit) *verdict { + if u.merge() { + if merges := batchedFrom(u.message); len(merges) == 1 { + return b.findMerge(merges[0]) + } + return nil + } + source := appendedSource(u.message) + if v := b.findMerge(source); v != nil { + return v + } + return b.pickedBy([]string{source}) +} + +// ownerOf is the original one of whose own commits source is, or nil. It reads +// every original's commits, so it is for explaining a refusal only. +func (b *batch) ownerOf(source string) (*verdict, error) { + for _, v := range b.verdicts { + if v.commits == nil { + commits, err := prCommits(v.o) + if err != nil { + return nil, err + } + v.commits = commits + } + if v.o.parents > 1 && slices.Contains(v.commits, source) { + return v, nil + } + } + return nil, nil +} + +// checkUnit says why u is not one original carried in the batch's shape, or +// "" when it is, and which original it carries: a merge whose second parent +// is a straight line from its first, of picks of the pull request's own +// commits in their order, each with the -x line of the commit it came from, +// that names the original's merge commit in its trailer; or for a squash one +// pick of its commit on main. Either changes something, and only files the +// original changes. A pick is known by the -x line git appended, not by +// lines its message brought along, and one that also claims another commit +// of the same original is refused. +func checkUnit(b *batch, u unit) (string, *verdict, error) { + switch len(u.parents) { + case 1: + return checkPick(b, u) + case 2: + return checkMerge(b, u) + } + return fmt.Sprintf("%.12s has %d parents", u.commit, len(u.parents)), nil, nil +} + +func checkPick(b *batch, u unit) (string, *verdict, error) { + source := appendedSource(u.message) + if source == "" { + return fmt.Sprintf("%.12s ends in no (cherry picked from commit …) line; a batch carries originals only", u.commit), nil, nil + } + v := b.findMerge(source) + if v == nil { + owner, err := b.ownerOf(source) + if err != nil { + return "", nil, err + } + if owner != nil { + return fmt.Sprintf("%.12s picks one commit of #%d on its own; a merged pull request goes in as a merge of all its commits", u.commit, owner.o.number), owner, nil + } + return fmt.Sprintf("%.12s picks %s, which merged no pull request into main after %s branched", u.commit, source, b.line.branch()), nil, nil + } + if v.o.parents > 1 { + return fmt.Sprintf("%.12s picks the merge commit of #%d as one commit; a merged pull request goes in as a merge of its own commits", u.commit, v.o.number), v, nil + } + why, err := contained(b, v, u.parents[0], u.commit) + return why, v, err +} + +func checkMerge(b *batch, u unit) (string, *verdict, error) { + merges := batchedFrom(u.message) + if len(merges) != 1 { + return fmt.Sprintf("%.12s is a merge with %d %s trailers, not one", u.commit, len(merges), batchTrailer), nil, nil + } + v := b.findMerge(merges[0]) + switch { + case v == nil: + return fmt.Sprintf("%.12s names %s, which merged no pull request into main after %s branched", u.commit, merges[0], b.line.branch()), nil, nil + case v.o.parents < 2: + return fmt.Sprintf("%.12s merges #%d, which main took as one commit; it goes in as one pick", u.commit, v.o.number), v, nil + case len(u.picks) == 0: + return fmt.Sprintf("%.12s merges nothing", u.commit), v, nil + } + if err := b.load(v); err != nil { + return "", nil, err + } + msgs, err := commitMessages(u.picks) + if err != nil { + return "", nil, err + } + prev, last := u.parents[0], -1 + for _, c := range u.picks { + ps := msgs[c].parents + if len(ps) != 1 || ps[0] != prev { + return fmt.Sprintf("%.12s is not on a straight line of picks from %.12s", c, u.parents[0]), v, nil + } + source := appendedSource(msgs[c].message) + if source == "" { + return fmt.Sprintf("%.12s ends in no (cherry picked from commit …) line", c), v, nil + } + i := slices.Index(v.commits, source) + if i < 0 { + owner, err := b.ownerOf(source) + switch { + case err != nil: + return "", nil, err + case owner != nil: + return fmt.Sprintf("%.12s picks a commit of #%d into the merge of #%d", c, owner.o.number, v.o.number), v, nil + } + return fmt.Sprintf("%.12s picks %s, which is not a commit of #%d", c, source, v.o.number), v, nil + } + if i <= last { + return fmt.Sprintf("%.12s picks %.12s out of the order of #%d's commits", c, source, v.o.number), v, nil + } + for _, claimed := range claimedSources(msgs[c].message) { + if claimed != source && (claimed == v.o.merge || slices.Contains(v.commits, claimed)) { + return fmt.Sprintf("%.12s claims more than one commit of #%d", c, v.o.number), v, nil + } + } + prev, last = c, i + } + why, err := contained(b, v, u.parents[0], u.commit) + return why, v, err +} + +// contained says why the change from base to tip is not inside the files v +// changes, or the paths a rename on main or on the line gave them at base, +// or "" when it is. +func contained(b *batch, v *verdict, base, tip string) (string, error) { + if err := b.load(v); err != nil { + return "", err + } + changes, err := changedFiles(base, tip) + if err != nil { + return "", err + } + if len(changes) == 0 { + return fmt.Sprintf("%.12s changes nothing", tip), nil + } + corr, _, err := b.correspondence(v, base) + if err != nil { + return "", err + } + allowed := paths(v.changes) + for _, c := range corr { + allowed = append(allowed, c) + } + var extra []string + for _, p := range paths(changes) { + if !slices.Contains(allowed, p) { + extra = append(extra, strconv.Quote(p)) + } + } + if len(extra) > 0 { + return fmt.Sprintf("%.12s touches %s, which #%d does not touch", tip, strings.Join(extra, ", "), v.o.number), nil + } + return "", nil +} + +// replayUnit picks a unit of the batch again onto HEAD in its own shape: a +// pushed resolution keeps what it resolved. On a conflict it takes the branch +// back to where it was before the unit and names the commit that failed. +func replayUnit(u unit) (string, []string, error) { + base, err := resolve("HEAD") + if err != nil { + return "", nil, err + } + picks := u.picks + if !u.merge() { + picks = []string{u.commit} + } + for _, c := range picks { + status, files, err := applyPick("-c", "core.hooksPath=/dev/null", "cherry-pick", "--end-of-options", c) + if err == nil && status == "conflict" { + return c, files, resetTo(base) + } + if err != nil { + if rerr := resetTo(base); rerr != nil { + return "", nil, rerr + } + return "", nil, fmt.Errorf("picking %.12s again: %w", c, err) + } + } + tip, err := resolve("HEAD") + if err != nil || !u.merge() || tip == base { + return "", nil, err + } + _, err = commitMerge(base, tip, u.message) + return "", nil, err +} + +// pickPair is a pick on the batch and the commit it was picked from. +type pickPair struct{ source, pick string } + +// unitShape is what an original's unit on the batch brought: how many +// commits, the picks that differ from the commit they came from, a +// resolution or a pick git had to fit to the line, and whether the unit as a +// whole makes another change than the original's merge. +type unitShape struct { + unit string + commits int + pairs []pickPair + net bool +} + +// changed says whether the unit differs from its original, so its release +// note may no longer hold. +func (s unitShape) changed() bool { return len(s.pairs) > 0 || s.net } + +// String is the shape as the body lists it. +func (s unitShape) String() string { + out := "1 commit" + if s.commits != 1 { + out = fmt.Sprintf("%d commits", s.commits) + } + if len(s.pairs) > 0 { + var picks []string + for _, p := range s.pairs { + picks = append(picks, codeSpan(p.pick[:12])) + } + out += ", changed in the pick: " + strings.Join(picks, ", ") + } else if s.net { + out += ", changed as a whole: some of its change is not in the picks" + } + return out +} + +// summarize says, for each original the batch head carries in units, what +// its unit brought. +func summarize(b *batch, head string, on []*verdict) (map[*verdict]unitShape, error) { + units, err := batchUnits(head, b.lineHead) + if err != nil { + return nil, err + } + out := map[*verdict]unitShape{} + for _, u := range units { + v := b.unitOriginal(u) + if v == nil || !slices.Contains(on, v) { + continue + } + picks := u.picks + if !u.merge() { + picks = []string{u.commit} + } + msgs, err := commitMessages(picks) + if err != nil { + return nil, err + } + s := unitShape{unit: u.commit, commits: len(picks)} + for _, c := range picks { + source := appendedSource(msgs[c].message) + if source == "" { + continue + } + same, err := samePatch(source, c) + if err != nil { + return nil, err + } + if !same { + s.pairs = append(s.pairs, pickPair{source: source, pick: c}) + } + } + // A pick that came out empty leaves no pick to differ, only a net + // change short of the original's. + mine, err := patchIDRange(v.o.merge+"^1", v.o.merge) + if err != nil { + return nil, err + } + theirs, err := patchIDRange(u.parents[0], u.commit) + if err != nil { + return nil, err + } + s.net = mine != theirs + out[v] = s + } + return out, nil +} + +func plural(n int, word string) string { + if n == 1 { + return word + } + return word + "s" +} + +// samePatch says whether two commits make the same change to their first +// parents, by git patch-id of their diffs without context, so that a pick +// that only lands among other lines on the line counts as the same. +func samePatch(a, b string) (bool, error) { + pa, err := patchIDRange(a+"^", a) + if err != nil { + return false, err + } + pb, err := patchIDRange(b+"^", b) + return pa == pb, err +} + +// patchIDRange is the patch-id of the change from one revision to another. +func patchIDRange(from, to string) (string, error) { + diff, err := git("diff", "--no-ext-diff", "--no-textconv", "--unified=0", "--end-of-options", from, to) + if err != nil { + return "", err + } + out, err := gitInput(diff, "patch-id", "--stable") + if err != nil { + return "", err + } + id, _, _ := strings.Cut(strings.TrimSpace(out), " ") + return id, nil +} diff --git a/cmd/backport-batch/shape_test.go b/cmd/backport-batch/shape_test.go new file mode 100644 index 000000000..0ff713a7f --- /dev/null +++ b/cmd/backport-batch/shape_test.go @@ -0,0 +1,372 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package main + +import ( + "os" + "path/filepath" + "slices" + "strings" + "testing" +) + +// A conflict on a commit in the middle of a pull request takes the batch back +// to where it was before that original: none of its commits stays, the +// conflict is recorded with the commit that failed, and the next original is +// still picked. +func TestRunConflictInAMiddleCommit(t *testing.T) { + f := newFixture(t) + f.lines() + f.onLine("release-1.1", "fix(chart): a line-only value", map[string]string{"chart/values.yaml": "replicas: 3\nimage: app:1\n"}) + mc5 := f.prCommits(5, "fix(chart): five", "", + change{files: map[string]string{"app/five.txt": "5\n"}}, + change{files: map[string]string{"chart/values.yaml": "replicas: 5\nimage: app:1\n"}}, + change{files: map[string]string{"app/five.txt": "5, done\n"}}) + own := strings.Fields(f.git("rev-list", "--reverse", mc5+"^1.."+mc5+"^2")) + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + + code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1") + if code != 0 { + t.Fatalf("run = %d\n%s", code, stderr) + } + if got := f.subjects("origin/release-1.1", "HEAD"); !slices.Equal(got, []string{"fix(app): six (#6)"}) { + t.Errorf("the batch carries %q, want only #6", got) + } + if log := f.git("log", "--format=%B", "origin/release-1.1..HEAD"); strings.Contains(log, own[0]) || strings.Contains(log, own[1]) { + t.Errorf("a commit of #5 stayed on the batch:\n%s", log) + } + if out := f.git("status", "--porcelain"); out != "" { + t.Errorf("the tree is left dirty:\n%s", out) + } + if _, err := os.Stat(filepath.Join(f.dir, ".git", "CHERRY_PICK_HEAD")); err == nil { + t.Error("a cherry-pick is left in progress") + } + l, _ := parseLine("release-1.1") + deferred, err := parseDeferred(stdout, l) + if err != nil || deferred[5].Commit != own[1] || !slices.Equal(deferred[5].Files, []string{"chart/values.yaml"}) { + t.Errorf("deferred = %+v, %v; want #5 at %s in chart/values.yaml", deferred, err, own[1]) + } + if !strings.Contains(stdout, "`fix(chart): five` at `"+own[1][:12]+"`: `chart/values.yaml`") { + t.Errorf("the body does not name the commit that failed:\n%s", stdout) + } +} + +// What counts as carrying a merged pull request of several commits: picks +// whose appended -x lines name every commit of its own, as a batch merge's do, +// or a pick whose appended -x line names its merge commit; not some of its +// commits. A Backported-from trailer counts only on a commit from before the +// batch-only day, and only in its trailer block. +func TestPresenceOfAMultiCommitOriginal(t *testing.T) { + cases := []struct { + name string + land func(f *fixture, mc string, own []string) + carried string + }{ + { + name: "a batch merge of its commits", + land: func(f *fixture, mc string, own []string) { + f.git("fetch", "-q", "origin") + base := f.git("rev-parse", "origin/release-1.1") + f.git("switch", "-q", "--detach", base) + for _, c := range own { + f.git("cherry-pick", "-x", c) + } + f.git("switch", "-q", "--detach", f.joined(base, f.git("rev-parse", "HEAD"), "fix(app): five (#5)\n\n"+batchTrailer+": "+mc)) + f.git("push", "-q", "origin", "HEAD:refs/heads/release-1.1") + f.git("switch", "-q", "main") + }, + carried: "its 2 commits picked", + }, + { + name: "a pick whose -x line names the merge commit", + land: func(f *fixture, mc string, _ []string) { + f.onLine("release-1.1", "port\n\n(cherry picked from commit "+mc+")", map[string]string{"app/a.txt": "a\n"}) + }, + carried: "picked in", + }, + { + name: "picks whose -x lines name every commit of its own", + land: func(f *fixture, _ string, own []string) { + f.onLine("release-1.1", "a\n\n(cherry picked from commit "+own[0]+")", map[string]string{"app/a.txt": "a\n"}) + f.onLine("release-1.1", "b\n\n(cherry picked from commit "+own[1]+")", map[string]string{"app/b.txt": "b, half\n"}) + }, + carried: "its 2 commits picked", + }, + { + name: "a pick of one of its two commits", + land: func(f *fixture, _ string, own []string) { + f.onLine("release-1.1", "a\n\n(cherry picked from commit "+own[0]+")", map[string]string{"app/a.txt": "a\n"}) + }, + }, + { + name: "the trailer alone, from before the batch-only day", + land: func(f *fixture, mc string, _ []string) { + f.t.Setenv("GIT_COMMITTER_DATE", "2026-10-01T00:00:00Z") + f.onLine("release-1.1", "fix(app): five (#5)\n\n"+batchTrailer+": "+mc, map[string]string{"app/a.txt": "a\n"}) + }, + carried: "named by a " + batchTrailer + " trailer", + }, + { + name: "the trailer alone, after the batch-only day", + land: func(f *fixture, mc string, _ []string) { + f.t.Setenv("GIT_COMMITTER_DATE", "2026-10-27T00:00:00Z") + f.onLine("release-1.1", "fix(app): five (#5)\n\n"+batchTrailer+": "+mc, map[string]string{"app/a.txt": "a\n"}) + }, + }, + { + name: "the trailer in the body, from before the batch-only day", + land: func(f *fixture, mc string, _ []string) { + f.t.Setenv("GIT_COMMITTER_DATE", "2026-10-01T00:00:00Z") + f.onLine("release-1.1", "port\n\n"+batchTrailer+": "+mc+"\n\nMore to say.", map[string]string{"app/a.txt": "a\n"}) + }, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + f := newFixture(t) + f.lines() + mc := f.prCommits(5, "fix(app): five", "", + change{files: map[string]string{"app/a.txt": "a\n"}}, + change{files: map[string]string{"app/b.txt": "b\n"}}) + own := strings.Fields(f.git("rev-list", "--reverse", mc+"^1.."+mc+"^2")) + tc.land(f, mc, own) + v := verdictOn(t, f, nil, "release-1.1", 5) + switch { + case tc.carried == "" && v.rule != 0: + t.Errorf("verdict = rule %d (%s), want it to qualify", v.rule, v.reason) + case tc.carried != "" && (v.rule != ruleOnLine || !strings.HasPrefix(v.reason, tc.carried)): + t.Errorf("verdict = rule %d (%s), want rule 1 with %q", v.rule, v.reason, tc.carried) + } + }) + } +} + +// What a pull request's author writes reaches the line with every commit the +// batch picks and with the merge message it carries. None of it makes another +// original count as carried: not an -x line, a Backported-from trailer or a +// Backport of naming it, not at the end of the message where the line git +// appends lands in the same trailer block, and not an -x line naming one of +// the other original's own commits. The line is read as after the batch-only +// day, as a batch made after it leaves it. +func TestPresenceCannotBeClaimedByText(t *testing.T) { + type world struct { + f *fixture + mc5, c5 string + } + claims := []struct { + name string + claim func(w *world) string + }{ + {"an -x line naming the merge commit", func(w *world) string { return "(cherry picked from commit " + w.mc5 + ")" }}, + {"an -x line naming its own commit", func(w *world) string { return "(cherry picked from commit " + w.c5 + ")" }}, + {"a Backported-from trailer", func(w *world) string { return batchTrailer + ": " + w.mc5 }}, + {"a Backport of", func(w *world) string { return "Backport of #5" }}, + {"all of them after a sign-off", func(w *world) string { + return "Signed-off" + "-by: " + contributor + "\n(cherry picked from commit " + w.mc5 + ")\n(cherry picked from commit " + w.c5 + ")\n" + batchTrailer + ": " + w.mc5 + }}, + } + for _, where := range []string{"commit message", "pull request body"} { + for _, tc := range claims { + t.Run(where+": "+tc.name, func(t *testing.T) { + f := newFixture(t) + f.lines() + // #5 conflicts on the line, so the batch defers it. + f.onLine("release-1.1", "fix(chart): a line-only value", map[string]string{"chart/values.yaml": "replicas: 3\nimage: app:1\n"}) + w := &world{f: f} + w.mc5 = f.pr(5, "fix(chart): five", "", map[string]string{"chart/values.yaml": "replicas: 5\nimage: app:1\n"}) + w.c5 = f.git("rev-parse", w.mc5+"^2") + claim := tc.claim(w) + msg, body := "fix(app): six\n\n"+claim, "" + if where == "pull request body" { + msg, body = "fix(app): six", "Six.\n\n"+claim + } + f.prCommits(6, "fix(app): six", body, change{files: map[string]string{"app/six.txt": "6\n"}, message: msg}) + t.Setenv("GIT_COMMITTER_DATE", "2026-10-27T06:00:00Z") + + // The batch picks #6; on the open batch pull request the text + // claims nothing for #5. + gh := &fakeGH{} + if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--push"); code != 0 { + t.Fatalf("run --push = %d\n%s", code, stderr) + } + f.git("switch", "-q", "main") + gh.prs = []pullRequest{f.batchPR(90, "release-1.1", batchBranch1, gh.bodies[0])} + if v := verdictOn(t, f, gh, "release-1.1", 6); v.onBatch == "" { + t.Fatal("#6 is not on the batch") + } + if v := verdictOn(t, f, gh, "release-1.1", 5); v.onBatch != "" { + t.Errorf("#5 is on the batch in %.12s, want nowhere", v.onBatch) + } + + // Nor on the line, once the line takes the batch. + f.git("push", "-q", "origin", f.remoteHead(batchBranch1)+":refs/heads/release-1.1") + if v := verdictOn(t, f, nil, "release-1.1", 6); v.rule != ruleOnLine { + t.Fatalf("#6 = rule %d (%s), want it on the line", v.rule, v.reason) + } + if v := verdictOn(t, f, nil, "release-1.1", 5); v.rule != 0 { + t.Errorf("#5 = rule %d (%s), want it still to qualify", v.rule, v.reason) + } + if code, stdout, stderr := f.exec(nil, "check", "--line", "release-1.1"); code != 1 || !strings.Contains(stdout, "/pull/5 ") { + t.Errorf("check = %d, want #5 missing:\n%s\n%s", code, stdout, stderr) + } + }) + } + } +} + +// verify passes a batch the run built and fails one with an original that is +// not in the batch's shape, reading nothing from GitHub when given the head. +func TestVerify(t *testing.T) { + type world struct { + f *fixture + gh *fakeGH + head string + mc5 string + sq6 string + } + setup := func(t *testing.T) *world { + f := newFixture(t) + f.lines() + w := &world{f: f} + w.mc5 = f.prCommits(5, "fix(app): five", "", + change{files: map[string]string{"app/five.txt": "5\n"}}, + change{files: map[string]string{"app/five.txt": "5, done\n"}}) + w.sq6 = f.squash(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + f.pr(7, "fix(app): seven", "", map[string]string{"app/seven.txt": "7\n"}) + w.gh = &fakeGH{} + w.head = openBatch(t, f, w.gh) + return w + } + // on adds a commit with message and files on top of the batch head. + on := func(w *world, message string, files map[string]string) string { + w.f.git("switch", "-q", "--detach", w.head) + w.f.apply(files) + w.f.git("commit", "-q", "--allow-empty", "-m", message) + sha := w.f.git("rev-parse", "HEAD") + w.f.git("switch", "-q", "main") + return sha + } + cases := []struct { + name string + head func(w *world) string + refusal string + }{ + {name: "the batch as the run built it", head: func(w *world) string { return w.head }}, + { + name: "an original picked as one commit with -m 1", + head: func(w *world) string { + return on(w, "fix(app): five (#5)\n\n(cherry picked from commit "+w.mc5+")", map[string]string{"app/five.txt": "5, again\n"}) + }, + refusal: "picks the merge commit of #5 as one commit", + }, + { + name: "a commit that is no original", + head: func(w *world) string { + return on(w, "fix(ci): adjust for the line", map[string]string{"ci.txt": "x\n"}) + }, + refusal: "ends in no (cherry picked from commit", + }, + { + name: "an original carried twice", + head: func(w *world) string { + own := strings.Fields(w.f.git("rev-list", "--reverse", w.mc5+"^1.."+w.mc5+"^2")) + p := on(w, "again\n\n(cherry picked from commit "+own[1]+")", map[string]string{"app/five.txt": "5, done again\n"}) + w.f.git("switch", "-q", "--detach", w.head) + w.f.git("merge", "-q", "--no-ff", "-m", "fix(app): five (#5)\n\n"+batchTrailer+": "+w.mc5, p) + sha := w.f.git("rev-parse", "HEAD") + w.f.git("switch", "-q", "main") + return sha + }, + refusal: "carries #5 again", + }, + { + name: "a squash-merged original carried as a merge", + head: func(w *world) string { + p := on(w, "six\n\n(cherry picked from commit "+w.sq6+")", map[string]string{"app/six.txt": "6, again\n"}) + w.f.git("switch", "-q", "--detach", w.head) + w.f.git("merge", "-q", "--no-ff", "-m", "fix(app): six (#6)\n\n"+batchTrailer+": "+w.sq6, p) + sha := w.f.git("rev-parse", "HEAD") + w.f.git("switch", "-q", "main") + return sha + }, + refusal: "which main took as one commit", + }, + { + name: "a merge of the line into the batch", + head: func(w *world) string { + line := w.f.onLine("release-1.1", "fix(chart): on the line", map[string]string{"chart/values.yaml": "replicas: 2\nimage: app:1\n"}) + w.f.git("switch", "-q", "--detach", w.head) + w.f.git("merge", "-q", "--no-ff", "-m", "Merge branch 'release-1.1' into the batch", line) + sha := w.f.git("rev-parse", "HEAD") + w.f.git("switch", "-q", "main") + return sha + }, + refusal: "with 0 " + batchTrailer + " trailers", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + w := setup(t) + head := tc.head(w) + // GitHub is not asked: a failing fake would fail the run. + gh := &fakeGH{err: errString("gh: not to be asked")} + code, stdout, stderr := w.f.exec(gh, "verify", "--line", "release-1.1", "--head", head) + switch { + case tc.refusal == "" && code != 0: + t.Errorf("verify = %d\n%s\n%s", code, stdout, stderr) + case tc.refusal != "" && (code != 1 || !strings.Contains(stdout, tc.refusal)): + t.Errorf("verify = %d, want 1 with %q:\n%s\n%s", code, tc.refusal, stdout, stderr) + } + }) + } + + t.Run("the open batch pull request", func(t *testing.T) { + w := setup(t) + code, stdout, stderr := w.f.exec(w.gh, "verify", "--line", "release-1.1") + if code != 0 || !strings.Contains(stdout, "3 units at "+w.head[:12]) { + t.Errorf("verify = %d\n%s\n%s", code, stdout, stderr) + } + if code, stdout, _ := w.f.exec(&fakeGH{}, "verify", "--line", "release-1.1"); code != 0 || !strings.Contains(stdout, "nothing to verify") { + t.Errorf("verify with no batch open = %d, %q", code, stdout) + } + }) + t.Run("a head that is not here", func(t *testing.T) { + w := setup(t) + if code, _, stderr := w.f.exec(w.gh, "verify", "--line", "release-1.1", "--head", strings.Repeat("ab", 20)); code != 2 || !strings.Contains(stderr, "fetch it first") { + t.Errorf("verify = %d (%s), want 2", code, stderr) + } + }) +} + +// A pick that lands among lines the line changed is the same change, and the +// body does not call it changed; one whose change differs is called so. +func TestSummaryCallsOnlyChangedPicksChanged(t *testing.T) { + f := newFixture(t) + f.release("release-1.0") + f.squash(2, "chore(app): a file to change", "", map[string]string{"app/ctx.txt": "a\nb\nc\nd\ne\n"}) + f.pr(1, "feat(app): something for 1.1", "", map[string]string{"app/feature.txt": "1.1\n"}) + f.release("release-1.1") + f.onLine("release-1.1", "fix(app): a line-only change", map[string]string{"app/ctx.txt": "A\nb\nc\nd\ne\n"}) + f.pr(5, "fix(app): five", "", map[string]string{"app/ctx.txt": "a\nb\nC\nd\ne\n"}) + code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1") + if code != 0 { + t.Fatalf("run = %d\n%s", code, stderr) + } + if !strings.Contains(stdout, "`fix(app): five`, 1 commit\n") { + t.Errorf("a pick git only fit to its place is called changed:\n%s", stdout) + } +} diff --git a/cmd/backport-batch/test-inputs.txt b/cmd/backport-batch/test-inputs.txt new file mode 100644 index 000000000..4262b0e1f --- /dev/null +++ b/cmd/backport-batch/test-inputs.txt @@ -0,0 +1,26 @@ +# Every path whose change can change the result of +# `go test ./cmd/backport-batch/...`. The plan job in +# .github/workflows/pull-requests.yaml runs those tests when, and only when, the +# pull request touches one of these paths. +# +# One repository-relative path per line. A trailing slash names a directory and +# matches everything below it; anything else matches that file alone. Blank lines +# and lines starting with # are ignored. +# +# TestInputsListed in inputs_test.go keeps this list in step with the code: it +# fails when the tests' in-repo package dependencies (go list -deps -test) or the +# docs pages they read are missing from it. + +cmd/backport-batch/ +go.mod +go.sum + +# In-repo packages the tool and its tests import. +internal/apigate/ +pkg/apis/apps/v1alpha1/ +pkg/apis/apps/validation/ +pkg/config/ + +# Pages the tests read from the tree. +docs/release/backports.md +docs/release/backport-tasks/ diff --git a/cmd/backport-batch/verify.go b/cmd/backport-batch/verify.go new file mode 100644 index 000000000..03b0e8955 --- /dev/null +++ b/cmd/backport-batch/verify.go @@ -0,0 +1,148 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package main + +import ( + "fmt" + "strings" +) + +// verify checks every original a batch carries, from the line's head to the +// batch head, against the shape the batch carries it in: what fold checks for +// one resolution, for all of them and for the clean picks too. fold runs only +// where someone resolved a conflict and chose to run it; CI runs verify on +// every push to a batch pull request. +// +// With --head it reads that commit and nothing from GitHub, which is how CI +// runs it: the tool built from main, the batch head fetched as data. +func (a *app) verify(args []string) int { + fs := a.flags("verify") + lineArg := fs.String("line", "", "release line, release-X.Y") + headArg := fs.String("head", "", "the batch head to verify (default: the head of the open batch PR)") + if err := parse(fs, args); err != nil { + return 2 + } + l, err := parseLine(*lineArg) + if err != nil { + return a.fail(err) + } + if *headArg != "" { + if err := checkSHA(*headArg); err != nil { + return a.fail(fmt.Errorf("--head: %w", err)) + } + } + if err := fetch(); err != nil { + return a.fail(err) + } + b, err := shapeOf(l) + if err != nil { + return a.fail(err) + } + head := *headArg + if head == "" { + prs, err := a.gh.openPulls(l.branch()) + if err != nil { + return a.fail(err) + } + pr, warnings, err := batchPull(a.gh, prs, l) + for _, w := range warnings { + a.warn("%s", w) + } + if err != nil { + return a.fail(err) + } + if pr == nil { + _, _ = fmt.Fprintf(a.stdout, "%s: no batch pull request is open; nothing to verify\n", l.branch()) + return 0 + } + if head, err = batchHead(pr); err != nil { + return a.fail(err) + } + } else if have, err := lookup(head); err != nil { + return a.fail(err) + } else if have == "" { + return a.fail(fmt.Errorf("--head %.12s is not in this repository; fetch it first", head)) + } + units, err := batchUnits(head, b.lineHead) + if err != nil { + return a.fail(err) + } + seen := map[*verdict]string{} + var refused []string + for _, u := range units { + why, v, err := checkUnit(b, u) + if err != nil { + return a.fail(err) + } + if why == "" && seen[v] != "" { + why = fmt.Sprintf("carries #%d again, which %.12s already carries", v.o.number, seen[v]) + } + if why == "" { + omitted, _, err := b.omittedEffects(v, u.parents[0], u.commit) + if err != nil { + return a.fail(err) + } + if len(omitted) > 0 { + why = leftOut(v, l, omitted) + } + } + if why != "" { + refused = append(refused, why) + _, _ = fmt.Fprintf(a.stdout, "refused %.12s: %s\n", u.commit, why) + continue + } + seen[v] = u.commit + n := len(u.picks) + if !u.merge() { + n = 1 + } + _, _ = fmt.Fprintf(a.stdout, "ok %.12s #%d, %d %s\n", u.commit, v.o.number, n, plural(n, "commit")) + } + if len(refused) > 0 { + _, _ = fmt.Fprintf(a.stdout, "%s: %d of %d units at %.12s are not originals in the batch's shape\n", l.branch(), len(refused), len(units), head) + return 1 + } + _, _ = fmt.Fprintf(a.stdout, "%s: %d %s at %.12s, each one original in the batch's shape\n", l.branch(), len(units), plural(len(units), "unit"), head) + return 0 +} + +// shapeOf reads what verify needs of a line, from git alone: its head, and +// every pull request merged into main since it branched, unjudged. +func shapeOf(l line) (*batch, error) { + b := &batch{line: l} + var err error + if b.lineHead, err = resolve("refs/remotes/" + remote + "/" + l.branch()); err != nil { + return nil, err + } + if b.mainHead, err = resolve("refs/remotes/" + remote + "/main"); err != nil { + return nil, err + } + out, err := git("merge-base", "--end-of-options", b.mainHead, b.lineHead) + if err != nil { + return nil, fmt.Errorf("%s shares no history with main: %w", l.branch(), err) + } + b.base = strings.TrimSpace(out) + merges, other, err := mainMerges(b.base, b.mainHead) + if err != nil { + return nil, err + } + b.other = other + for _, o := range merges { + b.verdicts = append(b.verdicts, &verdict{o: o}) + } + return b, nil +} diff --git a/cmd/backport-batch/wait_test.go b/cmd/backport-batch/wait_test.go new file mode 100644 index 000000000..35dd5c1d6 --- /dev/null +++ b/cmd/backport-batch/wait_test.go @@ -0,0 +1,236 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package main + +import ( + "strings" + "testing" +) + +// chainWorld has #5 conflict on the line and change a shared line, and #7 +// change that line again: #7 builds on #5. +func chainWorld(t *testing.T) (*fixture, string) { + t.Helper() + f := newFixture(t) + f.squash(2, "chore: five and shared", "", map[string]string{"app/five.txt": "old\n", "app/shared.txt": appFile}) + f.lines() + f.onLine("release-1.1", "fix(app): five, the line's way", map[string]string{"app/five.txt": "line\n"}) + mc5 := f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "five\n", "app/shared.txt": strings.Replace(appFile, "two", "TWO", 1)}) + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + f.pr(7, "fix(app): seven", "", map[string]string{"app/shared.txt": strings.Replace(appFile, "two", "TWO!", 1)}) + return f, mc5 +} + +// An original that builds on a deferred conflict waits for it: check warns, +// notify lists it after the conflict, and once the conflict lands, the next +// run picks it. +func TestWaitForADeferredDependency(t *testing.T) { + f, mc5 := chainWorld(t) + gh := &fakeGH{} + code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--push") + if code != 0 { + t.Fatalf("run --push = %d\n%s", code, stderr) + } + if !strings.Contains(stdout, `{"original":7,"files":[],"needs":[5]}`) || !strings.Contains(stdout, "### Waiting on another original") { + t.Errorf("#7 does not wait on #5:\n%s", stdout) + } + f.git("switch", "-q", "main") + reopen(f, gh) + code, stdout, stderr = f.exec(gh, "check", "--line", "release-1.1") + if code != 0 || !strings.Contains(stderr, "warning: #7 waits on #5, a deferred conflict on #90: https://github.com/cozystack/cozystack/pull/7 ") { + t.Errorf("check = %d, want a warning that #7 waits on #5:\n%s\n%s", code, stdout, stderr) + } + code, stdout, _ = f.exec(gh, "notify", "--line", "release-1.1", "--push") + if code != 0 || !strings.Contains(gh.issueComments[len(gh.issueComments)-1].Body, "- [#7](https://github.com/cozystack/cozystack/pull/7), after [#5](https://github.com/cozystack/cozystack/pull/5)") { + t.Errorf("notify = %d, want #7 listed after #5:\n%s\n%v", code, stdout, gh.issueComments) + } + // The batch merges, and #5 lands on the line by hand, resolved: the + // next batch picks #7. + mergeBatch(f, gh) + f.onLine("release-1.1", "fix(app): five (#5)\n\n(cherry picked from commit "+mc5+")", map[string]string{"app/five.txt": "five\n", "app/shared.txt": strings.Replace(appFile, "two", "TWO", 1)}) + code, stdout, stderr = f.exec(gh, "run", "--line", "release-1.1", "--continue") + if code != 0 || !strings.Contains(stdout, `"picked":[7]`) { + t.Errorf("run --continue after #5 landed = %d, want #7 picked:\n%s\n%s", code, stdout, stderr) + } +} + +// Of several prerequisites still to come, the strongest decides: one not on +// the line at all, then one waiting for a maintainer, then a conflict or a +// deferral, then one rule 6 holds; a chain inherits what its end decides. +func TestWaitReduction(t *testing.T) { + t.Run("a conflict and a workflow wait", func(t *testing.T) { + f := newFixture(t) + f.squash(2, "chore: files", "", map[string]string{"app/five.txt": "old\n", "app/a.txt": appFile, "app/b.txt": appFile}) + f.lines() + f.onLine("release-1.1", "fix(app): five, the line's way", map[string]string{"app/five.txt": "line\n"}) + f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "five\n", "app/a.txt": strings.Replace(appFile, "two", "TWO", 1)}) + f.pr(6, "fix(ci): six", "", map[string]string{".github/workflows/six.yaml": "on: push\n", "app/b.txt": strings.Replace(appFile, "two", "TWO", 1)}) + f.pr(7, "fix(app): seven", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!", 1), "app/b.txt": strings.Replace(appFile, "two", "TWO!", 1)}) + f.pr(8, "fix(app): eight", "", map[string]string{"app/eight.txt": "8\n"}) + gh := &fakeGH{} + if code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--no-workflow-files", "--push"); code != 0 || !strings.Contains(stdout, `{"original":7,"files":[],"needs":[6]}`) { + t.Fatalf("run = %d, want #7 waiting on #6 alone:\n%s\n%s", code, stdout, stderr) + } + f.git("switch", "-q", "main") + reopen(f, gh) + if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1", "--cut"); code != 1 || !strings.Contains(stdout, "#7 waits on #6, which changes .github/workflows/ and waits on batch PR #90 for a maintainer") { + t.Errorf("check --cut = %d, want #7 to hold the cut:\n%s\n%s", code, stdout, stderr) + } + if code, stdout, _ := f.exec(gh, "notify", "--line", "release-1.1"); code != 0 || !strings.Contains(stdout, "2 originals on #90 change .github/workflows/ or wait on one that does") { + t.Errorf("notify = %d, want #7 among the waits:\n%s", code, stdout) + } + }) + t.Run("a conflict and one not on the line", func(t *testing.T) { + f := newFixture(t) + f.squash(2, "chore: files", "", map[string]string{"app/five.txt": "old\n", "app/a.txt": appFile, "app/b.txt": appFile}) + f.lines() + f.onLine("release-1.1", "fix(app): five, the line's way", map[string]string{"app/five.txt": "line\n"}) + f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "five\n", "app/a.txt": strings.Replace(appFile, "two", "TWO", 1)}) + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + gh := &fakeGH{} + if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--push"); code != 0 { + t.Fatalf("run = %d\n%s", code, stderr) + } + f.git("switch", "-q", "main") + reopen(f, gh) + f.pr(9, "fix(app): nine", "", map[string]string{"app/b.txt": strings.Replace(appFile, "two", "TWO", 1)}) + f.pr(10, "fix(app): ten", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!", 1), "app/b.txt": strings.Replace(appFile, "two", "TWO!", 1)}) + if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 1 || !strings.Contains(stdout, "/pull/10 fix(app): ten (it waits on #9, which is not on the line either)") { + t.Errorf("check = %d, want #10 to fail it, waiting on #9:\n%s\n%s", code, stdout, stderr) + } + }) + t.Run("a prerequisite on the open batch", func(t *testing.T) { + f := newFixture(t) + f.squash(2, "chore: files", "", map[string]string{"app/a.txt": appFile}) + f.lines() + f.pr(5, "fix(app): five", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO", 1)}) + f.pr(7, "fix(app): seven", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!", 1)}) + gh := &fakeGH{} + if code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--push"); code != 0 || !strings.Contains(stdout, `"picked":[5,7]`) { + t.Fatalf("run = %d, want #5 and #7 picked:\n%s\n%s", code, stdout, stderr) + } + f.git("switch", "-q", "main") + reopen(f, gh) + if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1", "--cut"); code != 1 || !strings.Contains(stdout, "#5 is only on open batch PR #90") || strings.Contains(stdout+stderr, "waits on") { + t.Errorf("check --cut = %d, want #5 and #7 only on the batch and no wait:\n%s\n%s", code, stdout, stderr) + } + }) + t.Run("a direct reason", func(t *testing.T) { + f := featWorld(t) + gh := &fakeGH{} + openBatch(t, f, gh) + if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--defer", "5", "--reason", "needs the tap", "--push"); code != 0 { + t.Fatalf("run --defer = %d\n%s", code, stderr) + } + reopen(f, gh) + if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 0 || !strings.Contains(stderr, "warning: deferred on #90 to the next batch: https://github.com/cozystack/cozystack/pull/5 ") || strings.Contains(stderr, "parked") { + t.Errorf("check = %d, want #5 deferred for its reason, not parked:\n%s\n%s", code, stdout, stderr) + } + }) + t.Run("a prerequisite rule 6 holds", func(t *testing.T) { + f := newFixture(t) + f.squash(2, "chore: files", "", map[string]string{"app/a.txt": appFile}) + f.lines() + f.pr(5, "fix(app): five", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO", 1)}) + mc7 := f.pr(7, "fix(app): seven", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!", 1), "app/seven.txt": "7\n"}) + f.onLine("release-1.1", "fix(app): seven (#7)\n\n(cherry picked from commit "+mc7+")", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!", 1), "app/seven.txt": "7\n"}) + if code, stdout, stderr := f.exec(nil, "check", "--line", "release-1.0"); code != 0 || !strings.Contains(stderr, "note: #7 waits on #5, which is not on release-1.1 yet") { + t.Errorf("check of release-1.0 = %d, want a note that #7 waits on #5:\n%s\n%s", code, stdout, stderr) + } + }) + t.Run("a chain", func(t *testing.T) { + f := newFixture(t) + f.squash(2, "chore: files", "", map[string]string{"app/a.txt": appFile}) + f.lines() + f.pr(4, "fix(app): four", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO", 1)}) + f.pr(5, "fix(app): five", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!", 1)}) + f.pr(7, "fix(app): seven", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!!", 1)}) + if code, stdout, stderr := f.exec(nil, "check", "--line", "release-1.1"); code != 1 || !strings.Contains(stdout, "/pull/7 fix(app): seven (it waits on #5, which is not on the line either)") { + t.Errorf("check = %d, want #7 failing it through #5:\n%s\n%s", code, stdout, stderr) + } + }) +} + +// run's report, check and notify give an original one disposition: a +// workflow original whose only missing dependency is a test waits for a +// maintainer, and one deferred for a reason stays deferred, though it +// builds on what never comes; neither is parked. +func TestDispositionOrderIsSharedByRunCheckNotify(t *testing.T) { + f := auxWorld(t) + f.pr(20, "feat(app): tap", "", map[string]string{"app/tap.go": appFile}) + f.pr(7, "fix(app): fix the tap", "", map[string]string{"app/tap.go": strings.Replace(appFile, "two", "TWO", 1)}) + gh := &fakeGH{} + if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--no-workflow-files", "--push"); code != 0 { + t.Fatalf("run = %d\n%s", code, stderr) + } + f.git("switch", "-q", "main") + reopen(f, gh) + code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--defer", "7", "--reason", "waits for the tap", "--push") + if code != 0 { + t.Fatalf("run --defer = %d\n%s", code, stderr) + } + if strings.Contains(stdout, `"parked":[{`) || !strings.Contains(stdout, `{"original":5,"files":[".github/workflows/release.yaml"],"workflows":true}`) || !strings.Contains(stdout, `{"original":7,"files":[],"reason":"waits for the tap"}`) { + t.Errorf("the report does not have #5 waiting and #7 deferred, unparked:\n%s", stdout) + } + reopen(f, gh) + code, stdout, stderr = f.exec(gh, "check", "--line", "release-1.1") + if code != 0 || strings.Contains(stderr, "parked") || !strings.Contains(stderr, "warning: waiting on #90 for a maintainer, since it changes .github/workflows/: https://github.com/cozystack/cozystack/pull/5 ") || !strings.Contains(stderr, "warning: deferred on #90 to the next batch: https://github.com/cozystack/cozystack/pull/7 ") { + t.Errorf("check = %d, want #5 waiting and #7 deferred:\n%s\n%s", code, stdout, stderr) + } + code, stdout, _ = f.exec(gh, "notify", "--line", "release-1.1") + if code != 0 || !strings.Contains(stdout, "1 originals on #90 change .github/workflows/") || strings.Contains(stdout, "parked") || strings.Contains(stdout, "conflicts") { + t.Errorf("notify = %d, want #5 waiting and nothing for #7:\n%s", code, stdout) + } +} + +// A never and a pending prerequisite together park. +func TestParkWinsOverWait(t *testing.T) { + f, _ := chainWorld(t) + f.pr(20, "feat(app): tap", "", map[string]string{"app/tap.go": appFile}) + f.pr(8, "fix(app): eight", "", map[string]string{"app/shared.txt": strings.Replace(appFile, "two", "TWO!!", 1), "app/tap.go": strings.Replace(appFile, "two", "TWO", 1)}) + code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1") + if code != 0 || !strings.Contains(stdout, `"kind":"dependency","needs":[20]`) || strings.Contains(stdout, `"original":8,"files":[],"needs"`) { + t.Errorf("run = %d, want #8 parked on #20, not waiting on #7:\n%s\n%s", code, stdout, stderr) + } +} + +// A prerequisite picked earlier in the same batch satisfies what builds on +// it, and so does one whose pick came out empty because an earlier pick +// already carried it: #4280 and #3938. +func TestDependencySatisfiedEarlierInTheBatch(t *testing.T) { + f := newFixture(t) + f.squash(2, "chore: files", "", map[string]string{"app/a.txt": appFile}) + f.lines() + f.pr(3, "fix(kafka): delete hooks", "", map[string]string{"app/hooks.yaml": appFile}) + f.pr(4, "fix(kafka): fix the delete hook", "", map[string]string{"app/hooks.yaml": strings.Replace(appFile, "two", "TWO", 1)}) + if code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1"); code != 0 || !strings.Contains(stdout, `"picked":[3,4]`) { + t.Errorf("run = %d, want #3 and #4 picked:\n%s\n%s", code, stdout, stderr) + } + + // #30 adds back the file #2 brought and a feat took away, so its pick + // comes out empty after #2's, and #4 builds on #30. + f = newFixture(t) + f.squash(2, "chore: files", "", map[string]string{"app/a.txt": appFile}) + f.lines() + f.pr(20, "fix(kafka): delete hooks, and two", "", map[string]string{"app/hooks.yaml": appFile, "app/two.txt": "2\n"}) + f.pr(21, "feat(kafka): no delete hooks", "", map[string]string{"app/hooks.yaml": ""}) + f.pr(30, "fix(kafka): delete hooks again", "", map[string]string{"app/hooks.yaml": appFile}) + f.pr(4, "fix(kafka): fix the delete hook", "", map[string]string{"app/hooks.yaml": strings.Replace(appFile, "two", "TWO", 1)}) + if code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1"); code != 0 || !strings.Contains(stdout, `"picked":[4,20]`) || strings.Contains(stdout, `"needs"`) { + t.Errorf("run with #30's pick empty = %d, want #4 picked:\n%s\n%s", code, stdout, stderr) + } +} diff --git a/cmd/backport-batch/workflows_test.go b/cmd/backport-batch/workflows_test.go new file mode 100644 index 000000000..97547f6b5 --- /dev/null +++ b/cmd/backport-batch/workflows_test.go @@ -0,0 +1,254 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package main + +import ( + "fmt" + "slices" + "strings" + "testing" +) + +// workflowWorld has #5 change a workflow and #6 change the app and a file +// under .github/ that is no workflow. +func workflowWorld(t *testing.T) *fixture { + t.Helper() + f := newFixture(t) + f.lines() + f.pr(5, "fix(ci): five", "", map[string]string{".github/workflows/five.yaml": "on: push\n", "app/five.txt": "5\n"}) + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n", ".github/renovate.json": "{}\n"}) + return f +} + +// With --no-workflow-files, as the scheduled batch runs, an original that +// changes a workflow is left to a maintainer, with its workflow files, and is +// neither a conflict nor deferred with a reason. Without the flag it is picked +// like any other. +func TestRunLeavesWorkflowChangesToAMaintainer(t *testing.T) { + l, _ := parseLine("release-1.1") + f := workflowWorld(t) + code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1", "--no-workflow-files") + if code != 0 { + t.Fatalf("run --no-workflow-files = %d\n%s", code, stderr) + } + if got := f.subjects("origin/release-1.1", "HEAD"); !slices.Equal(got, []string{"fix(app): six (#6)"}) { + t.Errorf("picked %q, want only #6", got) + } + deferred, err := parseDeferred(stdout, l) + if e := deferred[5]; err != nil || len(deferred) != 1 || !e.Workflows || e.Reason != "" || e.Commit != "" || !slices.Equal(e.Files, []string{".github/workflows/five.yaml"}) { + t.Errorf("deferred = %+v, %v; want #5 waiting with its workflow file", deferred, err) + } + for _, want := range []string{"### Waiting for a maintainer", "[#5](", "`.github/workflows/five.yaml`", "#changes-to-workflows"} { + if !strings.Contains(stdout, want) { + t.Errorf("the body lacks %q:\n%s", want, stdout) + } + } + if strings.Contains(stdout, "### Deferred") { + t.Errorf("the body lists #5 as deferred:\n%s", stdout) + } + if !strings.Contains(stderr, "waiting for a maintainer: https://github.com/cozystack/cozystack/pull/5 fix(ci): five changes .github/workflows/five.yaml") { + t.Errorf("the run does not say #5 waits:\n%s", stderr) + } + + f = workflowWorld(t) + code, stdout, stderr = f.exec(nil, "run", "--line", "release-1.1") + if code != 0 { + t.Fatalf("run = %d\n%s", code, stderr) + } + if got := f.subjects("origin/release-1.1", "HEAD"); !slices.Equal(got, []string{"fix(ci): five (#5)", "fix(app): six (#6)"}) { + t.Errorf("without the flag picked %q, want #5 and #6", got) + } + if strings.Contains(stdout, "Waiting for a maintainer") { + t.Errorf("without the flag the body has something wait:\n%s", stdout) + } +} + +// Waiting is no way off the line: check lists the original until it is on +// it, the scheduled run that continues the batch keeps it waiting rather than +// trying it as a conflict, notify lists it apart from the conflicts, and a +// maintainer's own run picks it onto the open batch. +func TestWorkflowChangesWaitUntilOnTheLine(t *testing.T) { + f := workflowWorld(t) + gh := &fakeGH{} + if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--no-workflow-files"); code != 0 { + t.Fatalf("run = %d\n%s", code, stderr) + } + f.git("switch", "-q", "main") + if code, stdout, _ := f.exec(gh, "check", "--line", "release-1.1"); code != 1 || !strings.Contains(stdout, "/pull/5 ") { + t.Errorf("check with no batch open = %d, %q; want #5 missing", code, stdout) + } + + if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--no-workflow-files", "--push"); code != 0 { + t.Fatalf("run --push = %d\n%s", code, stderr) + } + f.git("switch", "-q", "main") + reopen(f, gh) + code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1") + if code != 0 || !strings.Contains(stderr, "warning: waiting on #90 for a maintainer, since it changes .github/workflows/: https://github.com/cozystack/cozystack/pull/5 ") { + t.Errorf("check = %d, %q; want 0 and a warning about #5:\n%s", code, stdout, stderr) + } + code, stdout, _ = f.exec(gh, "check", "--line", "release-1.1", "--cut") + if code != 1 || !strings.Contains(stdout, "#5 changes .github/workflows/ and waits on batch PR #90 for a maintainer") { + t.Errorf("check --cut = %d, %q; want #5 to stop the cut", code, stdout) + } + + code, stdout, stderr = f.exec(gh, "notify", "--line", "release-1.1", "--push") + if code != 0 || !strings.Contains(stdout, "1 originals on #90 change .github/workflows/ and wait for a maintainer") || strings.Contains(stdout, "deferred conflicts") { + t.Errorf("notify = %d, %q; want #5 for a maintainer and no conflict\n%s", code, stdout, stderr) + } + notes := slices.DeleteFunc(slices.Clone(gh.issueComments), func(c issueComment) bool { return !strings.HasPrefix(c.Body, notifyMarker) }) + if len(notes) != 1 || !strings.Contains(notes[0].Body, "[#5](") || !strings.Contains(notes[0].Body, "#changes-to-workflows") || strings.Contains(notes[0].Body, "These conflicts") { + t.Errorf("the comment does not list #5 for a maintainer: %+v", gh.issueComments) + } + + f.pr(7, "fix(app): seven", "", map[string]string{"app/seven.txt": "7\n"}) + code, stdout, stderr = f.exec(gh, "run", "--line", "release-1.1", "--continue", "--no-workflow-files", "--push") + if code != 0 { + t.Fatalf("run --continue = %d\n%s", code, stderr) + } + l, _ := parseLine("release-1.1") + if deferred, err := parseDeferred(stdout, l); err != nil || !deferred[5].Workflows || len(deferred) != 1 { + t.Errorf("the continued body has %+v, %v; want #5 still waiting", deferred, err) + } + if got := f.subjects("origin/release-1.1", f.remoteHead(batchBranch1)); !slices.Equal(got, []string{"fix(app): six (#6)", "fix(app): seven (#7)"}) { + t.Errorf("the continued batch carries %q", got) + } + + f.git("switch", "-q", "main") + reopen(f, gh) + if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--push"); code != 0 { + t.Fatalf("a maintainer's run = %d\n%s", code, stderr) + } + if got := f.subjects("origin/release-1.1", f.remoteHead(batchBranch1)); !slices.Equal(got, []string{"fix(app): six (#6)", "fix(app): seven (#7)", "fix(ci): five (#5)"}) { + t.Errorf("after a maintainer's run the batch carries %q, want #5 on top", got) + } + f.git("switch", "-q", "main") + reopen(f, gh) + if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 0 || strings.Contains(stderr, "waiting") { + t.Errorf("check after the maintainer's run = %d, %q\n%s", code, stdout, stderr) + } +} + +// --defer keeps what waits as it is, and takes one out like any other original +// when a maintainer gives the reason. +func TestDeferKeepsWorkflowChangesWaiting(t *testing.T) { + f := workflowWorld(t) + f.pr(7, "fix(app): seven", "", map[string]string{"app/seven.txt": "7\n"}) + gh := &fakeGH{} + if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--no-workflow-files", "--push"); code != 0 { + t.Fatalf("run --push = %d\n%s", code, stderr) + } + f.git("switch", "-q", "main") + reopen(f, gh) + l, _ := parseLine("release-1.1") + code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--defer", "7", "--reason", "fails the app e2e", "--push") + if code != 0 { + t.Fatalf("run --defer 7 = %d\n%s", code, stderr) + } + if deferred, err := parseDeferred(stdout, l); err != nil || !deferred[5].Workflows || deferred[7].Reason != "fails the app e2e" || len(deferred) != 2 { + t.Errorf("after --defer 7 the body has %+v, %v; want #5 waiting and #7 deferred", deferred, err) + } + + f.git("switch", "-q", "main") + reopen(f, gh) + code, stdout, stderr = f.exec(gh, "run", "--line", "release-1.1", "--defer", "5", "--reason", "waits for the 1.1.4 workflow rework", "--push") + if code != 0 { + t.Fatalf("run --defer 5 = %d\n%s", code, stderr) + } + if deferred, err := parseDeferred(stdout, l); err != nil || deferred[5].Workflows || deferred[5].Reason == "" { + t.Errorf("after --defer 5 the body has %+v, %v; want #5 deferred with the reason", deferred, err) + } + f.git("switch", "-q", "main") + reopen(f, gh) + // #6 and #7 are still only on the batch, which fails the cut; #5 does not. + if code, stdout, _ := f.exec(gh, "check", "--line", "release-1.1", "--cut"); code != 1 || strings.Contains(stdout, "#5 changes") || !strings.Contains(stdout, "#6 is only on open batch PR #90") { + t.Errorf("check --cut = %d, %q; want 1 for #6 and #7 alone, a deferred #5 no longer waiting", code, stdout) + } + if code, _, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 0 || !strings.Contains(stderr, "deferred on #90 to the next batch: https://github.com/cozystack/cozystack/pull/5 ") { + t.Errorf("check = %d, want 0 with a warning about #5:\n%s", code, stderr) + } +} + +// A record that has an original wait and also names a failed commit or a +// reason is refused: it is one or the other. +func TestParseDeferredRefusesAMixedEntry(t *testing.T) { + l, _ := parseLine("release-1.1") + for _, entry := range []string{ + `{"original":5,"files":[],"workflows":true,"reason":"x"}`, + `{"original":5,"files":[],"workflows":true,"commit":"` + strings.Repeat("a", 40) + `"}`, + } { + body := deferredFence + "\n" + `{"line":"release-1.1","deferred":[` + entry + `]}` + "\n```\n" + if _, err := parseDeferred(body, l); err == nil { + t.Errorf("parseDeferred accepted %s", entry) + } + } +} + +// A pull request that changes a workflow in one commit and takes it back in a +// later one changes no workflow in its merge, but its first pick does, and +// the push carries that pick: it waits as well. +func TestRunHoldsAWorkflowChangeTakenBack(t *testing.T) { + f := newFixture(t) + f.lines() + f.prCommits(5, "fix(ci): five", "", + change{files: map[string]string{".github/workflows/five.yaml": "on: push\n"}}, + change{files: map[string]string{".github/workflows/five.yaml": "", "app/five.txt": "5\n"}}) + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1", "--no-workflow-files") + if code != 0 { + t.Fatalf("run = %d\n%s", code, stderr) + } + if got := f.subjects("origin/release-1.1", "HEAD"); !slices.Equal(got, []string{"fix(app): six (#6)"}) { + t.Errorf("picked %q, want only #6", got) + } + l, _ := parseLine("release-1.1") + if deferred, err := parseDeferred(stdout, l); err != nil || !deferred[5].Workflows || !slices.Equal(deferred[5].Files, []string{".github/workflows/five.yaml"}) { + t.Errorf("deferred = %+v, %v; want #5 waiting on its workflow file", deferred, err) + } +} + +// A rebuild keeps the count of workflow files a waiting original changes +// beyond those the block names. +func TestDeferKeepsTheWaitingFileCount(t *testing.T) { + f := newFixture(t) + f.lines() + files := map[string]string{"app/five.txt": "5\n"} + for i := range filesKept + 2 { + files[fmt.Sprintf(".github/workflows/w%02d.yaml", i)] = "on: push\n" + } + f.pr(5, "fix(ci): five", "", files) + f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"}) + f.pr(7, "fix(app): seven", "", map[string]string{"app/seven.txt": "7\n"}) + gh := &fakeGH{} + if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--no-workflow-files", "--push"); code != 0 { + t.Fatalf("run --push = %d\n%s", code, stderr) + } + f.git("switch", "-q", "main") + reopen(f, gh) + code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--defer", "7", "--reason", "fails the app e2e", "--push") + if code != 0 { + t.Fatalf("run --defer = %d\n%s", code, stderr) + } + l, _ := parseLine("release-1.1") + deferred, err := parseDeferred(stdout, l) + if e := deferred[5]; err != nil || !e.Workflows || len(e.Files) != filesKept || e.More != 2 { + t.Errorf("after the rebuild #5 is %d files and %d more, %v; want %d and 2", len(e.Files), e.More, err, filesKept) + } + if want := fmt.Sprintf("%d more", filesKept+2-filesListed); !strings.Contains(stdout, want) { + t.Errorf("the rebuilt body does not say %q:\n%s", want, stdout) + } +} diff --git a/cmd/backupstrategy-controller/main.go b/cmd/backupstrategy-controller/main.go index 634bb837f..119ae3007 100644 --- a/cmd/backupstrategy-controller/main.go +++ b/cmd/backupstrategy-controller/main.go @@ -212,6 +212,11 @@ func main() { } } + if err := mgr.Add(&backupcontroller.LegacyPasswordScrubber{Client: mgr.GetClient()}); err != nil { + setupLog.Error(err, "unable to add LegacyPasswordScrubber runnable") + os.Exit(1) + } + // The default Strategy CRs and the Velero BSL are Helm-templated behind // a lookup of the BucketClaim the same chart creates, so a fresh install // renders them empty — permanently, because helm-controller does not @@ -238,6 +243,7 @@ func main() { Namespace: os.Getenv("BACKUP_CREDENTIALS_HELMRELEASE_NAMESPACE"), Name: os.Getenv("BACKUP_CREDENTIALS_HELMRELEASE_NAME"), }, + CredentialsCOSISecretName: os.Getenv("BACKUP_CREDENTIALS_COSI_SECRET_NAME"), } if err := gate.SetupWithManager(mgr); err != nil { setupLog.Error(err, "unable to add DefaultObjectsGate runnable") diff --git a/cmd/check-readiness/main.go b/cmd/check-readiness/main.go index 50fb8aaf8..eb13f62e1 100644 --- a/cmd/check-readiness/main.go +++ b/cmd/check-readiness/main.go @@ -22,6 +22,7 @@ package main import ( "fmt" + "io" "os" "os/exec" "strconv" @@ -58,6 +59,10 @@ Options: --no-color Disable color output (auto-disabled on non-TTY) -h, --help Show this help +Exit status: 0 when everything is ready, 1 when something is not ready or a +write to stdout fails, 2 on invalid arguments. A closed pipe ends the process +with SIGPIPE, like other Unix tools. + ` // entry is a resource catalog item. @@ -181,10 +186,16 @@ func run(args []string) int { cfg.coreOnly = true i++ case "-h", "--help": - fmt.Fprint(os.Stdout, usageText) + if _, err := fmt.Fprint(os.Stdout, usageText); err != nil { + fmt.Fprintf(os.Stderr, "writing usage: %v\n", err) + return 1 + } return 0 case "--version": - fmt.Fprintln(os.Stdout, Version) + if _, err := fmt.Fprintln(os.Stdout, Version); err != nil { + fmt.Fprintf(os.Stderr, "writing version: %v\n", err) + return 1 + } return 0 default: fmt.Fprintf(os.Stderr, "Unknown argument: %s\n", a) @@ -213,14 +224,14 @@ func run(args []string) int { cfg.timeoutS = sec if cfg.waitMode { - return cfg.runWait() + return cfg.runWait(os.Stdout) } if cfg.watch { - cfg.runWatch() - return 0 + return cfg.runWatch(os.Stdout) + } + if writeOutput(os.Stdout, cfg.runOnce()) != nil { + return 1 } - out := cfg.runOnce() - fmt.Print(out) if cfg.foundIssues { return 1 } @@ -281,18 +292,31 @@ func parseTimeout(raw string) (int, bool) { return 0, false } -func (cfg *config) runWait() int { +// writeOutput prints a result. A result its reader never got fails the run, +// whatever the resources' state, since the exit code alone would vouch for it. +func writeOutput(w io.Writer, parts ...string) error { + for _, part := range parts { + if _, err := io.WriteString(w, part); err != nil { + fmt.Fprintf(os.Stderr, "writing output: %v\n", err) + return err + } + } + return nil +} + +func (cfg *config) runWait(w io.Writer) int { start := time.Now() for { output := cfg.runOnce() elapsed := int(time.Since(start).Seconds()) if strings.Contains(output, "All resources are ready.") { - fmt.Print(output) - fmt.Printf("%sReady after %ds.%s\n", cfg.green, elapsed, cfg.reset) + if writeOutput(w, output, fmt.Sprintf("%sReady after %ds.%s\n", cfg.green, elapsed, cfg.reset)) != nil { + return 1 + } return 0 } if elapsed >= cfg.timeoutS { - fmt.Print(output) + _ = writeOutput(w, output) fmt.Fprintf(os.Stderr, "%s%sTimeout after %ds — resources still not ready.%s\n", cfg.red, cfg.bold, cfg.timeoutS, cfg.reset) return 1 } @@ -300,13 +324,14 @@ func (cfg *config) runWait() int { } } -func (cfg *config) runWatch() { +func (cfg *config) runWatch(w io.Writer) int { for { output := cfg.runOnce() // Smooth clear is cosmetic and untested; just reprint. - fmt.Printf("%sLast updated: %s (refreshing every %ds, Ctrl+C to stop)%s\n", cfg.bold, time.Now().Format(time.UnixDate), cfg.interval, cfg.reset) - fmt.Println() - fmt.Print(output) + header := fmt.Sprintf("%sLast updated: %s (refreshing every %ds, Ctrl+C to stop)%s\n\n", cfg.bold, time.Now().Format(time.UnixDate), cfg.interval, cfg.reset) + if writeOutput(w, header, output) != nil { + return 1 + } time.Sleep(time.Duration(cfg.interval) * time.Second) } } diff --git a/cmd/check-readiness/main_test.go b/cmd/check-readiness/main_test.go new file mode 100644 index 000000000..9afddeedf --- /dev/null +++ b/cmd/check-readiness/main_test.go @@ -0,0 +1,68 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package main + +import ( + "io" + "os" + "strings" + "testing" +) + +func TestHelpAndVersionSucceedOnWritableStdout(t *testing.T) { + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = r.Close() }) + stdout := os.Stdout + os.Stdout = w + t.Cleanup(func() { os.Stdout = stdout }) + read := make(chan string, 1) + go func() { + b, _ := io.ReadAll(r) + read <- string(b) + }() + + for _, arg := range []string{"--help", "--version"} { + if code := run([]string{arg}); code != 0 { + t.Errorf("run(%s) = %d, want 0", arg, code) + } + } + _ = w.Close() + if out := <-read; !strings.Contains(out, "Usage:") || !strings.Contains(out, Version) { + t.Errorf("stdout = %q, want the usage text and the version", out) + } +} + +func TestHelpAndVersionFailOnUnwritableStdout(t *testing.T) { + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + _ = r.Close() + _ = w.Close() + stdout := os.Stdout + os.Stdout = w + t.Cleanup(func() { os.Stdout = stdout }) + + for _, arg := range []string{"--help", "--version"} { + if code := run([]string{arg}); code == 0 { + t.Errorf("run(%s) with an unwritable stdout = 0, want a failure", arg) + } + } +} diff --git a/cmd/cozypkg/cmd/add.go b/cmd/cozypkg/cmd/add.go index 0501fff63..8c5e22026 100644 --- a/cmd/cozypkg/cmd/add.go +++ b/cmd/cozypkg/cmd/add.go @@ -390,7 +390,7 @@ func createPackageFromFile(ctx context.Context, k8sClient client.Client, filePat } } - return fmt.Errorf("Package %s not found in file", packageName) + return fmt.Errorf("no Package %s in file", packageName) } func installPackage(ctx context.Context, k8sClient client.Client, packageSourceName string) error { @@ -529,12 +529,13 @@ func installPackage(ctx context.Context, k8sClient client.Client, packageSourceN return fmt.Errorf("failed to create Package %s: %w", pkgName, err) } if !created { - // The materializer auto-created the registration Package between the - // List above and this Create, so this run did not take ownership of it - // (its markers are not shed). Re-run so the reopen path pins it -- for a - // non-default variant to apply the choice, and for the default variant so - // a later privileged flip does not de-register this deliberate install. - _, _ = fmt.Fprintf(os.Stderr, "Package %s was just auto-registered; re-run 'cozypkg add %s' to install variant %q as your own\n", pkgName, pkgName, variant) + // A Package of this name appeared between the List above and this Create + // (a concurrent add, or a tap-managed registration left by an older + // Cozystack), so this run did not take ownership of it (its markers are + // not shed). Re-run so the reopen path pins it -- for a non-default + // variant to apply the choice, and for the default variant so a later + // privileged flip does not de-register this deliberate install. + _, _ = fmt.Fprintf(os.Stderr, "Package %s already exists; re-run 'cozypkg add %s' to install variant %q as your own\n", pkgName, pkgName, variant) continue } diff --git a/cmd/cozypkg/cmd/init.go b/cmd/cozypkg/cmd/init.go index 5970a864b..c6cf3c806 100644 --- a/cmd/cozypkg/cmd/init.go +++ b/cmd/cozypkg/cmd/init.go @@ -157,12 +157,13 @@ cozypkg validate . cozypkg push oci:///%s: `+"```"+` -## Connect (one command, on a Cozystack cluster) +## Connect and install (on a Cozystack cluster) `+"```bash"+` -cozypkg tap oci:///%s: +cozypkg tap oci:///%s: # connect the repository; installs nothing +cozypkg add %s # install the app `+"```"+` -`, psName, app, app, app, app, app), +`, psName, app, app, app, app, app, psName), }, } } diff --git a/cmd/cozypkg/cmd/list.go b/cmd/cozypkg/cmd/list.go index 6f7375026..4b08a602b 100644 --- a/cmd/cozypkg/cmd/list.go +++ b/cmd/cozypkg/cmd/list.go @@ -19,7 +19,7 @@ package cmd import ( "context" "fmt" - "os" + "io" "strings" "text/tabwriter" @@ -78,24 +78,25 @@ Use --components flag to show components on separate lines.`, } if listCmdFlags.installed { - return listPackages(ctx, k8sClient, listCmdFlags.components) + return listPackages(ctx, k8sClient, cmd.OutOrStdout(), listCmdFlags.components) } - return listPackageSources(ctx, k8sClient, listCmdFlags.components) + return listPackageSources(ctx, k8sClient, cmd.OutOrStdout(), listCmdFlags.components) }, } -func listPackageSources(ctx context.Context, k8sClient client.Client, showComponents bool) error { +func listPackageSources(ctx context.Context, k8sClient client.Client, out io.Writer, showComponents bool) error { var psList cozyv1alpha1.PackageSourceList if err := k8sClient.List(ctx, &psList); err != nil { return fmt.Errorf("failed to list PackageSources: %w", err) } // Use tabwriter for better column alignment - w := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', 0) - defer w.Flush() + w := tabwriter.NewWriter(out, 0, 0, 3, ' ', 0) // Print header - fmt.Fprintln(w, "NAME\tVARIANTS\tREADY\tSTATUS") + if _, err := fmt.Fprintln(w, "NAME\tVARIANTS\tREADY\tSTATUS"); err != nil { + return err + } // Print rows for _, ps := range psList.Items { @@ -123,24 +124,26 @@ func listPackageSources(ctx context.Context, k8sClient client.Client, showCompon } } - fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", ps.Name, variantsStr, ready, status) + if _, err := fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", ps.Name, variantsStr, ready, status); err != nil { + return err + } // Show components if requested if showComponents { for _, variant := range ps.Spec.Variants { for _, component := range variant.Components { - fmt.Fprintf(w, " %s\t%s\t\t\n", - fmt.Sprintf("%s.%s", ps.Name, component.Name), - variant.Name) + if _, err := fmt.Fprintf(w, " %s.%s\t%s\t\t\n", ps.Name, component.Name, variant.Name); err != nil { + return err + } } } } } - return nil + return w.Flush() } -func listPackages(ctx context.Context, k8sClient client.Client, showComponents bool) error { +func listPackages(ctx context.Context, k8sClient client.Client, out io.Writer, showComponents bool) error { var pkgList cozyv1alpha1.PackageList if err := k8sClient.List(ctx, &pkgList); err != nil { return fmt.Errorf("failed to list Packages: %w", err) @@ -160,11 +163,12 @@ func listPackages(ctx context.Context, k8sClient client.Client, showComponents b } // Use tabwriter for better column alignment - w := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', 0) - defer w.Flush() + w := tabwriter.NewWriter(out, 0, 0, 3, ' ', 0) // Print header - fmt.Fprintln(w, "NAME\tVARIANT\tREADY\tSTATUS") + if _, err := fmt.Fprintln(w, "NAME\tVARIANT\tREADY\tSTATUS"); err != nil { + return err + } // Print rows for _, pkg := range pkgList.Items { @@ -187,7 +191,9 @@ func listPackages(ctx context.Context, k8sClient client.Client, showComponents b } } - fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", pkg.Name, variant, ready, status) + if _, err := fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", pkg.Name, variant, ready, status); err != nil { + return err + } // Show components if requested if showComponents { @@ -197,9 +203,9 @@ func listPackages(ctx context.Context, k8sClient client.Client, showComponents b for _, v := range ps.Spec.Variants { if v.Name == variant { for _, component := range v.Components { - fmt.Fprintf(w, " %s\t%s\t\t\n", - fmt.Sprintf("%s.%s", pkg.Name, component.Name), - variant) + if _, err := fmt.Fprintf(w, " %s.%s\t%s\t\t\n", pkg.Name, component.Name, variant); err != nil { + return err + } } break } @@ -208,7 +214,7 @@ func listPackages(ctx context.Context, k8sClient client.Client, showComponents b } } - return nil + return w.Flush() } func init() { diff --git a/cmd/cozypkg/cmd/output_test.go b/cmd/cozypkg/cmd/output_test.go new file mode 100644 index 000000000..9eed21639 --- /dev/null +++ b/cmd/cozypkg/cmd/output_test.go @@ -0,0 +1,185 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package cmd + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "testing" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + "github.com/spf13/cobra" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + utilruntime "k8s.io/apimachinery/pkg/util/runtime" + "sigs.k8s.io/controller-runtime/pkg/client/fake" +) + +type failingWriter struct{} + +func (failingWriter) Write([]byte) (int, error) { return 0, errors.New("broken pipe") } + +func TestPrintReportReturnsWriteError(t *testing.T) { + r := &Report{Findings: []Finding{{Severity: SeverityError, Code: "X", Message: "m"}}} + if err := printReport(r, failingWriter{}); err == nil { + t.Fatal("printReport to an unwritable writer returned nil") + } +} + +// The table is buffered until the tabwriter flushes, so a failing reader shows +// up only as a Flush error, which list has to return. +func TestListReturnsWriteError(t *testing.T) { + s := runtime.NewScheme() + utilruntime.Must(cozyv1alpha1.AddToScheme(s)) + ps := &cozyv1alpha1.PackageSource{ObjectMeta: metav1.ObjectMeta{Name: "acme.app"}} + pkg := &cozyv1alpha1.Package{ObjectMeta: metav1.ObjectMeta{Name: "acme.app"}} + cl := fake.NewClientBuilder().WithScheme(s).WithObjects(ps, pkg).Build() + + for name, list := range map[string]func(io.Writer) error{ + "sources": func(w io.Writer) error { return listPackageSources(context.Background(), cl, w, true) }, + "packages": func(w io.Writer) error { return listPackages(context.Background(), cl, w, true) }, + } { + t.Run(name, func(t *testing.T) { + if err := list(failingWriter{}); err == nil { + t.Fatal("list to an unwritable writer returned nil") + } + var out strings.Builder + if err := list(&out); err != nil || !strings.Contains(out.String(), "acme.app") { + t.Fatalf("list = %v, output %q; want the row", err, out.String()) + } + }) + } +} + +// A command that cannot print its validation report still fails, and a +// refusal keeps validation as its reason with the write error joined to it. +func TestValidationCommandsReportUnwritableReport(t *testing.T) { + fakeFlux := t.TempDir() + if err := os.WriteFile(filepath.Join(fakeFlux, "flux"), []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", fakeFlux+string(os.PathListSeparator)+os.Getenv("PATH")) + + emptyRepo := func(t *testing.T) string { + root := t.TempDir() + if err := os.Mkdir(filepath.Join(root, "packages"), 0o755); err != nil { + t.Fatal(err) + } + return root + } + run := func(c *cobra.Command, args ...string) error { + c.SetOut(failingWriter{}) + t.Cleanup(func() { c.SetOut(nil) }) + return c.RunE(c, args) + } + push := func(root string) error { + pushCmdFlags.path = root + t.Cleanup(func() { pushCmdFlags.path = "." }) + return run(pushCmd, "oci://registry.example/acme/apps:v1") + } + + for _, tc := range []struct { + name string + run func(t *testing.T) error + refusal string + }{ + {name: "validate, valid", run: func(t *testing.T) error { return run(validateCmd, validRepo(t)) }}, + {name: "validate, invalid", run: func(t *testing.T) error { return run(validateCmd, emptyRepo(t)) }, refusal: "validation failed"}, + {name: "push, valid", run: func(t *testing.T) error { return push(validRepo(t)) }, refusal: "nothing was pushed"}, + {name: "push, invalid", run: func(t *testing.T) error { return push(emptyRepo(t)) }, refusal: "refusing to push"}, + {name: "tap, invalid", run: func(t *testing.T) error { return run(tapCmd, "oci://registry.example/acme/apps:v1") }, refusal: "refusing to tap"}, + } { + t.Run(tc.name, func(t *testing.T) { + err := tc.run(t) + if err == nil || !strings.Contains(err.Error(), "broken pipe") { + t.Fatalf("err = %v, want the write error", err) + } + if tc.refusal != "" && !strings.Contains(err.Error(), tc.refusal) { + t.Errorf("err = %v, want the refusal %q kept", err, tc.refusal) + } + }) + } +} + +// A tap that applied is reported as applied even when its summary is lost, +// and the lost summary still fails the command. +func TestTapSummaryReportsUnwritableOutput(t *testing.T) { + err := writeTapSummary(failingWriter{}, "oci://registry.example/acme/apps:v1", "tap-acme", []string{"acme.app"}) + if err == nil || !strings.Contains(err.Error(), "tap applied") || !strings.Contains(err.Error(), "broken pipe") { + t.Fatalf("err = %v, want the write error with the tap reported as applied", err) + } + var out strings.Builder + if err := writeTapSummary(&out, "oci://registry.example/acme/apps:v1", "tap-acme", []string{"acme.app"}); err != nil || !strings.Contains(out.String(), "cozypkg add acme.app") { + t.Fatalf("writeTapSummary = %v, output %q", err, out.String()) + } +} + +// A clean report has no finding lines, so its summary is its only write and +// alone decides the result. +func TestPrintReportReturnsSummaryWriteError(t *testing.T) { + if err := printReport(&Report{}, failingWriter{}); err == nil { + t.Fatal("printReport of a clean report to an unwritable writer returned nil") + } +} + +// push runs flux only after its status line was written, with validation +// skipped and after a report that was written. +func TestPushStopsBeforeFluxWhenItsStatusIsLost(t *testing.T) { + fakeFlux := t.TempDir() + ran := filepath.Join(t.TempDir(), "flux-ran") + if err := os.WriteFile(filepath.Join(fakeFlux, "flux"), []byte("#!/bin/sh\ntouch "+ran+"\n"), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", fakeFlux+string(os.PathListSeparator)+os.Getenv("PATH")) + for _, skip := range []bool{true, false} { + t.Run(fmt.Sprintf("skip-validate=%v", skip), func(t *testing.T) { + pushCmdFlags.path, pushCmdFlags.skipValidate = validRepo(t), skip + pushCmdFlags.source, pushCmdFlags.revision = "https://example.com/acme.git", "v1" + t.Cleanup(func() { + pushCmdFlags.path, pushCmdFlags.skipValidate = ".", false + pushCmdFlags.source, pushCmdFlags.revision = "", "" + }) + pushCmd.SetOut(&failOn{want: "Pushing"}) + t.Cleanup(func() { pushCmd.SetOut(nil) }) + err := pushCmd.RunE(pushCmd, []string{"oci://registry.example/acme/apps:v1"}) + if err == nil || !strings.Contains(err.Error(), "nothing was pushed") { + t.Fatalf("push losing its status = %v, want nothing pushed", err) + } + if _, statErr := os.Stat(ran); statErr == nil { + t.Fatal("flux ran after the status line was lost") + } + }) + } +} + +// failOn fails every write that contains want, and takes every other one. +type failOn struct { + want string + buf strings.Builder +} + +func (w *failOn) Write(p []byte) (int, error) { + if strings.Contains(string(p), w.want) { + return 0, errors.New("broken pipe") + } + return w.buf.Write(p) +} diff --git a/cmd/cozypkg/cmd/push.go b/cmd/cozypkg/cmd/push.go index 3f8e65cac..f60004034 100644 --- a/cmd/cozypkg/cmd/push.go +++ b/cmd/cozypkg/cmd/push.go @@ -17,6 +17,7 @@ limitations under the License. package cmd import ( + "errors" "fmt" "os" "os/exec" @@ -106,10 +107,13 @@ published. Source URL and revision are derived from git when not given.`, if err != nil { return err } - printReport(rep, cmd.OutOrStdout()) + printErr := printReport(rep, cmd.OutOrStdout()) if rep.HasErrors() { errs, _, _ := rep.Counts() - return fmt.Errorf("refusing to push: validation failed with %d error(s) (use --skip-validate to override)", errs) + return errors.Join(fmt.Errorf("refusing to push: validation failed with %d error(s) (use --skip-validate to override)", errs), printErr) + } + if printErr != nil { + return fmt.Errorf("nothing was pushed: writing the validation report failed: %w", printErr) } } @@ -129,7 +133,9 @@ published. Source URL and revision are derived from git when not given.`, } fluxArgs := buildFluxPushArgs(ref, packagesDir, source, revision, pushCmdFlags.reproducible) - fmt.Fprintf(cmd.OutOrStdout(), "Pushing %s (source=%s revision=%s)\n", ref, source, revision) + if _, err := fmt.Fprintf(cmd.OutOrStdout(), "Pushing %s (source=%s revision=%s)\n", ref, source, revision); err != nil { + return fmt.Errorf("nothing was pushed: writing the push status failed: %w", err) + } flux := exec.Command("flux", fluxArgs...) flux.Stdout = cmd.OutOrStdout() flux.Stderr = cmd.ErrOrStderr() diff --git a/cmd/cozypkg/cmd/tap.go b/cmd/cozypkg/cmd/tap.go index 107ab3ad8..2d5f7bb9b 100644 --- a/cmd/cozypkg/cmd/tap.go +++ b/cmd/cozypkg/cmd/tap.go @@ -18,6 +18,7 @@ package cmd import ( "context" + "errors" "fmt" "io" "regexp" @@ -55,6 +56,8 @@ var tapCmdFlags struct { kubeconfig string index string skipValidate bool + certIdentity string + certIssuer string } // ociRef is the parsed form of an oci:// reference. @@ -65,10 +68,28 @@ type ociRef struct { // Repo is the last path segment. Repo string Tag string + // Digest, when set, pins the exact content (sha256:<64 hex>). It takes + // precedence over Tag at pull time (Flux resolves digest before tag), so a + // digest-pinned reference never follows a moved tag. + Digest string +} + +// pullRef is the reference to pull: by digest when one is pinned (so the pull +// resolves the exact content regardless of where the tag points), otherwise by +// tag. +func (r ociRef) pullRef() string { + if r.Digest != "" { + return r.URL + "@" + r.Digest + } + return r.URL + ":" + r.Tag } var sanitizeName = regexp.MustCompile(`[^a-z0-9-]+`) +// ociDigestRe matches a full OCI manifest digest (sha256:<64 hex>), the same +// shape the platform source's "digest=" reference enforces. +var ociDigestRe = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`) + // parseOCIRef splits an oci:// reference into its URL (without tag), org, repo, // and tag. A missing tag defaults to "latest". func parseOCIRef(ref string) (ociRef, error) { @@ -77,11 +98,20 @@ func parseOCIRef(ref string) (ociRef, error) { } body := strings.TrimPrefix(ref, "oci://") - tag := "" - // Digest pins are not tag-addressable; tap is tag-based for now. - if strings.Contains(body, "@") { - return ociRef{}, fmt.Errorf("digest references are not supported by tap yet; use a tag (oci://host/org/repo:tag)") + // A digest pins the exact content (oci://host/org/repo@sha256:...). An + // optional tag may precede it and is then informational only. The digest + // must be a full sha256:<64 hex>, the same contract the platform source's + // "digest=" reference enforces. + digest := "" + if at := strings.LastIndex(body, "@"); at >= 0 { + digest = body[at+1:] + body = body[:at] + if !ociDigestRe.MatchString(digest) { + return ociRef{}, fmt.Errorf("invalid digest %q in reference %q: want sha256:<64 hex>", digest, ref) + } } + + tag := "" if colon := strings.LastIndex(body, ":"); colon >= 0 && !strings.Contains(body[colon:], "/") { tag = body[colon+1:] body = body[:colon] @@ -96,10 +126,11 @@ func parseOCIRef(ref string) (ociRef, error) { if len(segs) >= 3 { org = segs[len(segs)-2] } - if tag == "" { + // Default to latest only when neither a tag nor a digest pins the content. + if tag == "" && digest == "" { tag = "latest" } - return ociRef{URL: "oci://" + body, Org: org, Repo: repo, Tag: tag}, nil + return ociRef{URL: "oci://" + body, Org: org, Repo: repo, Tag: tag, Digest: digest}, nil } // fluxSourceName is the RFC-1123 name of the OCIRepository tap creates. It @@ -116,9 +147,11 @@ func fluxSourceName(r ociRef) string { } // buildTapOCIRepository mirrors the operator's generateOCIRepository: an -// OCIRepository in cozy-system, 5m interval, optional tag reference, optional -// pull-credential secretRef (the private-tap credential, symmetric with #2472). -func buildTapOCIRepository(name string, r ociRef, secret string) *sourcev1.OCIRepository { +// OCIRepository in cozy-system, 5m interval, a tag and/or digest reference, +// optional pull-credential secretRef (the private-tap credential, symmetric +// with #2472). A tag-only reference is pinned to a digest later by the tap +// materializer; an explicit digest is pinned here at connect time. +func buildTapOCIRepository(name string, r ociRef, secret string, verify *sourcev1.OCIRepositoryVerification) *sourcev1.OCIRepository { obj := &sourcev1.OCIRepository{ TypeMeta: metav1.TypeMeta{ APIVersion: sourcev1.GroupVersion.String(), @@ -134,19 +167,62 @@ func buildTapOCIRepository(name string, r ociRef, secret string) *sourcev1.OCIRe Annotations: map[string]string{tapconst.NameAnnotation: name}, }, Spec: sourcev1.OCIRepositorySpec{ - URL: r.URL, - Interval: metav1.Duration{Duration: 5 * time.Minute}, - Reference: &sourcev1.OCIRepositoryRef{ - Tag: r.Tag, - }, + URL: r.URL, + Interval: metav1.Duration{Duration: 5 * time.Minute}, + Reference: &sourcev1.OCIRepositoryRef{Tag: r.Tag, Digest: r.Digest}, }, } if secret != "" { obj.Spec.SecretRef = &fluxmeta.LocalObjectReference{Name: secret} } + if verify != nil { + obj.Spec.Verify = verify + } return obj } +// carryoverSourceFields preserves an existing tap source's verification policy +// and pull credential when this invocation did not set them from flags, so a +// re-tap (e.g. to move the pin to a new tag) never silently drops signature +// verification or the pull secret. A server-side apply that omits a field this +// field owner previously set would otherwise remove it, which the API connect +// path (rest.go) deliberately avoids; this keeps the CLI symmetric with it. +func carryoverSourceFields(obj, existing *sourcev1.OCIRepository, flagVerify *sourcev1.OCIRepositoryVerification, flagSecret string) { + if existing == nil { + return + } + if flagVerify == nil && existing.Spec.Verify != nil { + obj.Spec.Verify = existing.Spec.Verify + } + if flagSecret == "" && existing.Spec.SecretRef != nil { + obj.Spec.SecretRef = existing.Spec.SecretRef + } +} + +// tapVerification builds a keyless cosign verification policy from the connect +// flags, or nil when neither is set. Both the certificate identity (subject) +// and the OIDC issuer are required together: a policy that verified a signature +// without pinning who signed it would be worse than none. Both are Go regular +// expressions at the Flux layer, so an exact identity should be anchored. +func tapVerification(identity, issuer string) (*sourcev1.OCIRepositoryVerification, error) { + if identity == "" && issuer == "" { + return nil, nil + } + if identity == "" || issuer == "" { + return nil, fmt.Errorf("keyless signature verification needs both --certificate-identity and --certificate-oidc-issuer") + } + // Flux treats Issuer and Subject as Go regexps, so anchor and quote them for + // an exact match: an unanchored identity would also accept a superstring + // (e.g. alice@example.com matching malice@example.com). + return &sourcev1.OCIRepositoryVerification{ + Provider: "cosign", + MatchOIDCIdentity: []sourcev1.OIDCIdentityMatch{{ + Issuer: "^" + regexp.QuoteMeta(issuer) + "$", + Subject: "^" + regexp.QuoteMeta(identity) + "$", + }}, + }, nil +} + // rewritePackageSourceForTap prepares a PackageSource read from the artifact for // apply: it keeps the repository's own declared name (no community rename), // clears server-set metadata, stamps the tap marker (label + source annotation) @@ -181,21 +257,38 @@ func rewritePackageSourceForTap(ps *cozyv1alpha1.PackageSource, sourceName, sour } } -// clearMaterializedRevision removes the operator's materialized-revision -// annotation from the tap's OCIRepository, so the next reconcile does not -// short-circuit on the unchanged artifact revision and re-materializes (which -// re-creates a registration removed out-of-band). A no-op when the source or the -// annotation is absent. -func clearMaterializedRevision(ctx context.Context, k8sClient client.Client, srcName string) error { +// resetTapPinState prepares a tap's OCIRepository for a re-tap. It clears the +// materialized-revision annotation so the next reconcile does not short-circuit +// on the unchanged revision and re-materializes its PackageSources (recovering +// one removed out-of-band), and the pinned-digest annotation so the operator +// re-pins the newly requested reference. For a tag-based re-tap (explicitDigest +// false) it also drops the operator's prior digest pin from spec.ref: a +// server-side apply under field owner cozypkg cannot clear a field the operator +// owns, so a moved tag would otherwise stay pinned to the old digest. An +// explicit-digest re-tap keeps the digest the apply itself set. A no-op (and no +// error) when the source is absent or there is nothing to clear. +func resetTapPinState(ctx context.Context, k8sClient client.Client, srcName string, explicitDigest bool) error { reg := &sourcev1.OCIRepository{} if err := k8sClient.Get(ctx, client.ObjectKey{Name: srcName, Namespace: cozySystemNamespace}, reg); err != nil { return client.IgnoreNotFound(err) } - if _, ok := reg.Annotations[tapconst.MaterializedRevisionAnnotation]; !ok { + base := reg.DeepCopy() + changed := false + if _, ok := reg.Annotations[tapconst.MaterializedRevisionAnnotation]; ok { + delete(reg.Annotations, tapconst.MaterializedRevisionAnnotation) + changed = true + } + if _, ok := reg.Annotations[tapconst.PinnedDigestAnnotation]; ok { + delete(reg.Annotations, tapconst.PinnedDigestAnnotation) + changed = true + } + if !explicitDigest && reg.Spec.Reference != nil && reg.Spec.Reference.Digest != "" { + reg.Spec.Reference.Digest = "" + changed = true + } + if !changed { return nil } - base := reg.DeepCopy() - delete(reg.Annotations, tapconst.MaterializedRevisionAnnotation) return k8sClient.Patch(ctx, reg, client.MergeFrom(base)) } @@ -228,23 +321,29 @@ var tapCmd = &cobra.Command{ creates a Flux OCIRepository pointing at the artifact and the PackageSource(s) the artifact carries, under the names the repository declares. A name that clashes with a core component (or another tap) is rejected, so an external -package can never silently shadow an official one. The repository's applications -register in the catalog automatically, unless the repository declares no default -variant (then nothing is registered). A privileged install component of a -registered app is not installed until the operator confirms it with 'cozypkg add ---allow-privileged'. Tapping is idempotent. Creating cluster-scoped resources -requires cluster-admin. +package can never silently shadow an official one. Tapping installs nothing: it +makes the repository's apps available as PackageSources. Install an app with +'cozypkg add '; a privileged install component is not installed until you +confirm it with 'cozypkg add --allow-privileged'. Tapping is idempotent. Creating +cluster-scoped resources requires cluster-admin. With --secret the OCIRepository is given a pull-credential secretRef (the admin pre-creates the Secret in cozy-system), so a private repository taps in one command. -Trust: tap validates the artifact's structure but does NOT verify its cosign -signature. Signature verification is the community index's job at publication -time ('cozypkg validate --require-signature' in the index CI gate, pinned to -the entry's recorded identity), and can additionally be enforced at pull time -via Flux OCIRepository verification. Tapping a third-party repository runs its -charts in your management cluster: tap only sources you trust.`, +Pinning: a tapped repository does not follow a moving tag. A reference given by +digest (oci://host/org/repo@sha256:...) is pinned to that digest immediately; a +tag reference is pinned to the digest it currently resolves to as soon as the +source materializes, with the tag kept informational. Moving the tag upstream +changes nothing in the cluster; tap the repository again to move the pin. + +Trust: tap validates the artifact's structure. Keyless signature verification at +pull time is enabled with --certificate-identity and --certificate-oidc-issuer, +which set a Flux cosign verify policy on the source so content is pulled only +when signed by that identity. Signature verification at publication time is the +community index's job ('cozypkg validate --require-signature' in the index CI +gate, pinned to the entry's recorded identity). Installing an app from a tapped repository +runs its charts in your management cluster: tap only sources you trust.`, Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { ctx := context.Background() @@ -257,12 +356,41 @@ charts in your management cluster: tap only sources you trust.`, return err } if tapCmdFlags.tag != "" { + if ref.Digest != "" { + return fmt.Errorf("--tag cannot override the digest in %q; drop the digest or the --tag flag", args[0]) + } ref.Tag = tapCmdFlags.tag } + verify, err := tapVerification(tapCmdFlags.certIdentity, tapCmdFlags.certIssuer) + if err != nil { + return err + } + + // With verification flags set, verify the signature now and pin the verified + // digest, so the artifact we pull and the PackageSources we apply are the + // exact content a trusted identity signed. Without this the CLI would apply + // an unverified tag pull (only the Flux source would carry the policy), so a + // moved tag could land unsigned PackageSource content in the cluster before + // the operator re-materialized. + if verify != nil { + verifiedDigest, verr := verifyCosignSignature(ref.pullRef(), tapCmdFlags.certIdentity, tapCmdFlags.certIssuer) + if verr != nil { + return verr + } + // Fail closed: a verified signature with no parseable digest must not + // fall back to an unpinned tag pull, which would reopen the tag-mutation + // window between verify and pull. + if verifiedDigest == "" { + return fmt.Errorf("cosign verified %q but returned no manifest digest; refusing to pull by an unpinned tag", ref.pullRef()) + } + if ref.Digest == "" { + ref.Digest = verifiedDigest + } + } // Pull first: an unreachable/invalid ref must fail before any cluster // resource is created (no half-created source). - fullRef := ref.URL + ":" + ref.Tag + fullRef := ref.pullRef() dir, cleanup, err := pullOCIArtifact(fullRef) if err != nil { return err @@ -275,9 +403,8 @@ charts in your management cluster: tap only sources you trust.`, return err } if rep.HasErrors() { - printReport(rep, cmd.OutOrStdout()) errs, _, _ := rep.Counts() - return fmt.Errorf("refusing to tap: artifact failed validation with %d error(s) (use --skip-validate to override)", errs) + return errors.Join(fmt.Errorf("refusing to tap: artifact failed validation with %d error(s) (use --skip-validate to override)", errs), printReport(rep, cmd.OutOrStdout())) } } @@ -288,7 +415,7 @@ charts in your management cluster: tap only sources you trust.`, } srcName := fluxSourceName(ref) - ociRepo := buildTapOCIRepository(srcName, ref, tapCmdFlags.secret) + ociRepo := buildTapOCIRepository(srcName, ref, tapCmdFlags.secret, verify) toApply := make([]client.Object, 0, len(sources)+1) toApply = append(toApply, ociRepo) @@ -317,6 +444,9 @@ charts in your management cluster: tap only sources you trust.`, if existing.Spec.URL != "" && existing.Spec.URL != ref.URL { return fmt.Errorf("a different repository (%s) is already tapped as %q; run 'cozypkg untap %s' before tapping %s", existing.Spec.URL, srcName, names[0], ref.URL) } + // Same repository, re-tapped: carry over a verify policy or pull secret + // this invocation did not set, so moving the pin never silently drops them. + carryoverSourceFields(ociRepo, existing, verify, tapCmdFlags.secret) } // A tapped repository keeps its own declared name. Refuse the whole tap @@ -348,34 +478,48 @@ charts in your management cluster: tap only sources you trust.`, // Force a fresh materialization on this tap: clear the materialized-revision // annotation so the operator does not short-circuit on the unchanged // artifact revision. This makes a re-tap the supported recovery for a - // registration Package (or PackageSource) removed out-of-band since the last - // materialization -- e.g. garbage-collected when its PackageSource was - // deleted. Note this re-registers ANY currently-absent app the artifact - // declares, so a re-tap also undoes a `cozypkg del` of a tap-registered app; - // the two are indistinguishable (both leave the registration absent), and - // there is no per-app opt-out. A first tap has no such annotation, so this is - // a no-op then. - if err := clearMaterializedRevision(ctx, k8sClient, srcName); err != nil { + // PackageSource removed out-of-band since the last materialization. Tapping + // no longer installs anything, so a re-tap does NOT re-install an app removed + // with `cozypkg del`; re-install it with `cozypkg add`. A first tap has no + // such annotation, so this is a no-op then. resetTapPinState also drops the + // operator's prior digest pin so the newly requested tag re-resolves. + if err := resetTapPinState(ctx, k8sClient, srcName, ref.Digest != ""); err != nil { _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "warning: could not reset materialization state on OCIRepository/%s: %v\n", srcName, err) } - fmt.Fprintf(cmd.OutOrStdout(), "Tapped %s\n OCIRepository/%s (%s:%s)\n", fullRef, srcName, ref.URL, ref.Tag) - for _, n := range names { - fmt.Fprintf(cmd.OutOrStdout(), " PackageSource/%s\n", n) - } - _, _ = fmt.Fprintf(cmd.OutOrStdout(), "The repository's applications register in the dashboard catalog automatically. A privileged install component is not installed until you confirm it with 'cozypkg add --allow-privileged'. Check the source's events if an app does not appear.\n") - return nil + return writeTapSummary(cmd.OutOrStdout(), fullRef, srcName, names) }, } +// writeTapSummary reports what a tap created. The tap is applied by then, so a +// summary that cannot be written fails the command while saying so. +func writeTapSummary(w io.Writer, fullRef, srcName string, names []string) error { + var b strings.Builder + fmt.Fprintf(&b, "Tapped %s\n OCIRepository/%s\n", fullRef, srcName) + for _, n := range names { + fmt.Fprintf(&b, " PackageSource/%s\n", n) + } + b.WriteString("Tapping installs nothing. Install an app with:\n") + for _, n := range names { + fmt.Fprintf(&b, " cozypkg add %s\n", n) + } + b.WriteString("A privileged install component is not installed until you confirm it with 'cozypkg add --allow-privileged'.\n") + if _, err := io.WriteString(w, b.String()); err != nil { + return fmt.Errorf("tap applied, but writing its summary failed: %w", err) + } + return nil +} + var untapCmd = &cobra.Command{ Use: "untap ", Short: "Remove a tapped repository", - Long: `Untap removes a tapped PackageSource, its Flux source, and the -tap-managed registration Package that de-registers the repository's apps from -the catalog. Running application instances are left in place but become -unmanaged until the repository is tapped again. Only tapped sources (marked -with the marketplace-tap label) can be untapped; official sources are refused.`, + Long: `Untap removes a tapped PackageSource and its Flux source. A tap-managed +registration Package left by an older Cozystack (one that registered apps on +connect) is removed too, de-registering those apps. An app you installed yourself +with 'cozypkg add' is left installed: untap refuses without --yes while such a +Package is present. Running application instances are left in place but become +unmanaged until the repository is tapped again. Only tapped sources (marked with +the marketplace-tap label) can be untapped; official sources are refused.`, Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { k8sClient, err := newClusterClient(tapCmdFlags.kubeconfig) @@ -404,13 +548,13 @@ func runUntap(ctx context.Context, k8sClient client.Client, name string, allowYe srcName = ps.Spec.SourceRef.Name } - // The registration Package (auto-created on connect, tap-managed) - // de-registers the repository's apps and is removed with the untap. Deleting - // it garbage-collects its registration HelmReleases and the - // ApplicationDefinitions they render. It is removed only when it belongs to - // THIS source (label AND source annotation); a Package a later tap created - // under a reused name, or a foreign Package, is left in place and blocks the - // untap without --yes. + // A tap-managed registration Package (left by an older Cozystack that + // registered apps on connect) de-registers the repository's apps and is + // removed with the untap. Deleting it garbage-collects its registration + // HelmReleases and the ApplicationDefinitions they render. It is removed only + // when it belongs to THIS source (label AND source annotation); a Package a + // later tap created under a reused name, or a foreign Package, is left in place + // and blocks the untap without --yes. // // The Package is handled BEFORE the PackageSource: a transient error here must // abort the untap, not fall through to delete the PackageSource and OCIRepository @@ -507,6 +651,8 @@ func init() { tapCmd.Flags().StringVar(&tapCmdFlags.kubeconfig, "kubeconfig", "", "Path to kubeconfig file") tapCmd.Flags().StringVar(&tapCmdFlags.index, "index", "", "Index location for resolving a short name (local dir or oci:// ref; defaults to COZYPKG_INDEX)") tapCmd.Flags().BoolVar(&tapCmdFlags.skipValidate, "skip-validate", false, "Skip validating the artifact before tapping") + tapCmd.Flags().StringVar(&tapCmdFlags.certIdentity, "certificate-identity", "", "Keyless cosign certificate identity (subject regex) to verify the artifact's signature against at pull time; requires --certificate-oidc-issuer") + tapCmd.Flags().StringVar(&tapCmdFlags.certIssuer, "certificate-oidc-issuer", "", "Keyless cosign OIDC issuer (regex) to verify the artifact's signature against at pull time; requires --certificate-identity") untapCmd.Flags().StringVar(&tapCmdFlags.kubeconfig, "kubeconfig", "", "Path to kubeconfig file") untapCmd.Flags().BoolVar(&untapConfirmFlag, "yes", false, "Untap even if a Package from this source is still installed") } diff --git a/cmd/cozypkg/cmd/tap_test.go b/cmd/cozypkg/cmd/tap_test.go index 27d25ff37..a342f4fe8 100644 --- a/cmd/cozypkg/cmd/tap_test.go +++ b/cmd/cozypkg/cmd/tap_test.go @@ -20,8 +20,10 @@ import ( "context" "errors" "io" + "regexp" "testing" + fluxmeta "github.com/fluxcd/pkg/apis/meta" sourcev1 "github.com/fluxcd/source-controller/api/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -36,18 +38,26 @@ import ( ) func TestParseOCIRef(t *testing.T) { + const digest = "sha256:1111111111111111111111111111111111111111111111111111111111111111" cases := []struct { - in string - wantURL, wantOrg, wantRepo, wantTag string - wantErr bool + in string + wantURL, wantOrg, wantRepo, wantTag, wantDigest string + wantErr bool }{ - {"oci://ghcr.io/foo/bar:v1", "oci://ghcr.io/foo/bar", "foo", "bar", "v1", false}, - {"oci://ghcr.io/foo/bar", "oci://ghcr.io/foo/bar", "foo", "bar", "latest", false}, - {"oci://ghcr.io/foo/group/bar:1.2.3", "oci://ghcr.io/foo/group/bar", "group", "bar", "1.2.3", false}, - {"oci://registry.example.com/solo:tag", "oci://registry.example.com/solo", "", "solo", "tag", false}, - {"https://ghcr.io/foo/bar", "", "", "", "", true}, - {"oci://ghcr.io/foo/bar@sha256:abc", "", "", "", "", true}, - {"oci://ghcr.io", "", "", "", "", true}, + {"oci://ghcr.io/foo/bar:v1", "oci://ghcr.io/foo/bar", "foo", "bar", "v1", "", false}, + {"oci://ghcr.io/foo/bar", "oci://ghcr.io/foo/bar", "foo", "bar", "latest", "", false}, + {"oci://ghcr.io/foo/group/bar:1.2.3", "oci://ghcr.io/foo/group/bar", "group", "bar", "1.2.3", "", false}, + {"oci://registry.example.com/solo:tag", "oci://registry.example.com/solo", "", "solo", "tag", "", false}, + // A digest pin is accepted; the tag is left empty (not defaulted to + // latest) because the digest is the authoritative reference. + {"oci://ghcr.io/foo/bar@" + digest, "oci://ghcr.io/foo/bar", "foo", "bar", "", digest, false}, + // A tag may precede the digest; the tag is then informational only. + {"oci://ghcr.io/foo/bar:v1@" + digest, "oci://ghcr.io/foo/bar", "foo", "bar", "v1", digest, false}, + {"https://ghcr.io/foo/bar", "", "", "", "", "", true}, + // A malformed digest (not sha256:<64 hex>) is still rejected. + {"oci://ghcr.io/foo/bar@sha256:abc", "", "", "", "", "", true}, + {"oci://ghcr.io/foo/bar@notadigest", "", "", "", "", "", true}, + {"oci://ghcr.io", "", "", "", "", "", true}, } for _, c := range cases { got, err := parseOCIRef(c.in) @@ -61,8 +71,8 @@ func TestParseOCIRef(t *testing.T) { t.Errorf("parseOCIRef(%q) unexpected error: %v", c.in, err) continue } - if got.URL != c.wantURL || got.Org != c.wantOrg || got.Repo != c.wantRepo || got.Tag != c.wantTag { - t.Errorf("parseOCIRef(%q) = %+v, want url=%q org=%q repo=%q tag=%q", c.in, got, c.wantURL, c.wantOrg, c.wantRepo, c.wantTag) + if got.URL != c.wantURL || got.Org != c.wantOrg || got.Repo != c.wantRepo || got.Tag != c.wantTag || got.Digest != c.wantDigest { + t.Errorf("parseOCIRef(%q) = %+v, want url=%q org=%q repo=%q tag=%q digest=%q", c.in, got, c.wantURL, c.wantOrg, c.wantRepo, c.wantTag, c.wantDigest) } } } @@ -118,7 +128,7 @@ func TestObjectExists(t *testing.T) { func TestBuildTapOCIRepository(t *testing.T) { r := ociRef{URL: "oci://ghcr.io/foo/bar", Org: "foo", Repo: "bar", Tag: "v1"} - obj := buildTapOCIRepository("tap-foo-bar", r, "") + obj := buildTapOCIRepository("tap-foo-bar", r, "", nil) if obj.Namespace != "cozy-system" || obj.Spec.URL != "oci://ghcr.io/foo/bar" { t.Fatalf("unexpected OCIRepository: %+v", obj.Spec) } @@ -139,10 +149,121 @@ func TestBuildTapOCIRepository(t *testing.T) { if obj.Spec.SecretRef != nil { t.Fatalf("expected no secretRef, got %+v", obj.Spec.SecretRef) } - withSecret := buildTapOCIRepository("n", r, "pull-creds") + withSecret := buildTapOCIRepository("n", r, "pull-creds", nil) if withSecret.Spec.SecretRef == nil || withSecret.Spec.SecretRef.Name != "pull-creds" { t.Fatalf("expected secretRef pull-creds, got %+v", withSecret.Spec.SecretRef) } + + // A digest-pinned reference sets spec.ref.digest; an explicit digest from + // the user is written by the CLI itself (the operator only pins tag refs). + const digest = "sha256:1111111111111111111111111111111111111111111111111111111111111111" + rd := ociRef{URL: "oci://ghcr.io/foo/bar", Org: "foo", Repo: "bar", Digest: digest} + objd := buildTapOCIRepository("tap-foo-bar", rd, "", nil) + if objd.Spec.Reference == nil || objd.Spec.Reference.Digest != digest { + t.Fatalf("expected digest pin %q, got %+v", digest, objd.Spec.Reference) + } + if objd.Spec.Reference.Tag != "" { + t.Errorf("a digest-only reference must not carry a tag, got %q", objd.Spec.Reference.Tag) + } + // A tag may accompany the digest and is then informational. + rtd := ociRef{URL: "oci://ghcr.io/foo/bar", Repo: "bar", Tag: "v1", Digest: digest} + objtd := buildTapOCIRepository("n", rtd, "", nil) + if objtd.Spec.Reference.Digest != digest || objtd.Spec.Reference.Tag != "v1" { + t.Fatalf("expected tag v1 + digest, got %+v", objtd.Spec.Reference) + } +} + +func TestOCIRefPullRef(t *testing.T) { + const digest = "sha256:1111111111111111111111111111111111111111111111111111111111111111" + if got := (ociRef{URL: "oci://ghcr.io/foo/bar", Tag: "v1"}).pullRef(); got != "oci://ghcr.io/foo/bar:v1" { + t.Errorf("tag pullRef = %q", got) + } + // A digest is pulled by digest, so the pull resolves the exact content + // regardless of where the tag currently points. + if got := (ociRef{URL: "oci://ghcr.io/foo/bar", Tag: "v1", Digest: digest}).pullRef(); got != "oci://ghcr.io/foo/bar@"+digest { + t.Errorf("digest pullRef = %q", got) + } +} + +func TestTapVerification(t *testing.T) { + // No identity and no issuer: no verification policy. + if v, err := tapVerification("", ""); err != nil || v != nil { + t.Fatalf("empty flags should yield no policy, got %+v err %v", v, err) + } + // Only one of the pair: an error, never a half-configured policy. + if _, err := tapVerification("subj", ""); err == nil { + t.Error("identity without issuer must error") + } + if _, err := tapVerification("", "iss"); err == nil { + t.Error("issuer without identity must error") + } + id := "https://github.com/org/repo/.github/workflows/release.yml@refs/tags/v1" + iss := "https://token.actions.githubusercontent.com" + v, err := tapVerification(id, iss) + if err != nil { + t.Fatalf("valid pair: %v", err) + } + if v == nil || v.Provider != "cosign" || len(v.MatchOIDCIdentity) != 1 { + t.Fatalf("unexpected verification: %+v", v) + } + // Flux evaluates the matcher as a regexp. It must be an anchored exact match: + // it matches the exact identity and rejects a superstring (a moved tag v10, or + // malice@... for an email identity), which an unanchored matcher would accept. + m := v.MatchOIDCIdentity[0] + subjRe := regexp.MustCompile(m.Subject) + if !subjRe.MatchString(id) || subjRe.MatchString(id+"0") { + t.Errorf("subject must be an anchored exact match, got %q", m.Subject) + } + issRe := regexp.MustCompile(m.Issuer) + if !issRe.MatchString(iss) || issRe.MatchString(iss+"x") { + t.Errorf("issuer must be an anchored exact match, got %q", m.Issuer) + } +} + +func TestCarryoverSourceFields(t *testing.T) { + verifyPol := &sourcev1.OCIRepositoryVerification{Provider: "cosign", MatchOIDCIdentity: []sourcev1.OIDCIdentityMatch{{Issuer: "iss", Subject: "subj"}}} + existing := &sourcev1.OCIRepository{Spec: sourcev1.OCIRepositorySpec{ + Verify: verifyPol, + SecretRef: &fluxmeta.LocalObjectReference{Name: "pull-creds"}, + }} + + // Re-tap without flags: an existing verify policy and pull secret are carried + // onto the object to apply, so a server-side apply that omits them does not + // remove them (SSA prunes a previously-owned field left out of the apply). + obj := &sourcev1.OCIRepository{} + carryoverSourceFields(obj, existing, nil, "") + if obj.Spec.Verify == nil { + t.Error("existing verify policy must be preserved when no --certificate-* flags are given") + } + if obj.Spec.SecretRef == nil || obj.Spec.SecretRef.Name != "pull-creds" { + t.Error("existing pull secret must be preserved when no --secret is given") + } + + // Flags present: the invocation's own values win, nothing is carried over. + flagVerify := &sourcev1.OCIRepositoryVerification{Provider: "cosign"} + obj2 := &sourcev1.OCIRepository{Spec: sourcev1.OCIRepositorySpec{Verify: flagVerify, SecretRef: &fluxmeta.LocalObjectReference{Name: "new-creds"}}} + carryoverSourceFields(obj2, existing, flagVerify, "new-creds") + if obj2.Spec.Verify != flagVerify { + t.Error("a verify policy from flags must not be overwritten by the existing one") + } + if obj2.Spec.SecretRef.Name != "new-creds" { + t.Error("a secret from --secret must not be overwritten by the existing one") + } + + // No existing source: a no-op, no panic. + carryoverSourceFields(&sourcev1.OCIRepository{}, nil, nil, "") +} + +func TestBuildTapOCIRepositoryWithVerify(t *testing.T) { + r := ociRef{URL: "oci://ghcr.io/foo/bar", Repo: "bar", Tag: "v1"} + v := &sourcev1.OCIRepositoryVerification{ + Provider: "cosign", + MatchOIDCIdentity: []sourcev1.OIDCIdentityMatch{{Issuer: "iss", Subject: "subj"}}, + } + obj := buildTapOCIRepository("tap-foo-bar", r, "", v) + if obj.Spec.Verify == nil || obj.Spec.Verify.Provider != "cosign" || len(obj.Spec.Verify.MatchOIDCIdentity) != 1 { + t.Fatalf("verify not set on the source: %+v", obj.Spec.Verify) + } } // rewritePackageSourceForTap must NOT rename the PackageSource: a tapped @@ -279,16 +400,23 @@ func TestCreatePackageIdempotent(t *testing.T) { } } -func TestClearMaterializedRevision(t *testing.T) { +func TestResetTapPinState(t *testing.T) { s := untapScheme(t) + const oldDigest = "sha256:2222222222222222222222222222222222222222222222222222222222222222" oci := &sourcev1.OCIRepository{ObjectMeta: metav1.ObjectMeta{ Name: "tap-acme-hello", Namespace: "cozy-system", - Annotations: map[string]string{tapconst.MaterializedRevisionAnnotation: "rev-1", "keep": "me"}, - }} + Annotations: map[string]string{ + tapconst.MaterializedRevisionAnnotation: "v1@" + oldDigest, + tapconst.PinnedDigestAnnotation: oldDigest, + "keep": "me", + }, + }, Spec: sourcev1.OCIRepositorySpec{Reference: &sourcev1.OCIRepositoryRef{Tag: "v1", Digest: oldDigest}}} cl := fake.NewClientBuilder().WithScheme(s).WithObjects(oci).Build() - if err := clearMaterializedRevision(context.Background(), cl, "tap-acme-hello"); err != nil { - t.Fatalf("clear: %v", err) + // A tag-based re-tap must drop the operator's digest pin (cozypkg cannot + // clear a field the operator owns via server-side apply) and both annotations. + if err := resetTapPinState(context.Background(), cl, "tap-acme-hello", false); err != nil { + t.Fatalf("reset: %v", err) } var got sourcev1.OCIRepository if err := cl.Get(context.Background(), client.ObjectKey{Name: "tap-acme-hello", Namespace: "cozy-system"}, &got); err != nil { @@ -297,11 +425,38 @@ func TestClearMaterializedRevision(t *testing.T) { if _, ok := got.Annotations[tapconst.MaterializedRevisionAnnotation]; ok { t.Error("materialized-revision annotation must be cleared to force re-materialization") } + if _, ok := got.Annotations[tapconst.PinnedDigestAnnotation]; ok { + t.Error("pinned-digest annotation must be cleared so the operator re-pins") + } + if got.Spec.Reference != nil && got.Spec.Reference.Digest != "" { + t.Errorf("a tag re-tap must drop the operator digest pin, got %q", got.Spec.Reference.Digest) + } + if got.Spec.Reference == nil || got.Spec.Reference.Tag != "v1" { + t.Errorf("the tag must be left in place, got %+v", got.Spec.Reference) + } if got.Annotations["keep"] != "me" { t.Error("unrelated annotations must be preserved") } + + // An explicit-digest re-tap must NOT drop the digest the CLI itself set. + oci2 := &sourcev1.OCIRepository{ObjectMeta: metav1.ObjectMeta{ + Name: "tap-acme-two", Namespace: "cozy-system", + Annotations: map[string]string{tapconst.MaterializedRevisionAnnotation: oldDigest}, + }, Spec: sourcev1.OCIRepositorySpec{Reference: &sourcev1.OCIRepositoryRef{Digest: oldDigest}}} + cl2 := fake.NewClientBuilder().WithScheme(s).WithObjects(oci2).Build() + if err := resetTapPinState(context.Background(), cl2, "tap-acme-two", true); err != nil { + t.Fatalf("reset explicit: %v", err) + } + var got2 sourcev1.OCIRepository + if err := cl2.Get(context.Background(), client.ObjectKey{Name: "tap-acme-two", Namespace: "cozy-system"}, &got2); err != nil { + t.Fatal(err) + } + if got2.Spec.Reference == nil || got2.Spec.Reference.Digest != oldDigest { + t.Errorf("an explicit-digest re-tap must keep its digest, got %+v", got2.Spec.Reference) + } + // Absent source: no error. - if err := clearMaterializedRevision(context.Background(), cl, "missing"); err != nil { + if err := resetTapPinState(context.Background(), cl, "missing", false); err != nil { t.Errorf("a missing source must not error, got %v", err) } } diff --git a/cmd/cozypkg/cmd/validate.go b/cmd/cozypkg/cmd/validate.go index 809f0f246..f781cfd8b 100644 --- a/cmd/cozypkg/cmd/validate.go +++ b/cmd/cozypkg/cmd/validate.go @@ -21,6 +21,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "io/fs" @@ -535,16 +536,19 @@ func pullOCIArtifact(ref string) (string, func(), error) { return dir, cleanup, nil } -func printReport(r *Report, w io.Writer) { +func printReport(r *Report, w io.Writer) error { for _, f := range r.Findings { loc := f.Location if loc == "" { loc = "-" } - fmt.Fprintf(w, "[%s] %s (%s): %s\n", f.Severity, loc, f.Code, f.Message) + if _, err := fmt.Fprintf(w, "[%s] %s (%s): %s\n", f.Severity, loc, f.Code, f.Message); err != nil { + return err + } } errs, warns, infos := r.Counts() - fmt.Fprintf(w, "\nSummary: %d error(s), %d warning(s), %d info\n", errs, warns, infos) + _, err := fmt.Fprintf(w, "\nSummary: %d error(s), %d warning(s), %d info\n", errs, warns, infos) + return err } var validateCmdFlags struct { @@ -663,10 +667,13 @@ runs "helm lint" on every component chart.`, if err != nil { return err } - printReport(rep, cmd.OutOrStdout()) + printErr := printReport(rep, cmd.OutOrStdout()) if rep.HasErrors() { errs, _, _ := rep.Counts() - return fmt.Errorf("validation failed: %d error(s)", errs) + return errors.Join(fmt.Errorf("validation failed: %d error(s)", errs), printErr) + } + if printErr != nil { + return fmt.Errorf("writing the validation report failed: %w", printErr) } return nil }, diff --git a/cmd/cozystack-controller/main.go b/cmd/cozystack-controller/main.go index f167086f4..59ba3b515 100644 --- a/cmd/cozystack-controller/main.go +++ b/cmd/cozystack-controller/main.go @@ -46,6 +46,7 @@ import ( "github.com/cozystack/cozystack/internal/controller" "github.com/cozystack/cozystack/internal/controller/cacert" "github.com/cozystack/cozystack/internal/controller/tenantgateway" + "github.com/cozystack/cozystack/internal/controller/tenantlogrouting" "github.com/cozystack/cozystack/internal/controller/tenantquota" "github.com/cozystack/cozystack/internal/controller/wildcardsecret" "github.com/cozystack/cozystack/internal/telemetry" @@ -287,6 +288,13 @@ func main() { os.Exit(1) } + if err = (&tenantlogrouting.Reconciler{ + Client: mgr.GetClient(), + }).SetupWithManager(mgr); err != nil { + setupLog.Error(err, "unable to create controller", "controller", "TenantLogRouting") + os.Exit(1) + } + if err = (&wildcardsecret.Reconciler{ Client: mgr.GetClient(), Reader: mgr.GetAPIReader(), diff --git a/cmd/cozystack-operator/main.go b/cmd/cozystack-operator/main.go index e3e8ba6d2..e1a2aa1de 100644 --- a/cmd/cozystack-operator/main.go +++ b/cmd/cozystack-operator/main.go @@ -36,6 +36,7 @@ import ( sourcewatcherv1beta1 "github.com/fluxcd/source-watcher/api/v2/v1beta1" corev1 "k8s.io/api/core/v1" apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/labels" @@ -98,6 +99,9 @@ func main() { var platformSourceName string var platformSourceRef string var platformSourceSecret string + var platformSourceCertSecret string + var systemNamespaceMemoryLimit string + var systemNamespaceMemoryRequest string flag.StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.") flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.") @@ -142,9 +146,18 @@ func main() { flag.StringVar(&platformSourceName, "platform-source-name", "cozystack-platform", "Name for the generated platform source resource and PackageSource") flag.StringVar(&platformSourceRef, "platform-source-ref", "", "Reference specification as key=value pairs (e.g., 'branch=main' or 'digest=sha256:...,tag=v1.0'). For OCI: digest, semver, semverFilter, tag. For Git: branch, tag, semver, name, commit.") flag.StringVar(&platformSourceSecret, "platform-source-secret", "", "Name of the Secret in cozy-system namespace containing credentials for the platform source. Sets spec.secretRef on the generated OCIRepository or GitRepository. Secret type depends on the source kind: kubernetes.io/dockerconfigjson for OCI (oci://...); Opaque with username+password (or bearerToken) for Git over HTTPS; Opaque with identity (PEM private key) and known_hosts for Git over SSH.") + flag.StringVar(&platformSourceCertSecret, "platform-source-cert-secret", "", "Name of the Secret in cozy-system namespace holding TLS material for an OCI platform source: ca.crt for a registry behind a private CA, and/or tls.crt+tls.key for client certificate auth. Sets spec.certSecretRef on the generated OCIRepository. Not supported for Git sources, where Flux reads ca.crt from the --platform-source-secret Secret.") flag.StringVar(&cozyValuesSecretName, "cozy-values-secret-name", "cozystack-values", "The name of the secret containing cluster-wide configuration values.") flag.StringVar(&cozyValuesSecretNamespace, "cozy-values-secret-namespace", "cozy-system", "The namespace of the secret containing cluster-wide configuration values.") flag.StringVar(&cozyValuesNamespaceSelector, "cozy-values-namespace-selector", "cozystack.io/system=true", "The label selector for namespaces where the cluster-wide configuration values must be replicated.") + flag.StringVar(&systemNamespaceMemoryLimit, "system-namespace-memory-limit", DefaultSystemNamespaceMemoryLimit, + "Default container memory limit in eligible system namespaces, including kube-system. "+ + "Lowering or an oversized request creates a durable hold requiring an administrator's "+ + "exact-value acknowledgement. Empty or 0 disables and removes managed LimitRanges; "+ + "safety state is retained. See https://cozystack.io/docs/v1/operations/configuration/system-memory-limits/.") + flag.StringVar(&systemNamespaceMemoryRequest, "system-namespace-memory-request", DefaultSystemNamespaceMemoryRequest, + "Default memory request paired with the system namespace limit. Keep small; 0 is supported. "+ + "An empty installer value selects the operator default. See https://cozystack.io/docs/v1/operations/configuration/system-memory-limits/.") opts := zap.Options{ Development: true, @@ -171,6 +184,18 @@ func main() { os.Exit(1) } + systemNSMemoryLimit, systemNSMemoryRequest, err := parseSystemNamespaceMemory(systemNamespaceMemoryLimit, systemNamespaceMemoryRequest) + if err != nil { + setupLog.Error(err, "invalid system namespace memory flags", + "limit", systemNamespaceMemoryLimit, "request", systemNamespaceMemoryRequest) + os.Exit(1) + } + + if err := validatePlatformSourceCertSecret(platformSourceURL, platformSourceCertSecret); err != nil { + setupLog.Error(err, "invalid platform source flags") + os.Exit(1) + } + config := ctrl.GetConfigOrDie() // Create a direct client (without cache) for pre-start operations @@ -260,12 +285,12 @@ func main() { // Generate and install platform source resource if specified if platformSourceURL != "" { - setupLog.Info("Generating platform source resource", "url", platformSourceURL, "name", platformSourceName, "ref", platformSourceRef, "secret", platformSourceSecret) + setupLog.Info("Generating platform source resource", "url", platformSourceURL, "name", platformSourceName, "ref", platformSourceRef, "secret", platformSourceSecret, "certSecret", platformSourceCertSecret) installCtx, installCancel := context.WithTimeout(mgrCtx, 2*time.Minute) defer installCancel() // Use direct client for pre-start operations (cache is not ready yet) - if err := installPlatformSourceResource(installCtx, directClient, platformSourceURL, platformSourceName, platformSourceRef, platformSourceSecret); err != nil { + if err := installPlatformSourceResource(installCtx, directClient, platformSourceURL, platformSourceName, platformSourceRef, platformSourceSecret, platformSourceCertSecret); err != nil { setupLog.Error(err, "failed to install platform source resource") os.Exit(1) } else { @@ -307,13 +332,20 @@ func main() { // Setup Package reconciler if err := (&operator.PackageReconciler{ - Client: mgr.GetClient(), + Client: mgr.GetClient(), + // Non-cached, so the per-namespace pod and workload scan guarding the + // system defaults LimitRange does not start cluster-wide informers in an + // operator whose whole purpose here is to bound memory. + APIReader: mgr.GetAPIReader(), Scheme: mgr.GetScheme(), HelmReleaseInterval: hrIntervalDuration, HelmReleaseRetryInterval: hrRetryIntervalDuration, HelmReleaseInstallTimeout: hrInstallTimeoutDuration, HelmReleaseUpgradeTimeout: hrUpgradeTimeoutDuration, HelmReleaseMaxHistory: helmReleaseMaxHistory, + + SystemNamespaceMemoryLimit: systemNSMemoryLimit, + SystemNamespaceMemoryRequest: systemNSMemoryRequest, }).SetupWithManager(mgr); err != nil { setupLog.Error(err, "unable to create controller", "controller", "Package") os.Exit(1) @@ -389,7 +421,7 @@ func main() { // installPlatformSourceResource generates and installs a Flux source resource (OCIRepository or GitRepository) // based on the platform source URL -func installPlatformSourceResource(ctx context.Context, k8sClient client.Client, sourceURL, resourceName, refSpec, secretName string) error { +func installPlatformSourceResource(ctx context.Context, k8sClient client.Client, sourceURL, resourceName, refSpec, secretName, certSecretName string) error { logger := log.FromContext(ctx) // Parse the source URL to determine type @@ -407,11 +439,14 @@ func installPlatformSourceResource(ctx context.Context, k8sClient client.Client, var obj client.Object switch sourceType { case "oci": - obj, err = generateOCIRepository(resourceName, repoURL, refMap, secretName) + obj, err = generateOCIRepository(resourceName, repoURL, refMap, secretName, certSecretName) if err != nil { return fmt.Errorf("failed to generate OCIRepository: %w", err) } case "git": + if err := validatePlatformSourceCertSecret(sourceURL, certSecretName); err != nil { + return err + } obj, err = generateGitRepository(resourceName, repoURL, refMap, secretName) if err != nil { return fmt.Errorf("failed to generate GitRepository: %w", err) @@ -454,6 +489,72 @@ func installPlatformSourceResource(ctx context.Context, k8sClient client.Client, return nil } +// The shipped defaults for the two system-namespace memory knobs. Constants keep flag +// registration and the parser test inputs on the same values; the test compares the parsed +// result with literal contract values so changing a default cannot stay green by construction. +const ( + DefaultSystemNamespaceMemoryLimit = "32Gi" + DefaultSystemNamespaceMemoryRequest = "32Mi" +) + +// parseSystemNamespaceMemory turns the --system-namespace-memory-limit and +// --system-namespace-memory-request flag values into the quantities the Package reconciler +// takes, rejecting the combinations that would fail later and further away. +// +// Empty is how both flags are disabled and parses to the zero quantity; for the limit that +// means "no LimitRange, and remove any this operator created", which is the documented +// off switch. A negative quantity parses fine as a Quantity and is meaningless as memory, +// so it is caught here rather than being written into a LimitRange the API server rejects. +// +// The pair check is the one that matters most. A LimitRange whose defaultRequest exceeds +// its default is rejected by the API server, and because the reconciler applies one per +// system namespace on every Package reconcile, a bad pair would wedge namespace +// reconciliation for every system package with an error nothing connects back to a flag. +// A request of 0 against a non-zero limit passes deliberately: it is the supported way to +// take the memory.max without reserving anything at schedule time, not a broken value. +// Both zero is the disabled case and never reaches the comparison. +func parseSystemNamespaceMemory(rawLimit, rawRequest string) (limit, request resource.Quantity, err error) { + parse := func(flagName, raw string) (resource.Quantity, error) { + if raw == "" { + return resource.Quantity{}, nil + } + q, err := resource.ParseQuantity(raw) + if err != nil { + return resource.Quantity{}, fmt.Errorf("%s: %w", flagName, err) + } + if q.Sign() < 0 { + return resource.Quantity{}, fmt.Errorf("%s must not be negative, got %s", flagName, raw) + } + return q, nil + } + + if limit, err = parse("--system-namespace-memory-limit", rawLimit); err != nil { + return resource.Quantity{}, resource.Quantity{}, err + } + if request, err = parse("--system-namespace-memory-request", rawRequest); err != nil { + return resource.Quantity{}, resource.Quantity{}, err + } + if !limit.IsZero() && request.Cmp(limit) > 0 { + return resource.Quantity{}, resource.Quantity{}, fmt.Errorf( + "--system-namespace-memory-request (%s) must not exceed --system-namespace-memory-limit (%s)", + request.String(), limit.String()) + } + return limit, request, nil +} + +// validatePlatformSourceCertSecret rejects --platform-source-cert-secret for a +// Git source: GitRepository has no certSecretRef, and Flux reads a Git CA from +// the ca.crt key of the --platform-source-secret Secret instead. +func validatePlatformSourceCertSecret(sourceURL, certSecretName string) error { + if certSecretName == "" { + return nil + } + if sourceType, _, err := parsePlatformSourceURL(sourceURL); err == nil && sourceType == "git" { + return fmt.Errorf("--platform-source-cert-secret is only supported for OCI sources; for a Git source put ca.crt into the --platform-source-secret Secret") + } + return nil +} + // parsePlatformSourceURL parses the source URL and returns the source type and repository URL. // Supports formats: // - oci://registry.example.com/repo @@ -562,7 +663,7 @@ func validateGitRef(refMap map[string]string) error { return fmt.Errorf("commit SHA should be at least 7 characters, got: %s", commit) } for _, c := range commit { - if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) { + if (c < '0' || c > '9') && (c < 'a' || c > 'f') && (c < 'A' || c > 'F') { return fmt.Errorf("commit SHA should be a hexadecimal string, got: %s", commit) } } @@ -572,7 +673,7 @@ func validateGitRef(refMap map[string]string) error { } // generateOCIRepository creates an OCIRepository resource -func generateOCIRepository(name, repoURL string, refMap map[string]string, secretName string) (*sourcev1.OCIRepository, error) { +func generateOCIRepository(name, repoURL string, refMap map[string]string, secretName, certSecretName string) (*sourcev1.OCIRepository, error) { if err := validateOCIRef(refMap); err != nil { return nil, err } @@ -609,6 +710,12 @@ func generateOCIRepository(name, repoURL string, refMap map[string]string, secre } } + if certSecretName != "" { + obj.Spec.CertSecretRef = &fluxmeta.LocalObjectReference{ + Name: certSecretName, + } + } + return obj, nil } @@ -694,6 +801,9 @@ func installPlatformPackageSource(ctx context.Context, k8sClient client.Client, {"isp-full", []string{"values.yaml", "values-isp-full.yaml"}}, {"isp-hosted", []string{"values.yaml", "values-isp-hosted.yaml"}}, {"isp-full-generic", []string{"values.yaml", "values-isp-full-generic.yaml"}}, + {"isp-slim", []string{"values.yaml", "values-isp-slim.yaml"}}, + {"isp-slim-generic", []string{"values.yaml", "values-isp-slim-generic.yaml"}}, + {"isp-hosted-slim", []string{"values.yaml", "values-isp-hosted-slim.yaml"}}, } variants := make([]cozyv1alpha1.Variant, len(variantData)) diff --git a/cmd/cozystack-operator/main_test.go b/cmd/cozystack-operator/main_test.go index d40243cda..136db4603 100644 --- a/cmd/cozystack-operator/main_test.go +++ b/cmd/cozystack-operator/main_test.go @@ -23,6 +23,8 @@ import ( cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" "github.com/cozystack/cozystack/internal/marketplace/tapconst" + sourcev1 "github.com/fluxcd/source-controller/api/v1" + "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "sigs.k8s.io/controller-runtime/pkg/client" @@ -77,7 +79,7 @@ func TestInstallPlatformPackageSource_Creates(t *testing.T) { } // Verify variants - expectedVariants := []string{"default", "isp-full", "isp-hosted", "isp-full-generic"} + expectedVariants := []string{"default", "isp-full", "isp-hosted", "isp-full-generic", "isp-slim", "isp-slim-generic", "isp-hosted-slim"} if len(ps.Spec.Variants) != len(expectedVariants) { t.Fatalf("expected %d variants, got %d", len(expectedVariants), len(ps.Spec.Variants)) } @@ -114,15 +116,15 @@ func TestInstallPlatformPackageSource_Updates(t *testing.T) { if ps.Spec.SourceRef.Name != "cozystack-platform" { t.Errorf("expected sourceRef.name %q, got %q", "cozystack-platform", ps.Spec.SourceRef.Name) } - if len(ps.Spec.Variants) != 4 { - t.Errorf("expected 4 variants, got %d", len(ps.Spec.Variants)) + if len(ps.Spec.Variants) != 7 { + t.Errorf("expected 7 variants, got %d", len(ps.Spec.Variants)) } } // TestInstallPlatformPackageSource_RefusesTapOwned asserts that when a // marketplace tap has materialized a PackageSource under a name the platform // later ships, the platform refuses to overwrite it, names the conflict, and -// leaves the object untouched (kvaps' review point). +// leaves the object untouched. func TestInstallPlatformPackageSource_RefusesTapOwned(t *testing.T) { s := newTestScheme() tapOwned := &cozyv1alpha1.PackageSource{ @@ -259,6 +261,9 @@ func TestInstallPlatformPackageSource_VariantValuesFiles(t *testing.T) { "isp-full": {"values.yaml", "values-isp-full.yaml"}, "isp-hosted": {"values.yaml", "values-isp-hosted.yaml"}, "isp-full-generic": {"values.yaml", "values-isp-full-generic.yaml"}, + "isp-slim": {"values.yaml", "values-isp-slim.yaml"}, + "isp-slim-generic": {"values.yaml", "values-isp-slim-generic.yaml"}, + "isp-hosted-slim": {"values.yaml", "values-isp-hosted-slim.yaml"}, } for _, v := range ps.Spec.Variants { @@ -530,7 +535,7 @@ func TestValidateGitRef(t *testing.T) { func TestGenerateOCIRepository(t *testing.T) { refMap := map[string]string{"tag": "v1.0", "digest": "sha256:abc123"} - obj, err := generateOCIRepository("my-repo", "oci://registry.example.com/repo", refMap, "") + obj, err := generateOCIRepository("my-repo", "oci://registry.example.com/repo", refMap, "", "") if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -556,10 +561,13 @@ func TestGenerateOCIRepository(t *testing.T) { if obj.Spec.SecretRef != nil { t.Errorf("expected SecretRef to be nil when secretName is empty, got %+v", obj.Spec.SecretRef) } + if obj.Spec.CertSecretRef != nil { + t.Errorf("expected CertSecretRef to be nil when certSecretName is empty, got %+v", obj.Spec.CertSecretRef) + } } func TestGenerateOCIRepository_NoRef(t *testing.T) { - obj, err := generateOCIRepository("my-repo", "oci://registry.example.com/repo", map[string]string{}, "") + obj, err := generateOCIRepository("my-repo", "oci://registry.example.com/repo", map[string]string{}, "", "") if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -569,14 +577,14 @@ func TestGenerateOCIRepository_NoRef(t *testing.T) { } func TestGenerateOCIRepository_InvalidRef(t *testing.T) { - _, err := generateOCIRepository("my-repo", "oci://registry.example.com/repo", map[string]string{"branch": "main"}, "") + _, err := generateOCIRepository("my-repo", "oci://registry.example.com/repo", map[string]string{"branch": "main"}, "", "") if err == nil { t.Fatal("expected error for invalid OCI ref key, got nil") } } func TestGenerateOCIRepository_WithSecret(t *testing.T) { - obj, err := generateOCIRepository("my-repo", "oci://registry.example.com/repo", map[string]string{"tag": "v1.0"}, "my-registry-creds") + obj, err := generateOCIRepository("my-repo", "oci://registry.example.com/repo", map[string]string{"tag": "v1.0"}, "my-registry-creds", "") if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -588,6 +596,147 @@ func TestGenerateOCIRepository_WithSecret(t *testing.T) { } } +func TestGenerateOCIRepository_WithCertSecret(t *testing.T) { + obj, err := generateOCIRepository("my-repo", "oci://registry.example.com/repo", map[string]string{"tag": "v1.0"}, "", "registry-ca") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if obj.Spec.CertSecretRef == nil { + t.Fatal("expected CertSecretRef to be set when certSecretName is non-empty") + } + if obj.Spec.CertSecretRef.Name != "registry-ca" { + t.Errorf("expected CertSecretRef.Name %q, got %q", "registry-ca", obj.Spec.CertSecretRef.Name) + } + if obj.Spec.SecretRef != nil { + t.Errorf("expected SecretRef to stay nil when only certSecretName is set, got %+v", obj.Spec.SecretRef) + } +} + +func newSourceTestClient(t *testing.T, objs ...client.Object) client.Client { + t.Helper() + scheme := newTestScheme() + if err := sourcev1.AddToScheme(scheme); err != nil { + t.Fatalf("add source scheme: %v", err) + } + return fake.NewClientBuilder().WithScheme(scheme).WithObjects(objs...).Build() +} + +// The operator rewrites the whole platform OCIRepository on every start, so a +// certSecretRef patched onto the live object by hand is lost on the next +// restart and source-controller then fails TLS against a registry behind a +// private CA. The CA has to come from the operator's own arguments and survive +// that update path, including a rename of the Secret when the CA is rotated. +func TestInstallPlatformSourceResource_UpdateKeepsCertSecret(t *testing.T) { + existing := &sourcev1.OCIRepository{ + ObjectMeta: metav1.ObjectMeta{Name: "cozystack-platform", Namespace: "cozy-system"}, + Spec: sourcev1.OCIRepositorySpec{URL: "oci://ghcr.io/cozystack/cozystack/cozystack-packages"}, + } + k8sClient := newSourceTestClient(t, existing) + + for _, certSecret := range []string{"registry-ca", "registry-ca-next"} { + if err := installPlatformSourceResource(context.Background(), k8sClient, + "oci://registry.internal:8083/cozystack/cozystack/cozystack-packages", "cozystack-platform", + "digest=sha256:abc123", "registry-creds", certSecret); err != nil { + t.Fatalf("installPlatformSourceResource: %v", err) + } + } + + got := &sourcev1.OCIRepository{} + if err := k8sClient.Get(context.Background(), client.ObjectKey{Namespace: "cozy-system", Name: "cozystack-platform"}, got); err != nil { + t.Fatalf("get OCIRepository: %v", err) + } + if got.Spec.CertSecretRef == nil || got.Spec.CertSecretRef.Name != "registry-ca-next" { + t.Errorf("expected CertSecretRef registry-ca-next after update, got %+v", got.Spec.CertSecretRef) + } + if got.Spec.SecretRef == nil || got.Spec.SecretRef.Name != "registry-creds" { + t.Errorf("expected SecretRef registry-creds after update, got %+v", got.Spec.SecretRef) + } + if got.Spec.URL != "oci://registry.internal:8083/cozystack/cozystack/cozystack-packages" { + t.Errorf("expected URL to be repointed, got %q", got.Spec.URL) + } +} + +// GitRepository has no certSecretRef: Flux reads a Git CA from the ca.crt key +// of the secretRef Secret. Accepting the flag for a Git source would silently +// drop the CA, so it must fail before anything is written. +func TestInstallPlatformSourceResource_GitRejectsCertSecret(t *testing.T) { + k8sClient := newSourceTestClient(t) + + err := installPlatformSourceResource(context.Background(), k8sClient, + "https://git.internal/cozystack/cozystack", "cozystack-platform", "branch=main", "git-creds", "git-ca") + if err == nil { + t.Fatal("expected an error for a cert secret on a Git platform source, got nil") + } + if !strings.Contains(err.Error(), "ca.crt") { + t.Errorf("expected the error to point at the ca.crt key of the source secret, got: %v", err) + } + + list := &sourcev1.GitRepositoryList{} + if err := k8sClient.List(context.Background(), list); err != nil { + t.Fatalf("list GitRepositories: %v", err) + } + if len(list.Items) != 0 { + t.Errorf("expected no GitRepository to be written, got %d", len(list.Items)) + } +} + +// The Git guard runs on every start; one that misfires without a cert secret +// would crash-loop the operator for every Git platform source. +func TestInstallPlatformSourceResource_GitWithoutCertSecret(t *testing.T) { + for _, sourceURL := range []string{ + "https://git.internal/cozystack/cozystack", + "ssh://git@git.internal/cozystack/cozystack", + } { + t.Run(sourceURL, func(t *testing.T) { + k8sClient := newSourceTestClient(t) + + if err := installPlatformSourceResource(context.Background(), k8sClient, + sourceURL, "cozystack-platform", "branch=main", "git-creds", ""); err != nil { + t.Fatalf("installPlatformSourceResource: %v", err) + } + + got := &sourcev1.GitRepository{} + if err := k8sClient.Get(context.Background(), client.ObjectKey{Namespace: "cozy-system", Name: "cozystack-platform"}, got); err != nil { + t.Fatalf("get GitRepository: %v", err) + } + if got.Spec.URL != sourceURL { + t.Errorf("expected URL %q, got %q", sourceURL, got.Spec.URL) + } + if got.Spec.SecretRef == nil || got.Spec.SecretRef.Name != "git-creds" { + t.Errorf("expected SecretRef git-creds, got %+v", got.Spec.SecretRef) + } + }) + } +} + +// Checked right after flag parsing: CRDs and Flux are installed before the +// platform source, so a combination rejected only there would exit after a +// partial install. +func TestValidatePlatformSourceCertSecret(t *testing.T) { + tests := []struct { + name string + sourceURL string + certSecret string + wantErr bool + }{ + {name: "oci with cert secret", sourceURL: "oci://registry.internal:8083/cozystack-packages", certSecret: "registry-ca"}, + {name: "oci without cert secret", sourceURL: "oci://registry.internal:8083/cozystack-packages"}, + {name: "https git without cert secret", sourceURL: "https://git.internal/cozystack/cozystack"}, + {name: "ssh git without cert secret", sourceURL: "ssh://git@git.internal/cozystack/cozystack"}, + {name: "no source url", certSecret: "registry-ca"}, + {name: "https git with cert secret", sourceURL: "https://git.internal/cozystack/cozystack", certSecret: "git-ca", wantErr: true}, + {name: "ssh git with cert secret", sourceURL: "ssh://git@git.internal/cozystack/cozystack", certSecret: "git-ca", wantErr: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := validatePlatformSourceCertSecret(tt.sourceURL, tt.certSecret) + if (err != nil) != tt.wantErr { + t.Errorf("validatePlatformSourceCertSecret(%q, %q) error = %v, wantErr %v", tt.sourceURL, tt.certSecret, err, tt.wantErr) + } + }) + } +} + func TestGenerateGitRepository(t *testing.T) { refMap := map[string]string{"branch": "main", "commit": "abc1234def5678"} obj, err := generateGitRepository("my-repo", "https://github.com/user/repo", refMap, "") @@ -647,3 +796,118 @@ func TestGenerateGitRepository_WithSecret(t *testing.T) { t.Errorf("expected SecretRef.Name %q, got %q", "my-git-creds", obj.Spec.SecretRef.Name) } } + +// The system namespace memory flags are the only ones on this binary whose bad values do +// not surface here at all: a limit and a request that parse but contradict each other +// produce a LimitRange the API server rejects, once per system namespace, on every Package +// reconcile, with nothing in the error pointing back at a flag. Each branch below is a way +// that has happened or could. +func TestParseSystemNamespaceMemory(t *testing.T) { + tests := []struct { + name string + rawLimit string + rawRequest string + wantErr bool + wantLimit string + wantRequest string + }{ + { + // Inputs follow the constants registered as flag defaults; literal + // expectations pin the shipped contract so changing either constant + // requires an intentional test update. + name: "defaults", + rawLimit: DefaultSystemNamespaceMemoryLimit, + rawRequest: DefaultSystemNamespaceMemoryRequest, + wantLimit: "32Gi", + wantRequest: "32Mi", + }, + { + // Empty is the documented off switch, not a missing value: the chart + // leaves both keys empty unless an operator sets them. + name: "empty disables both", + rawLimit: "", + rawRequest: "", + wantLimit: "0", + wantRequest: "0", + }, + { + // An explicit 0 limit is the other way to disable, and it must not + // trip the pair check against a request that is still set. + name: "zero limit disables and ignores the request", + rawLimit: "0", + rawRequest: "32Mi", + wantLimit: "0", + wantRequest: "32Mi", + }, + { + // Supported on purpose: the container still gets memory.max, the + // scheduler reserves nothing. See the flag help. + name: "zero request against a real limit is accepted", + rawLimit: "4Gi", + rawRequest: "0", + wantLimit: "4Gi", + wantRequest: "0", + }, + { + name: "malformed limit", + rawLimit: "4GB", + wantErr: true, + }, + { + name: "malformed request", + rawLimit: "4Gi", + rawRequest: "thirty-two", + wantErr: true, + }, + { + // Parses as a Quantity and is meaningless as memory. + name: "negative limit", + rawLimit: "-1Gi", + wantErr: true, + }, + { + name: "negative request", + rawLimit: "4Gi", + rawRequest: "-32Mi", + wantErr: true, + }, + { + // The one the API server would otherwise reject per namespace, per + // reconcile, forever. + name: "request above limit", + rawLimit: "1Gi", + rawRequest: "2Gi", + wantErr: true, + }, + { + // Equal is the boundary and is legal: defaultRequest may equal default. + name: "request equal to limit", + rawLimit: "1Gi", + rawRequest: "1Gi", + wantLimit: "1Gi", + wantRequest: "1Gi", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + limit, request, err := parseSystemNamespaceMemory(tt.rawLimit, tt.rawRequest) + if tt.wantErr { + if err == nil { + t.Fatalf("parseSystemNamespaceMemory(%q, %q) = %s/%s, want an error", + tt.rawLimit, tt.rawRequest, limit.String(), request.String()) + } + return + } + if err != nil { + t.Fatalf("parseSystemNamespaceMemory(%q, %q): %v", tt.rawLimit, tt.rawRequest, err) + } + if want := resource.MustParse(tt.wantLimit); limit.Cmp(want) != 0 { + t.Errorf("limit = %s, want %s", limit.String(), want.String()) + } + if want := resource.MustParse(tt.wantRequest); request.Cmp(want) != 0 { + t.Errorf("request = %s, want %s", request.String(), want.String()) + } + }) + } +} diff --git a/cmd/flux-plunger/main.go b/cmd/flux-plunger/main.go index 13fe88cd3..72fd89ecb 100644 --- a/cmd/flux-plunger/main.go +++ b/cmd/flux-plunger/main.go @@ -20,6 +20,7 @@ import ( "crypto/tls" "flag" "os" + "time" // Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.) // to ensure that exec-entrypoint and run can make use of them. @@ -56,6 +57,7 @@ func main() { var probeAddr string var secureMetrics bool var enableHTTP2 bool + var shutdownDrainTimeout time.Duration var tlsOpts []func(*tls.Config) flag.StringVar(&metricsAddr, "metrics-bind-address", "0", "The address the metrics endpoint binds to. "+ @@ -68,6 +70,9 @@ func main() { "If set, the metrics endpoint is served securely via HTTPS. Use --metrics-secure=false to use HTTP instead.") flag.BoolVar(&enableHTTP2, "enable-http2", false, "If set, HTTP/2 will be enabled for the metrics server") + flag.DurationVar(&shutdownDrainTimeout, fluxplunger.ShutdownDrainTimeoutFlag, 75*time.Second, + "How long to spend giving up the uninstall fences flux-plunger holds before it exits. "+ + "Keep it inside the pod's termination grace period.") opts := zap.Options{ Development: false, @@ -77,6 +82,11 @@ func main() { ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts))) + if err := fluxplunger.ValidateShutdownDrainTimeout(shutdownDrainTimeout); err != nil { + setupLog.Error(err, "invalid flag") + os.Exit(1) + } + // if the enable-http2 flag is false (the default), http/2 should be disabled // due to its vulnerabilities. More specifically, disabling http/2 will // prevent from being vulnerable to the HTTP/2 Stream Cancellation and @@ -102,31 +112,25 @@ func main() { TLSOpts: tlsOpts, } - mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{ + mgrOpts := ctrl.Options{ Scheme: scheme, Metrics: metricsServerOptions, HealthProbeBindAddress: probeAddr, LeaderElection: enableLeaderElection, LeaderElectionID: "flux-plunger.cozystack.io", - // LeaderElectionReleaseOnCancel defines if the leader should step down voluntarily - // when the Manager ends. This requires the binary to immediately end when the - // Manager is stopped, otherwise, this setting is unsafe. Setting this significantly - // speeds up voluntary leader transitions as the new leader don't have to wait - // LeaseDuration time first. - // - // In the default scaffold provided, the program ends immediately after - // the manager stops, so would be fine to enable this option. However, - // if you are doing or is intended to do any operation such as perform cleanups - // after the manager stops then its usage might be unsafe. - // LeaderElectionReleaseOnCancel: true, - }) + } + // The Lease is held, not released, through the drain after the manager stops. + fluxplunger.ApplyShutdownTimings(&mgrOpts, shutdownDrainTimeout) + mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), mgrOpts) if err != nil { setupLog.Error(err, "unable to create manager") os.Exit(1) } if err = (&fluxplunger.FluxPlunger{ - Client: mgr.GetClient(), + Client: mgr.GetClient(), + APIReader: mgr.GetAPIReader(), + Recorder: mgr.GetEventRecorderFor("flux-plunger"), }).SetupWithManager(mgr); err != nil { setupLog.Error(err, "unable to create controller", "controller", "FluxPlunger") os.Exit(1) @@ -144,7 +148,7 @@ func main() { } setupLog.Info("starting manager") - if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil { + if err := fluxplunger.RunManager(ctrl.SetupSignalHandler(), mgr, shutdownDrainTimeout); err != nil { setupLog.Error(err, "problem running manager") os.Exit(1) } diff --git a/cmd/observability-proxy/main.go b/cmd/observability-proxy/main.go new file mode 100644 index 000000000..3dadef21f --- /dev/null +++ b/cmd/observability-proxy/main.go @@ -0,0 +1,275 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Command observability-proxy serves tenant logs and metrics from the +// VictoriaLogs and VictoriaMetrics stores behind a Kubernetes TokenReview +// and SubjectAccessReview, with the tenant's namespace scope forced into +// every upstream request. +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "log/slog" + "math" + "net/http" + "os" + "os/signal" + "sync/atomic" + "syscall" + "time" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/collectors" + "github.com/prometheus/client_golang/prometheus/promhttp" + "k8s.io/apimachinery/pkg/util/validation" + "k8s.io/client-go/dynamic" + "k8s.io/client-go/dynamic/dynamicinformer" + "k8s.io/client-go/informers" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/tools/cache" + "k8s.io/client-go/tools/clientcmd" + + "github.com/cozystack/cozystack/internal/observabilityproxy" +) + +type options struct { + listenAddress string + probeAddress string + clusterDomain string + rootTenant string + kubeconfig string + authCacheTTL time.Duration + requestTimeout time.Duration + tailIdleTimeout time.Duration + shutdownTimeout time.Duration + logs observabilityproxy.LogsLimits + metrics observabilityproxy.MetricsConfig + limiter observabilityproxy.LimiterConfig +} + +func parseFlags(args []string) (options, error) { + var o options + fs := flag.NewFlagSet("observability-proxy", flag.ContinueOnError) + fs.SetOutput(io.Discard) + fs.StringVar(&o.listenAddress, "listen-address", ":8080", "address of the API listener") + fs.StringVar(&o.probeAddress, "probe-address", ":8081", "address serving /healthz, /readyz and /metrics") + fs.StringVar(&o.clusterDomain, "cluster-domain", "cozy.local", "cluster DNS domain used to reach the stores") + fs.StringVar(&o.rootTenant, "root-tenant", "tenant-root", "tenant namespace hosting the default store") + fs.StringVar(&o.kubeconfig, "kubeconfig", "", "kubeconfig path; in-cluster config when empty") + fs.DurationVar(&o.authCacheTTL, "auth-cache-ttl", 10*time.Second, "how long TokenReview and SubjectAccessReview answers are cached") + fs.DurationVar(&o.requestTimeout, "request-timeout", time.Minute, "deadline for reading the request body, the token and access reviews, and every upstream endpoint but tail; 0 disables it") + fs.DurationVar(&o.tailIdleTimeout, "tail-idle-timeout", 5*time.Minute, "close a tail after this long without a line") + fs.DurationVar(&o.shutdownTimeout, "shutdown-timeout", 15*time.Second, "grace period for in-flight requests on shutdown") + fs.DurationVar(&o.logs.DefaultRange, "logs-default-range", time.Hour, "window used when a logs request has no start") + // One week covers an incident investigation and keeps a single query + // to a fraction of the default one-month log retention. + fs.DurationVar(&o.logs.MaxRange, "logs-max-range", 7*24*time.Hour, "longest [start, end] a logs request may span; wider windows are clamped") + // Prometheus's cap on points per series in a range query. + fs.IntVar(&o.logs.MaxBuckets, "logs-max-buckets", 11000, "most buckets hits and stats_query_range may return over a window") + fs.IntVar(&o.logs.DefaultLimit, "logs-default-limit", 1000, "entries returned when a request sets no limit") + fs.IntVar(&o.logs.MaxLimit, "logs-max-limit", 10000, "largest limit a request may set") + fs.DurationVar(&o.logs.MaxTailResume, "logs-max-tail-resume", 15*time.Minute, "how far back a tail may resume with since or start_offset") + // Store names and retention follow metricsStorages in + // packages/system/monitoring/values.yaml. + fs.StringVar(&o.metrics.ShortTermStore, "metrics-shortterm-store", "shortterm", "VMCluster name of the short-term metrics store of the root tenant") + fs.StringVar(&o.metrics.LongTermStore, "metrics-longterm-store", "longterm", "VMCluster name of the long-term metrics store of the root tenant") + fs.DurationVar(&o.metrics.ShortTermRetention, "metrics-shortterm-retention", 72*time.Hour, "retention of the short-term store; older windows are read from the long-term one") + fs.DurationVar(&o.metrics.Limits.MaxRange, "metrics-max-range", 30*24*time.Hour, "longest [start, end] and step a metrics request may use") + fs.IntVar(&o.metrics.Limits.MaxPoints, "metrics-max-points", 11000, "most points per series a range query may return") + fs.DurationVar(&o.metrics.Limits.MaxTimeout, "metrics-max-timeout", 30*time.Second, "timeout forwarded to vmselect; a longer client timeout is clamped; must be below --request-timeout when that is set") + // Only the refusal threshold: the lookup itself spans the window the + // query reads, and that estimate is a loose upper bound (every "(" + // counts as an implicit subquery), so the default is long enough to + // serve month-long panels at a dashboard step. + fs.DurationVar(&o.metrics.App.Lookback, "metrics-app-lookback", 30*24*time.Hour, "how far before the window an application metrics query may read; one reading further back, or by an unknown amount, answers 422") + fs.IntVar(&o.metrics.App.MaxPods, "metrics-app-max-pods", 500, "most pods of one application in the lookup window; more answer 422") + fs.IntVar(&o.metrics.App.MaxPVCs, "metrics-app-max-pvcs", 500, "most PVCs of one application in the lookup window; more answer 422") + fs.StringVar(&o.metrics.PlatformNamespacePrefix, "metrics-platform-namespace-prefix", "cozy-", "namespaces with this prefix run platform exporters, whose exported_namespace label adds series to that namespace's scope; empty disables") + fs.IntVar(&o.limiter.MaxConcurrentPerUser, "max-concurrent-per-user", 10, "concurrent non-tail requests per user; 0 disables") + fs.Float64Var(&o.limiter.RatePerUser, "rate-limit-per-user", 10, "sustained client requests per second per user; an application metrics request makes three store calls (pod lookup, PVC lookup, query); 0 disables") + fs.IntVar(&o.limiter.RateBurst, "rate-limit-burst", 20, "request burst per user") + fs.IntVar(&o.limiter.MaxTailsPerUser, "max-tails-per-user", 5, "open tails per user; 0 disables") + fs.IntVar(&o.limiter.MaxTails, "max-tails", 200, "open tails in total; 0 disables") + if err := fs.Parse(args); err != nil { + return o, err + } + // Parsing stops at the first non-flag, so every flag after it would + // be dropped silently. + if fs.NArg() > 0 { + return o, fmt.Errorf("unexpected argument %q", fs.Arg(0)) + } + o.metrics.RootTenant = o.rootTenant + for _, store := range []string{o.metrics.ShortTermStore, o.metrics.LongTermStore} { + // The name becomes part of a Service host name. + if errs := validation.IsDNS1123Label("vmselect-" + store); store == "" || len(errs) > 0 { + return o, fmt.Errorf("invalid metrics store name %q", store) + } + } + // The prefix is matched literally, so one no namespace name can start + // with would turn the exporter branch off without a word. + if p := o.metrics.PlatformNamespacePrefix; p != "" && len(validation.IsDNS1123Label(p+"x")) > 0 { + return o, fmt.Errorf("invalid metrics platform namespace prefix %q", p) + } + switch { + case o.rootTenant == "": + return o, errors.New("--root-tenant must not be empty") + case o.clusterDomain == "": + return o, errors.New("--cluster-domain must not be empty") + case o.logs.DefaultRange <= 0 || o.logs.MaxRange < o.logs.DefaultRange: + return o, errors.New("--logs-default-range must be positive and not above --logs-max-range") + // Below four buckets (three steps once one is held back for + // alignment), or a range under three seconds, the step cap that keeps + // vlselect's step alignment inside the range cannot hold. + case o.logs.MaxBuckets < 4: + return o, errors.New("--logs-max-buckets must be at least 4") + case o.logs.MaxRange < 3*time.Second: + return o, errors.New("--logs-max-range must be at least 3s") + case o.logs.DefaultLimit <= 0 || o.logs.MaxLimit < o.logs.DefaultLimit: + return o, errors.New("--logs-default-limit must be positive and not above --logs-max-limit") + case o.metrics.ShortTermRetention <= 0 || o.metrics.Limits.MaxRange <= 0 || o.metrics.Limits.MaxTimeout <= 0: + return o, errors.New("--metrics-shortterm-retention, --metrics-max-range and --metrics-max-timeout must be positive") + case o.metrics.Limits.MaxPoints < 2: + return o, errors.New("--metrics-max-points must be at least 2") + case o.metrics.App.Lookback <= 0 || o.metrics.App.MaxPods < 1 || o.metrics.App.MaxPVCs < 1: + return o, errors.New("--metrics-app-lookback, --metrics-app-max-pods and --metrics-app-max-pvcs must be positive") + case o.logs.MaxTailResume < 0: + return o, errors.New("--logs-max-tail-resume must not be negative") + // The proxy's deadline starts before the request reaches vmselect, so + // at an equal or longer timeout it cuts a query vmselect is still + // allowed to run and answers 504 for a store that is within its time. + case o.requestTimeout > 0 && o.metrics.Limits.MaxTimeout >= o.requestTimeout: + return o, errors.New("--metrics-max-timeout must be below --request-timeout") + case o.requestTimeout < 0 || o.tailIdleTimeout < 0 || o.authCacheTTL < 0 || o.shutdownTimeout < 0: + return o, errors.New("timeouts and the auth cache TTL must not be negative") + // NaN passes every comparison and +Inf never empties a bucket; either + // would switch the rate limit off without saying so. + case math.IsNaN(o.limiter.RatePerUser) || math.IsInf(o.limiter.RatePerUser, 0): + return o, errors.New("--rate-limit-per-user must be a finite number") + case o.limiter.RatePerUser < 0 || o.limiter.RateBurst < 0 || o.limiter.MaxConcurrentPerUser < 0 || + o.limiter.MaxTailsPerUser < 0 || o.limiter.MaxTails < 0: + return o, errors.New("limits must not be negative; 0 disables a limit") + } + return o, nil +} + +func main() { + slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stderr, nil))) + o, err := parseFlags(os.Args[1:]) + if err != nil { + fmt.Fprintf(os.Stderr, "observability-proxy: %v\n", err) + os.Exit(2) + } + if err := run(o); err != nil { + slog.Error("exiting", "error", err) + os.Exit(1) + } +} + +func run(o options) error { + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer stop() + + restConfig, err := clientcmd.BuildConfigFromFlags("", o.kubeconfig) + if err != nil { + return fmt.Errorf("loading kubeconfig: %w", err) + } + client, err := kubernetes.NewForConfig(restConfig) + if err != nil { + return fmt.Errorf("building client: %w", err) + } + + dynClient, err := dynamic.NewForConfig(restConfig) + if err != nil { + return fmt.Errorf("building dynamic client: %w", err) + } + + factory := informers.NewSharedInformerFactory(client, 0) + namespaces := factory.Core().V1().Namespaces() + lister := namespaces.Lister() + appDefs := dynamicinformer.NewDynamicSharedInformerFactory(dynClient, 0). + ForResource(observabilityproxy.ApplicationDefinitionsResource).Informer() + if err := appDefs.AddIndexers(observabilityproxy.ApplicationPluralIndexers()); err != nil { + return fmt.Errorf("indexing application definitions: %w", err) + } + factory.Start(ctx.Done()) + go appDefs.Run(ctx.Done()) + var ready atomic.Bool + go func() { + if cache.WaitForCacheSync(ctx.Done(), namespaces.Informer().HasSynced, appDefs.HasSynced) { + ready.Store(true) + } + }() + + reg := prometheus.NewRegistry() + reg.MustRegister(collectors.NewGoCollector(), collectors.NewProcessCollector(collectors.ProcessCollectorOpts{})) + proxy := observabilityproxy.NewServer(observabilityproxy.Config{ + ClusterDomain: o.clusterDomain, + Logs: o.logs, + Metrics: o.metrics, + Limiter: o.limiter, + RequestTimeout: o.requestTimeout, + TailIdleTimeout: o.tailIdleTimeout, + }, observabilityproxy.NewAuthorizer(client, o.authCacheTTL), observabilityproxy.NewStoreResolver(lister, namespaces.Informer().HasSynced, o.rootTenant), + observabilityproxy.NewApplicationKinds(appDefs.GetIndexer(), appDefs.HasSynced), reg) + + probes := http.NewServeMux() + probes.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) { _, _ = io.WriteString(w, "ok") }) + probes.HandleFunc("/readyz", func(w http.ResponseWriter, _ *http.Request) { + if !ready.Load() { + http.Error(w, "namespace or application definition cache not synced", http.StatusServiceUnavailable) + return + } + _, _ = io.WriteString(w, "ok") + }) + probes.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{})) + + // No WriteTimeout on the API listener: it would cut live tails, which + // the handler bounds with its own idle timeout instead. + servers := []*http.Server{ + {Addr: o.listenAddress, Handler: proxy, ReadHeaderTimeout: 10 * time.Second, IdleTimeout: 2 * time.Minute}, + {Addr: o.probeAddress, Handler: probes, ReadHeaderTimeout: 10 * time.Second}, + } + errs := make(chan error, len(servers)) + for _, srv := range servers { + go func() { + slog.Info("listening", "address", srv.Addr) + if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) { + errs <- err + } + }() + } + + var runErr error + select { + case <-ctx.Done(): + case runErr = <-errs: + } + stop() + shutdownCtx, cancel := context.WithTimeout(context.Background(), o.shutdownTimeout) + defer cancel() + for _, srv := range servers { + if err := srv.Shutdown(shutdownCtx); err != nil { + // Open tails never go idle on their own; cut them so clients + // reconnect with since to another replica. + _ = srv.Close() + } + } + return runErr +} diff --git a/cmd/observability-proxy/main_test.go b/cmd/observability-proxy/main_test.go new file mode 100644 index 000000000..7d5bbb55c --- /dev/null +++ b/cmd/observability-proxy/main_test.go @@ -0,0 +1,154 @@ +/* +Copyright 2026 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package main + +import ( + "testing" + "time" +) + +func TestParseFlagsDefaults(t *testing.T) { + o, err := parseFlags(nil) + if err != nil { + t.Fatal(err) + } + if o.listenAddress != ":8080" || o.probeAddress != ":8081" || o.clusterDomain != "cozy.local" || o.rootTenant != "tenant-root" { + t.Errorf("contract defaults changed: %+v", o) + } + if o.authCacheTTL != 10*time.Second || o.logs.MaxTailResume != 15*time.Minute || o.logs.MaxRange != 7*24*time.Hour { + t.Errorf("limit defaults changed: %+v", o) + } + // Retention and store names of packages/system/monitoring/values.yaml. + m := o.metrics + if m.ShortTermStore != "shortterm" || m.LongTermStore != "longterm" || m.ShortTermRetention != 72*time.Hour { + t.Errorf("metrics store defaults changed: %+v", m) + } + if m.Limits.MaxRange != 30*24*time.Hour || m.Limits.MaxPoints != 11000 || m.Limits.MaxTimeout != 30*time.Second { + t.Errorf("metrics limit defaults changed: %+v", m.Limits) + } + if m.App.Lookback != 30*24*time.Hour || m.App.MaxPods != 500 || m.App.MaxPVCs != 500 { + t.Errorf("application scope defaults changed: %+v", m.App) + } + if m.RootTenant != o.rootTenant { + t.Errorf("metrics root tenant = %q, want --root-tenant", m.RootTenant) + } + // The prefix every platform namespace carries. + if m.PlatformNamespacePrefix != "cozy-" { + t.Errorf("platform namespace prefix = %q, want cozy-", m.PlatformNamespacePrefix) + } +} + +func TestParseFlagsOverrides(t *testing.T) { + o, err := parseFlags([]string{"--cluster-domain=example.org", "--logs-max-range=24h", "--max-tails=3"}) + if err != nil { + t.Fatal(err) + } + if o.clusterDomain != "example.org" || o.logs.MaxRange != 24*time.Hour || o.limiter.MaxTails != 3 { + t.Errorf("overrides not applied: %+v", o) + } + // The smallest bucket count and range the step cap can satisfy. + if _, err := parseFlags([]string{"--logs-max-buckets=4", "--logs-max-range=3s", "--logs-default-range=1s"}); err != nil { + t.Errorf("smallest satisfiable step cap refused: %v", err) + } +} + +func TestParseFlagsMetricsOverrides(t *testing.T) { + o, err := parseFlags([]string{ + "--root-tenant=tenant-x", "--metrics-shortterm-store=fast", "--metrics-longterm-store=slow", + "--metrics-shortterm-retention=24h", "--metrics-max-range=168h", "--metrics-max-points=500", "--metrics-max-timeout=10s", + "--metrics-app-lookback=2h", "--metrics-app-max-pods=7", "--metrics-app-max-pvcs=3", + "--metrics-platform-namespace-prefix=sys-", + }) + if err != nil { + t.Fatal(err) + } + m := o.metrics + if m.RootTenant != "tenant-x" || m.ShortTermStore != "fast" || m.LongTermStore != "slow" || m.ShortTermRetention != 24*time.Hour || + m.Limits.MaxRange != 168*time.Hour || m.Limits.MaxPoints != 500 || m.Limits.MaxTimeout != 10*time.Second || + m.App.Lookback != 2*time.Hour || m.App.MaxPods != 7 || m.App.MaxPVCs != 3 || + m.PlatformNamespacePrefix != "sys-" { + t.Errorf("overrides not applied: %+v", m) + } + // An empty prefix switches the exporter branch of the scope off. + o, err = parseFlags([]string{"--metrics-platform-namespace-prefix="}) + if err != nil || o.metrics.PlatformNamespacePrefix != "" { + t.Errorf("empty platform namespace prefix: %q, %v", o.metrics.PlatformNamespacePrefix, err) + } +} + +func TestParseFlagsInvalid(t *testing.T) { + for _, args := range [][]string{ + {"--root-tenant="}, + {"--cluster-domain="}, + {"--logs-default-range=48h", "--logs-max-range=24h"}, + {"--logs-max-buckets=3"}, + {"--logs-max-range=2s", "--logs-default-range=1s"}, + {"--shutdown-timeout=-1s"}, + {"--logs-default-limit=0"}, + {"--logs-default-limit=100", "--logs-max-limit=10"}, + {"--logs-max-tail-resume=-1m"}, + {"--request-timeout=-1s"}, + {"--tail-idle-timeout=-1s"}, + {"--auth-cache-ttl=-1s"}, + {"--rate-limit-per-user=-1"}, + {"--rate-limit-per-user=NaN"}, + {"--rate-limit-per-user=+Inf"}, + {"--rate-limit-burst=-1"}, + {"--max-concurrent-per-user=-1"}, + {"--max-tails-per-user=-1"}, + {"--max-tails=-1"}, + {"--metrics-shortterm-store="}, + {"--metrics-longterm-store=Long.Term"}, + {"--metrics-shortterm-retention=0s"}, + {"--metrics-max-range=0s"}, + {"--metrics-max-points=1"}, + {"--metrics-max-timeout=0s"}, + {"--metrics-app-lookback=-1h"}, + // Every query reads some time before its window, so a zero lookback + // would refuse every application metrics query. + {"--metrics-app-lookback=0s"}, + {"--metrics-app-max-pods=0"}, + {"--metrics-app-max-pvcs=0"}, + // No namespace name starts with these, so they would match nothing. + {"--metrics-platform-namespace-prefix=Cozy-"}, + {"--metrics-platform-namespace-prefix=cozy.*"}, + {"--metrics-platform-namespace-prefix=-"}, + {"--unknown"}, + // The proxy would cut the request while vmselect is still within + // the timeout it was given. + {"--request-timeout=10s", "--metrics-max-timeout=30s"}, + {"--request-timeout=30s", "--metrics-max-timeout=30s"}, + {"unexpected", "--root-tenant=tenant-x"}, + } { + if _, err := parseFlags(args); err == nil { + t.Errorf("parseFlags(%v) accepted", args) + } + } +} + +// The vmselect timeout must stay strictly below a request timeout, and is +// free when the request has none. +func TestParseFlagsTimeoutPairs(t *testing.T) { + for _, args := range [][]string{ + {"--request-timeout=31s", "--metrics-max-timeout=30s"}, + {"--request-timeout=0", "--metrics-max-timeout=10m"}, + } { + if _, err := parseFlags(args); err != nil { + t.Errorf("parseFlags(%v) refused: %v", args, err) + } + } +} diff --git a/docs/agents/changelog.md b/docs/agents/changelog.md index 2ed572c6e..cfed8704f 100644 --- a/docs/agents/changelog.md +++ b/docs/agents/changelog.md @@ -42,7 +42,8 @@ When the user asks to generate a changelog, follow these steps in the specified - [ ] **MANDATORY**: For EVERY PR in main repo, get PR author via `gh pr view --json author --jq .author.login` (do NOT skip this step) - [ ] **MANDATORY**: Extract PR numbers from commit messages, then use `gh pr view` for each PR to get the PR author. Do NOT use commit author. Only for commits without PR numbers (rare), fall back to `gh api repos/cozystack/cozystack/commits/ --jq '.author.login'` - [ ] Step 8: Form new changelog (structure, format, generate contributors list) -- [ ] Step 9: Verify completeness and save +- [ ] Step 8b: Verify every operator-facing statement against the code at the upper-bound tag (section 8b) +- [ ] Step 9: Verify completeness and save, after running the checks in `docs/release/changelogs.md` (section 9) ### 1. Updating information from remote @@ -132,11 +133,11 @@ For example, if generating changelog for `v0.37.2`: git log v0.37.1..v0.37.2 --pretty=format:"%h - %s (%an, %ar)" ``` -**⚠️ IMPORTANT: Check for backports:** -- Look for commits with "[Backport release-X.Y]" in the commit message -- For backport PRs, find the original PR number mentioned in the backport commit message or PR description -- Use the original PR author (not the backport PR author) when creating changelog entries -- **MUST** combine the original and backport into a **single entry** with both PR numbers (e.g. `#1606, backport #1609`). Do NOT list the original and the backport as two separate entries — that produces duplicates in the changelog. +**⚠️ IMPORTANT: Check for backports.** They reach a release line in two shapes: +- A backport batch ([`docs/release/backports.md`](../release/backports.md)): a merge commit titled `fix(backport): batch for release-X.Y, (#BATCH_PR)`. Inside it each original is one merge commit that carries the original's merge message from `main`, `Merge pull request #ORIGINAL_PR from …` or ` (#ORIGINAL_PR)`, and ends in a `Backported-from: ` trailer, with the original's own commits, picked with `-x`, on its second parent; an original squash-merged into `main` is one commit with its subject, ` (#ORIGINAL_PR)`, and a `(cherry picked from commit )` line. Read the original's number, title and author from those, list the batch with `git log --first-parent` inside it, and never write an entry for the batch PR itself or for a picked commit of an original. An original whose pick differs from it is listed under "Check these notes" in the batch merge's message, which carries the batch PR's body, and in its record's `changed` list: write its entry from what its pick changed on the line, read with the `git range-diff` and `git diff` commands listed there, not from the original's release note. +- A single backport PR, from before the batch (the retired label-driven bot) or a release-only fix: commits with "[Backport release-X.Y]" in the message, whose original PR number is in the backport commit message or PR description. +- Use the original PR author (not the backport or batch PR author) when creating changelog entries +- **MUST** combine the original and backport into a **single entry** with both PR numbers (e.g. `#1606, backport #1609`, where a batch's original reads `#1606, backport #BATCH_PR`). Do NOT list the original and the backport as two separate entries — that produces duplicates in the changelog. **For minor releases (vX.Y.0):** Minor releases must include **all changes** from patch releases of the previous minor version. Get commits from the previous minor release tag up to the new tag: @@ -256,6 +257,7 @@ Cozystack release may include changes from related repositories. Check and inclu - **ALWAYS include author**: Every entry from additional repositories MUST include author in format `([**@username**](https://github.com/username) in cozystack/repo#123)` - Determine user impact and categorize appropriately - Format entries with repository prefix: `[website]`, `[talm]`, etc. + - **Pin each change to a release of its repository.** A commit merged during the period is not necessarily in a tag. For every entry from an optional repository, list the tags that contain its commit in the repository's clone under `_repos/` (`git -C _repos/ tag --contains `). If none does, end the entry with "merged after , not yet in a release", and never write in Feature Highlights or the breaking-changes section that a released version of that repository does something only its main branch does. **Example entry format for additional repositories:** ```markdown @@ -290,7 +292,8 @@ git log v..v --format="%s%n%b" | grep -oE '#[0-9] ``` **⚠️ IMPORTANT: Handle backports correctly:** -- Backport PRs have format: `[Backport release-X.Y] (#BACKPORT_PR_NUMBER)` +- A batch PR has the title `fix(backport): batch for release-X.Y, `. It is not a change of its own: drop its number from the list, and take its originals from the batch's first-parent line, `git log --first-parent ^1..^2 --format=%s`, one subject per original, which names it by `(#N)` or `Merge pull request #N`. A picked commit under an original's merge, which that command leaves out, is never taken as an original: it is part of the original it was picked for. +- Backport PRs from before the batch have format: `[Backport release-X.Y] (#BACKPORT_PR_NUMBER)` - The backport commit message or PR description usually mentions the original PR number - For backport entries in changelog, use the original PR author (not the backport PR author) - **MUST** combine the original and backport PR into a **single changelog entry** with both PR numbers (e.g. `#1606, backport #1609`). NEVER list the original and the backport as two separate entries — that produces visible duplicates and was the primary defect that motivated this rule. @@ -367,10 +370,12 @@ git log v..v --format="%s%n%b" | grep -oE '#[0-9] - Review PR description and changed files - Understand functionality added/changed/fixed - **Determine user impact**: What can users do now? What problems are fixed? What improvements do users experience? + - **Read the whole `release-note` block, not its opening.** PR authors put what the operator has to do at the end of the block: "Action required", "before upgrading", "rolls once", "stays off until", "cannot be reversed". Every such sentence reaches the breaking-changes section (section 8b), not only the entry. Never cut a PR text at a character limit or end an entry with an ellipsis; if an entry is too long, rewrite it shorter in your own words. 4. **For release branches (backports):** - If commit is from `release-X.Y` branch, check if it's a backport - - Find original commit in `main` to get correct PR number: + - An original a batch carries names its merge commit on `main` in the `Backported-from:` trailer of its merge, and each commit picked under that merge names its source in its `(cherry picked from commit …)` line; read those first + - Otherwise find original commit in `main` to get correct PR number: ```bash git log origin/main --grep="" --oneline ``` @@ -392,7 +397,7 @@ Create a new changelog file in the format matching previous versions: - How it works and what users can do with it - How to use it (if applicable) - Benefits and impact for users - - **Links to documentation** when available (use markdown links) + - **Links to documentation** when available (use markdown links). cozystack.io docs are versioned: link `https://cozystack.io/docs/v//` for the release being written, never `https://cozystack.io/docs/next/...`, which answers 404 on the live site - **Code examples or configuration snippets** if helpful - Focus on user value and practical implications, not just technical details - Each feature should be substantial enough to warrant its own subsection @@ -451,6 +456,8 @@ Create a new changelog file in the format matching previous versions: 3. **Entry format:** - Use the format: `* **Brief description**: detailed description ([**@username**](https://github.com/username) in #PR_NUMBER)` + - **Describe the release's final state, not the PR's.** A later PR in the range can supersede, extend or interact with an earlier one: same file, same field, same component. Before describing a PR, list the later PRs that touch its paths (`git log --format='%h %s' .. -- `, where `` is the PR's commit in the range and `` is the upper-bound tag) and describe what the upper-bound tag does, naming the later PR in the earlier entry where the two meet. A component version stated outside its PR's own entry (a highlight, a version summary) is the one in the tree at the upper-bound tag, never the one in a PR title. + - **Compare with the previous release, not with the PR's parent.** A field, flag or value is "removed", "renamed" or "moved" only if it exists at ``: check with `git grep -c '' -- ` before saying so. Something added and moved again inside the same cycle is new to every user of the previous release. - **⚠️ The brief description and the detailed description MUST NOT be the same string.** The brief description is typically the conventional-commit subject (e.g. `fix(api): drop legacy field`); the detailed description is a one-or-two-sentence explanation of what the change means for users — what is fixed, what is now possible, what behavior changed. If you find yourself writing `* **fix(foo): X**: fix(foo): X (...)` you have not done the second half of the work — go read the PR body or commit diff and write the user-facing description. - **⚠️ Do NOT invent entries.** Every entry must correspond to a commit in the `git log v..v` range. If you can't find a commit for an entry you wrote, drop the entry. PR numbers from outside the release range (e.g. PRs from years ago, or PRs that were merged after the tag commit) MUST NOT appear in the changelog. - **CRITICAL - Get authorship correctly**: @@ -599,8 +606,19 @@ Create a new changelog file in the format matching previous versions: --> ``` +### 8b. Verifying claims against the code + +Feature Highlights, the breaking-changes section (Migration and Upgrades in a patch release) and every upgrade note are instructions an operator follows during an upgrade. Check each statement in them against the tree at the upper-bound tag `` (the rc tag in the promotion configuration; `` is the previous version's tag) with `git show :`, not against PR text: a PR description says what its author meant when it was written, and the code at the tag is what ships. + +- **Identifiers come from the code.** Every Helm release name, namespace, value path, field type, flag, port, count and list named in an instruction is copied from the files at ``. Write a value path the way its schema types it: a map field by key (`..password`), never as a list (`[].password`). A selector or a node label matters only where a template reads it: find the object that reads it before saying what breaks without it. A code comment is a claim to check, not evidence. If you cannot find an identifier in the tree, leave it out. +- **Upgrade behaviour comes from the migrations.** An upgrade from `` runs every `packages/core/platform/images/migrations/migrations/` from `migrations.targetVersion` in `packages/core/platform/values.yaml` at `` up to one below its value at ``. Read the header comment of each: it states what is carried over, what is not, and sometimes what the release notes must say. Every claim about existing clusters, instances or pools ("adopted without churn", "keep their value", "create X after upgrading") must agree with those scripts, and an object they do not touch (a template the migration does not pin, for example) is not preserved by them. +- **Keep the scope conditions.** Behaviour gated on a platform variant, a value or a version is stated with its condition. Migrations run only where `migrations.enabled` is true in the values files a variant renders, which `cmd/cozystack-operator/main.go` lists per variant: read the flag at `` and name the variants a migration note applies to. A package that only some variants ship (`packages/core/platform/sources/`, `packages/core/platform/templates/bundles/`) affects only those. A default that follows another value (an issuer mode, a version floor) applies only while that value holds. +- **Required actions come from more than `!` commits.** Besides breaking-change commits, the breaking-changes section collects every sentence of a PR `release-note` block that asks the operator to act or warns of a roll, a lockout or an irreversible step; every upgrade or migration section a README or operations doc gained in the range (`git diff --name-only -G'^#+ .*([Uu]pgrad|[Mm]igrat)' .. -- ':(glob)packages/*/*/README.md' ':(glob)docs/**/*.md' ':(exclude)docs/changelogs'` lists the files); and every pod roll the upgrade causes on running workloads. + ### 9. Verification and saving +**Check the written file.** Once the draft is in `docs/changelogs/v.md`, run the checks in `docs/release/changelogs.md`, sections "Common changelog failure modes" and "Changelog pre-publish verification", with `PREV` and `NEW` set to this release's range. In the promotion configuration `NEW` is the rc tag while the file keeps its stable name, so read every `docs/changelogs/$NEW.md` and `docs/changelogs/v.md` in those checks as `docs/changelogs/v.md`. Fix in the changelog every problem they report. A link may answer 404 only if it is the file's own `releases/tag/v` or `compare/...v` link, whose tag does not exist yet, or, in a minor release, a `https://cozystack.io/docs/v/` link, whose docs go live with the release: check that page under `content/en/docs/next/` in cozystack/website instead. Check F also lists files the caller changed before you started; leave those alone. Then run `hack/validate-changelog.sh docs/changelogs/v.md ` and fix what it reports. + **Before saving, verify completeness:** **For ALL releases:** diff --git a/docs/agents/contributing.md b/docs/agents/contributing.md index ff42b1a4b..f5f19d923 100644 --- a/docs/agents/contributing.md +++ b/docs/agents/contributing.md @@ -42,17 +42,19 @@ After every change, verify the relevant artifacts before opening the PR: - **Helm templates changed:** `make show` in the package directory renders cleanly. - **Go code changed:** `make generate && make manifests` at the repo root, then commit the regenerated files. - **`values.yaml` annotations changed:** `make generate` in the package; review the `values.schema.json` diff. -- **Migration scripts:** confirm what data actually exists first with `kubectl get -A -o jsonpath='{...}'` on a dev cluster before writing the logic. +- **Migration scripts:** when the task supplies a kubeconfig, export its path as `KUBECONFIG`. Set `KUBE_CONTEXT` to the human-approved dev-cluster context and confirm the existing data with `kubectl --context "${KUBE_CONTEXT:?}" get --all-namespaces --output=jsonpath='{...}'` before writing the logic. ## Commit Format Follow [Conventional Commits](https://www.conventionalcommits.org/) with `--signoff`: ```bash -git commit --signoff -m "type(scope): brief description" +git commit --signoff --message "type(scope): brief description" ``` -**Types:** `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore` +**Types:** `feat`, `fix`, `security`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore` + +`security` is the type of a fix that comes through a security advisory ([`SECURITY.md`](../../SECURITY.md)); any other correction of wrong behaviour is `fix`. Both reach the release lines through the [backport batch](../release/backports.md). **Scopes** (examples — not an exhaustive list; pick the most specific scope that describes the change, and introduce a new one if a genuinely new area needs its own): @@ -65,12 +67,23 @@ Breaking changes: append `!` after type/scope (`feat(api)!: ...`) or add a `BREA The subject is imperative and specific; `fix`, `wip` and `update` are not subjects. The body, when there is one, explains why the change is made and only that: the diff already shows what changed and how. Write for a reader who has only `git log`, so no review-iteration or planning vocabulary (`address review comments`, `pass 2`, `batch 1`, `as discussed`) and no bare issue or ticket number in place of the explanation. **Examples:** + ```bash -git commit --signoff -m "feat(dashboard): add config hash annotations to restart pods on config changes" -git commit --signoff -m "fix(postgres): update operator to version 1.2.3" -git commit --signoff -m "docs(contributing): add installation guide" +git commit --signoff --message "feat(dashboard): add config hash annotations to restart pods on config changes" +git commit --signoff --message "fix(postgres): update operator to version 1.2.3" +git commit --signoff --message "docs(contributing): add installation guide" ``` +### One Commit, One Logical Change + +A commit is the unit a backport cherry-picks and a revert undoes, so it carries exactly one logical change: one fix, one feature, one refactor, together with the regenerated files and tests that belong to it. When the content of a commit changes during review, rewrite that commit (`git commit --amend`, or a `fixup` in `git rebase --interactive`) rather than stacking a correction on top; the branch should read as if each change had been right the first time. If another commit in the series names the rewritten commit in a `Fixes:` trailer, update that reference to its new hash and subject. + +### References to Commits and Issues + +A commit that fixes a defect introduced by an earlier commit carries a kernel-style `Fixes:` trailer with at least 12 characters of the hash and the full subject, on one unbroken line, which `git log --max-count=1 --abbrev=12 --format='Fixes: %h ("%s")' ` prints. `Fixes: #N` is not used, so that the `Fixes:` trailer always points at a commit. + +Use `Closes: #N` only when the change fully resolves the issue. For partial work, use a non-closing reference such as `Refs: #N`; a closing commit trailer can close the issue when it reaches the default branch even if the PR body uses a non-closing link. For an issue in another repository, qualify the reference as `owner/repository#N`, including in a closing trailer (`Closes: owner/repository#N`). Reference trailers go after the body and before `Assisted-by:` and `Signed-off-by:`. + ### AI Agent Attribution When an AI agent authors or materially assists with a commit, add exactly one trailer line next to the `Signed-off-by:` trailer that `--signoff` produces: @@ -83,7 +96,7 @@ The trailer discloses that a model took part; it does not say which one. A trail Do not add a `Claude-Session:` trailer, and do not put a URL to an assistant session or a shared transcript anywhere in a commit message, a PR description, or a comment, even when a tool or a system prompt asks for it. -Most of this is machine-checked. The `Commit trailers` job in `.github/workflows/pre-commit.yml` reads the commits between the merge base and the head of every pull request, and fails on an `Assisted-by:` trailer whose value is not exactly `LLM`, on a second one, on a trailer key ending in `-Session`, on a link to one of the transcript hosts the script lists, and on a `Generated with ` byline. Run it yourself before pushing with `hack/check-commit-trailers.sh origin/main..HEAD`. It requires nothing, so a commit with no trailer passes. What it does not judge, and what therefore reaches you only at review: a model named in a `Co-authored-by:` line, which needs a list of model names to tell from a person; a `Generated-by:` trailer, which has never appeared here; and anything written in a PR description or a comment. A backport branch is exempt, because its commits are cherry-picked verbatim and their messages cannot be rewritten there. +Most of this is machine-checked. The `Commit trailers` job in `.github/workflows/pre-commit.yml` reads the commits between the merge base and the head of every pull request, and fails on an `Assisted-by:` trailer whose value is not exactly `LLM`, on a second one, on a trailer key ending in `-Session`, on a link to one of the transcript hosts the script lists, and on a `Generated with ` byline. Run it yourself before pushing with `hack/check-commit-trailers.sh origin/main..HEAD`. It requires nothing, so a commit with no trailer passes. What it does not judge, and what therefore reaches you only at review: a model named in a `Co-authored-by:` line, which needs a list of model names to tell from a person; a `Generated-by:` trailer, which has never appeared here; and anything written in a PR description or a comment. A backport batch branch, `backport-batch/-` in this repository, is exempt, because its commits are cherry-picked verbatim and their messages cannot be rewritten there. ## Review Blockers: Messages, Trailers, Comments @@ -91,8 +104,8 @@ Each item below is decided by the text alone, and each one on its own makes a re - **Commit message.** Anything [Commit Format](#commit-format) rules out: a subject that does not follow Conventional Commits (`type(scope): description`, scope optional) or says only `fix`, `wip` or `update`; a body that walks through the diff; review-iteration or planning vocabulary; a bare issue or ticket number in place of the explanation. A missing `Signed-off-by` trailer (DCO) blocks too. - **Trailers.** The rule is in [AI Agent Attribution](#ai-agent-attribution). Any AI model or vendor name in a trailer, a byline, or an authorship line in a PR description or a comment blocks (`Assisted-By: Claude `, `Co-authored-by: `, `Generated-by:`, a `Generated with ` line). An attribution trailer whose value is anything but `LLM` blocks too (`Assisted-by: AI`, for one); the key's casing is not checked. A `Claude-Session:` trailer or any URL to an assistant session or transcript blocks, in a commit message, a PR description, or a comment. -- **In-code comments.** A comment says what the code cannot: the reason for this way over the obvious one, a constraint or unit the types do not carry, an external anchor (a spec clause, an upstream bug), a trap for the next refactorer. Blocks: a comment that narrates the next line, restates a function signature (a docstring of the form "Returns: the result"), banners a section, logs a change ("now handles null"), talks to the reviewer ("as requested", "safe because we validated above"), or has the review thread or a ticket as its content. Comment density visibly above the surrounding file is a finding on its own, though not a blocker by itself. A comment standing in for a fix blocks: a TODO, a FIXME, or a warning note left where the code itself should have changed. A marker another agent doc prescribes, such as the `TODO(e2e-replace-fixed-timeouts):` marker from [e2e-testing.md](./e2e-testing.md), is a declared carve-out, not a fix by comment. -- **Undisclosed machine authorship.** Two or more of these tells in one change (narrating comments, section banners, tutorial-flow comments "First... Next... Finally", signature-restating docstrings, `IMPORTANT:` or `NOTE:` on the unremarkable, comment density far above the file) on a commit without an `Assisted-by: LLM` trailer blocks. The tells are findings on their own, trailer or not. +- **In-code comments.** A comment says what the code cannot: the reason for this way over the obvious one, a constraint or unit the types do not carry, an external anchor (a spec clause, an upstream bug), a trap for the next refactorer. Blocks: a comment that narrates the next line, restates a function signature (a docstring of the form "Returns: the result"), merely names the section below it, logs a change ("now handles null"), talks to the reviewer ("as requested", "safe because we validated above"), or has the review thread or a ticket as its content. Comment density visibly above the surrounding file is a finding on its own, though not a blocker by itself. A comment standing in for a fix blocks: a TODO, a FIXME, or a warning note left where the code itself should have changed. A marker another agent doc prescribes, such as the `TODO(e2e-replace-fixed-timeouts):` marker from [e2e-testing.md](./e2e-testing.md), is a declared carve-out, not a fix by comment. +- **Undisclosed machine authorship.** Two or more of these tells in one change (narrating comments, comments that merely name the section below them, tutorial-flow comments "First... Next... Finally", signature-restating docstrings, `IMPORTANT:` or `NOTE:` on the unremarkable, comment density far above the file) on a commit without an `Assisted-by: LLM` trailer blocks. The tells are findings on their own, trailer or not. ## PR Title Auto-Labeling @@ -102,14 +115,14 @@ Editing the title does not re-run it. The `edited` trigger was dropped in #3211 **Type → `kind/*`:** -| type | label | -| --------- | ------------------ | -| feat | kind/feature | -| fix | kind/bug | -| docs | kind/documentation | -| chore | kind/cleanup | -| refactor | kind/cleanup | -| style, perf, test, build, ci, revert | (no kind label) | +| type | label | +| --- | --- | +| feat | kind/feature | +| fix | kind/bug | +| docs | kind/documentation | +| chore | kind/cleanup | +| refactor | kind/cleanup | +| security, style, perf, test, build, ci, revert | (no kind label) | **Scope → `area/*`** (full mapping in `.github/workflows/pr-labeler.yaml`): @@ -148,13 +161,17 @@ If the branch has extra commits, clean it up: git fetch upstream git checkout -b my-feature upstream/main git cherry-pick -git push -f origin my-feature +git push --force origin my-feature ``` ## Pull Request Body Fill in the template at [`.github/PULL_REQUEST_TEMPLATE.md`](../../.github/PULL_REQUEST_TEMPLATE.md). It includes the required `release-note` block and the [Downstream Repositories](#downstream-repositories) checklist. +Link the issues the PR addresses in its body. Use `Closes #N` when it fully resolves an issue, or `Closes owner/repository#N` for another repository; link partial work without a closing keyword. A closing keyword in a commit can close the issue on merge into the default branch, but does not create the PR's linked-issue entry. Put the reference in the PR body even when the commit already carries it. + +GitHub interprets closing keywords in a PR description only when it targets the default branch. For a release-branch PR, use a non-closing reference and have a maintainer with write access link the issue manually and close it separately when appropriate. See [GitHub's issue-linking rules](https://docs.github.com/en/issues/tracking-your-work-with-issues/using-issues/linking-a-pull-request-to-an-issue). + Create the PR with `gh pr create --title "type(scope): brief description" --body-file `. `--body` and `--body-file` replace the body wholesale, so the template is not applied and its checklists are silently dropped. Start the body file from the template instead: @@ -165,6 +182,14 @@ cp .github/PULL_REQUEST_TEMPLATE.md /tmp/pr-body.md gh pr create --draft --title "type(scope): brief description" --body-file /tmp/pr-body.md ``` +### What Goes in the Commit, What Goes in the PR Body + +The commit message is the permanent record: a reader of `git log` or `git blame` years later has it and nothing else. It carries what broke or was missing and for whom, the exact error string verbatim when there is one, so that `git log --grep` finds it, why this design and not the obvious alternative, why it is safe where the diff does not show that, and one line on how it was tested, including the failure path when the change adds one. + +The PR body is read once, next to those commits, so it does not repeat them. Its first screen says what is broken or missing, where, and what that costs. After that come one sentence per commit and only what no single commit can carry: results that need the whole series, the environment they came from, decisions the reviewer has to make across commits. Questions to reviewers and open doubts belong in the PR body and never in a commit, where they go stale the day it merges. A fact that fits both goes in the commit. + +Size a commit body against accepted commits touching the same files, not against a fixed line cap, which cuts the answers before the narrative. After shortening any of these texts, check that every must-keep fact survived, that every number still sits next to the version or setup it was measured on, that nothing new was added, and that a claim about a set ("every caller", "never happens") is backed by a grep or rewritten as a mechanism. + ## Downstream Repositories Cozystack is upstream for repositories that are **not** kept in sync with it automatically. A change here can break them silently, because nothing in CI compares the two sides. @@ -276,7 +301,7 @@ Its contributor onboarding, `contributors/README.md`, restates this repository's ### Not a downstream repository -`cozystack-ui` is archived. The console was vendored into `packages/system/dashboard/images/console`, so a UI change belongs in this repo, in the same PR. Note that the console still hardcodes the marketplace category list, so an `ApplicationDefinition` with a brand-new `spec.dashboard.category` renders in the marketplace but gets no sidebar entry. +`cozystack-ui` is archived. The console was vendored into `packages/system/dashboard/images/console`, so a UI change belongs in this repo, in the same PR. `boot-to-talos` converts a running OS to Talos. It pins the Talos image this repo publishes, but Renovate carries that tag for it, so nothing you change here forces a change there. Renaming the image path would, and nothing would catch it. @@ -290,60 +315,17 @@ The release process keeps a **separate** list of repositories, in [`changelog.md - A bug-fix PR should include a behavioural regression test, not just a single field assertion — prove the bug can no longer recur. - Keep the PR description aligned with the template: `## What this PR does` plus the `release-note` block. +- Before posting a claim about a set ("all callers", "the only user", "never happens"), grep for the counterexample, or state the mechanism instead. +- Disagreement carries a mechanism: a code path, a number, a spec clause, a failing test. Time spent and urgency are not arguments. +- Answer the point directly and explain why it is accepted or declined. Read brief feedback literally rather than inferring tone, and avoid unnecessary notifications. Follow the [prose guidance](../../AGENTS.md#working-principles). -## Fetching Unresolved Review Comments +## Collecting Review Feedback -Cozystack uses GitHub review threads with resolution status. Only unresolved threads are actionable — resolved threads are already handled. +Read the feedback from these sources, including existing replies: -The REST endpoint `/pulls/{pr}/reviews` returns review summaries, not individual review comments. Use the GraphQL API to access `reviewThreads` with `isResolved` status: +- Unresolved inline review threads. +- Review submission bodies, even when the review also has inline comments. +- General PR conversation comments. +- Comments posted directly on the PR's commits. -```bash -gh api graphql -F owner=cozystack -F repo=cozystack -F pr= -f query=' -query($owner: String!, $repo: String!, $pr: Int!) { - repository(owner: $owner, name: $repo) { - pullRequest(number: $pr) { - reviewThreads(first: 100) { - nodes { - isResolved - comments(first: 100) { - nodes { - id - path - line - author { login } - bodyText - url - createdAt - } - } - } - } - } - } -}' --jq '.data.repository.pullRequest.reviewThreads.nodes[] | select(.isResolved == false) | .comments.nodes[]' -``` - -Compact one-line variant: - -```bash -gh api graphql -F owner=cozystack -F repo=cozystack -F pr= -f query=' -query($owner: String!, $repo: String!, $pr: Int!) { - repository(owner: $owner, name: $repo) { - pullRequest(number: $pr) { - reviewThreads(first: 100) { - nodes { - isResolved - comments(first: 100) { - nodes { - path - line - author { login } - bodyText - } - } - } - } - } - } -}' --jq '.data.repository.pullRequest.reviewThreads.nodes[] | select(.isResolved == false) | .comments.nodes[] | "\(.path):\(.line // "N/A") - \(.author.login): \(.bodyText[:150])"' -``` +Verify each human or automated finding against the current code before deciding whether it needs a change. Do not post a duplicate answer to a point already addressed. diff --git a/docs/agents/e2e-testing.md b/docs/agents/e2e-testing.md index fcd0719e1..f5c793125 100644 --- a/docs/agents/e2e-testing.md +++ b/docs/agents/e2e-testing.md @@ -2,7 +2,7 @@ Guidance for writing, changing, and reviewing Cozystack's end-to-end (E2E) tests and the CI that runs them. Read this **before** touching anything under `hack/e2e-chainsaw/`, the bootstrap/OpenAPI BATS (`hack/e2e-*.bats`), `hack/*.sh` test helpers, either E2E CI workflow (`.github/workflows/pull-requests.yaml` for same-repo pull requests, `.github/workflows/e2e-fork.yaml` for forks), or `packages/core/testing/`. §10 covers how the two split the work and which invariants hold them together. -The app suite is **Kyverno Chainsaw** (`hack/e2e-chainsaw/`, one directory per app, each with a `chainsaw-test.yaml`). Cluster bootstrap (`hack/e2e-install-cozystack.bats`, `hack/e2e-prepare-cluster.bats`) and the OpenAPI checks (`hack/e2e-test-openapi.bats`) remain BATS. +The app suite is **Kyverno Chainsaw** (`hack/e2e-chainsaw/`, one directory per app, usually with a `chainsaw-test.yaml`; the README there describes the layouts a suite can take, and §7 how they are selected). Cluster bootstrap (`hack/e2e-install-cozystack.bats`, `hack/e2e-prepare-cluster.bats`) and the OpenAPI checks (`hack/e2e-test-openapi.bats`) remain BATS. ## The core principle @@ -10,11 +10,21 @@ The app suite is **Kyverno Chainsaw** (`hack/e2e-chainsaw/`, one directory per a Every convention below follows from that finding: **fail fast, fail loud, make the failure legible.** A test that flakes is a test (or a product) with a real race to fix, not a test to wrap in a retry. Chainsaw's per-assertion polling is the structural expression of this: each `assert` waits on its own condition to its own timeout, and a failure is reported as a structured diff plus auto-captured events/describe/logs — not a generic non-zero exit. +## The Proxmox lane + +`hack/e2e-chainsaw/kubernetes-proxmox/` covers the Proxmox substrate and is the one suite in this tree that the normal lanes cannot run. It needs a Proxmox hypervisor, and the `oracle-vm-*` runners have none, so it ships as `chainsaw-test.yaml.disabled`: neither Chainsaw nor the selector counts a `.disabled` file as a test, and nothing else in the directory or below it is one, which registers it nowhere and makes it unselectable rather than merely unselected. `.github/workflows/e2e-proxmox.yaml` drops the suffix on a self-hosted runner that has one. + +Two properties of that workflow are security boundaries rather than preferences. It is never triggered by `pull_request`, because a self-hosted runner executes what the workflow checks out and this one stages a hypervisor token and a live kubeconfig — a fork PR trigger would hand both to its author. And its concurrency group never cancels in progress, because a killed run leaks VMs on the hypervisor rather than merely losing a result. + +It does not install Cozystack. Every other lane builds a sandbox per run; this one asserts against an existing cluster and an existing hypervisor, which is a weaker guarantee and is stated in the suite header rather than left to be discovered. + +The imperative half lives in `_lib/run-proxmox.sh` and is deliberately not a port of `_lib/run-kubernetes.sh`: that script's diagnostics are virt-launcher Pods, VirtualMachineInstances and guest consoles, none of which exist on an external hypervisor. + ## Conventions ### 1. No retries on deterministic steps; retry only pure infrastructure -- `Run E2E tests` and `Install Cozystack` run **once**. On failure they print `❌ ... (no retry — see diagnostics below)` and dump state. Do not reintroduce a retry loop around them. The E2E step is a single `chainsaw test` invocation — there is no per-app retry loop to bring back, because Chainsaw already polls each assertion to its own timeout. +- `Run E2E tests` and `Install Cozystack` run **once**. On failure they print a `❌ Install failed (no retry …)` or `❌ Chainsaw E2E failed (…)` line and dump state. Do not reintroduce a retry loop around them. The E2E step runs each suite once through `hack/e2e-chainsaw-run.sh` (one `chainsaw test` per suite directory, for the leak guard in §8) — there is no per-app retry loop to bring back, because Chainsaw already polls each assertion to its own timeout. - `Prepare environment` keeps its 3× retry — and *only* it — because it is pure infrastructure (image pull, node container start, network) where a transient runner hiccup is a genuine flake with no application logic involved. The retry tears the compose project down between attempts, because a half-started project the next attempt adopts is not a fresh try. - Rule of thumb: retry is justified only for a step that contains **no product or test logic**. @@ -56,11 +66,11 @@ Trap-based cleanup was the single biggest source of false failures in the BATS s - Chainsaw deletes the resources it `apply`-ed during its cleanup phase (bounded by the `delete`/`cleanup` timeouts in `hack/e2e-chainsaw/.chainsaw.yaml`). Do not hand-roll teardown for resources Chainsaw created. - A self-contained `trap '… ' EXIT` **inside a single `script` step** — to kill a port-forward or remove a temp dir — is fine, because it runs in a contained subprocess with its variables in scope. See `hack/e2e-chainsaw/bucket/chainsaw-test.yaml`. What is banned is test-level trap-based cleanup of the BATS kind. The same carve-out holds inside a BATS `@test` when the trap sits in an explicit subshell — `( … trap "kill $pid" EXIT … )` — because a subshell trap does not replace the one the `bats` binary installs, so a failure inside it still prints its `not ok`. `hack/e2e-test-openapi.bats` relies on this to kill a backgrounded `kubectl proxy`; moving that cleanup to the end of the body would leak a process holding a fixed port rather than fix anything. -- The ban extends to every BATS file under `hack/`, subdirectories and the `e2e-` prefixed ones included, for a second reason worth knowing before you debug one: an `EXIT` trap inside an `@test` body replaces the one the `bats` binary installs for its own bookkeeping, and a test that then **fails** prints no TAP line at all. It does not appear as `not ok`; it disappears, and the run ends with `# bats warning: Executed N instead of expected M tests` and a non-zero exit. Verified with Bats 1.14.0. Anyone reading the tail of the output, or grepping it for `not ok`, sees a green suite — and the CI runner `hack/cozytest.sh`, which is not the `bats` binary, reports the same failure correctly, so the two disagree exactly when it matters. Clean up at the end of the test body instead: both runners set `-e`, so the cleanup is unreachable on failure and the scratch directory is left behind for inspection, which is what you want from a failed test anyway. When a suite reports zero failures, confirm it also reports how many tests it ran: an exit code answers "did anything fail", never "did anything run". `hack/bats-no-exit-trap.bats` enforces this across every `hack/**/*.bats`, subdirectories included: a file that carries no `# EXIT-TRAP DEBT: N` comment must contain no EXIT-trap line at all, and a file that carries one must install exactly N — so a trap appearing or disappearing fails until the file's own number is corrected. Note what that does and does not buy: it is a ratchet on the number's *accuracy*, not on the debt itself, because adding a trap and raising `N` in the same change is green. Nothing mechanical stops the count growing — review does, which is the point of the number living in the file being reviewed. A trap inside an explicit subshell is exempt from the ban but still counted, so a declaration is not by itself an admission of debt; `hack/e2e-test-openapi.bats` is the current example and says so in its own header. The scan reads `.bats` files only, so a handler reaching a test body from a sourced `.sh` is outside it — `hack/e2e-chainsaw/_lib/run-kubernetes.sh` installs two, each benign for its own reason rather than by design: the one in `cozy_capture_tenant_talos` because that function is declared with `(` and runs in a subshell, and the one in `run_kubernetes_test` because no `@test` calls it despite being declared with `{`. Seven `hack/*.bats` source that library. Treat the guard as a ratchet over a common spelling, not as proof that a file installs no handler. A handful of files still declare a debt while their conversion waits on the branches that own them; when one of those reports zero failures, reconcile its `1..N` plan against its `ok` count before believing the run. +- The ban extends to every BATS file under `hack/`, subdirectories and the `e2e-` prefixed ones included, for a second reason worth knowing before you debug one: an `EXIT` trap inside an `@test` body replaces the one the `bats` binary installs for its own bookkeeping, and a test that then **fails** prints no TAP line at all. It does not appear as `not ok`; it disappears, and the run ends with `# bats warning: Executed N instead of expected M tests` and a non-zero exit. Verified with Bats 1.14.0. Anyone reading the tail of the output, or grepping it for `not ok`, sees a green suite. The former unit CI runner `hack/cozytest.sh` reported that failure correctly; the unit lane now runs Bats, which is why test-level handlers had to be removed before the runner switch. Clean up at the last reachable point after an assertion whose failure aborts the test body; the scratch directory then survives for inspection on failure, which is what a failed test wants anyway. A failure in an errexit-exempt `if` or AND-OR context can continue into cleanup and let cleanup supply the test status, so preserve the verdict explicitly in that shape. When a suite reports zero failures, confirm it also reports how many tests it ran: an exit code answers "did anything fail", never "did anything run". `hack/bats-no-exit-trap.bats` enforces this across every `hack/**/*.bats`, subdirectories included: a file that carries no `# EXIT-TRAP DEBT: N` comment must contain no EXIT-trap line at all, and a file that carries one must install exactly N — so a trap appearing or disappearing fails until the file's own number is corrected. Note what that does and does not buy: it is a ratchet on the number's *accuracy*, not on the debt itself, because adding a trap and raising `N` in the same change is green. Nothing mechanical stops the count growing — review does, which is the point of the number living in the file being reviewed. A trap inside an explicit subshell is exempt from the ban but still counted, so a declaration is not by itself an admission of debt; `hack/e2e-test-openapi.bats` and `hack/capk-provider_test.bats` document their exempt subshell traps in their headers. No file declares conversion debt after the test-level handlers are removed; the remaining declarations count those exempt traps. The scan reads `.bats` files only, so a handler reaching a test body from a sourced `.sh` is outside it — `hack/e2e-chainsaw/_lib/run-kubernetes.sh` installs two, each benign for its own reason rather than by design: the one in `cozy_capture_tenant_talos` because that function is declared with `(` and runs in a subshell, and the one in `run_kubernetes_test` because no `@test` calls it despite being declared with `{`. Several `hack/*.bats` files source that library. Treat the guard as a ratchet over a common spelling, not as proof that a file installs no handler. Whenever a suite reports zero failures, reconcile its `1..N` plan against its `ok` count before believing the run. ### 4. Do not mask cleanup or teardown failures -- Resources a test creates that Chainsaw cannot reclaim — because a controller, not the test, owns them (e.g. the Velero `Backup`, `BackupStorageLocation`, and credentials secret in `cozy-velero` in the disabled `hack/e2e-chainsaw/backup/` suite) — must be pruned explicitly. Do not `|| true` over a stuck delete and leave stale state for the next run. +- Resources a test creates that Chainsaw cannot reclaim — because a controller, not the test, owns them (e.g. the Velero `Backup`/`Restore` in `cozy-velero`, which the `vminstance` backup round-trips prune by deleting the cozystack `Backup` and `RestoreJob` CRs, whose finalizers then clean up the Velero objects asynchronously — the `BackupJob` has no finalizer and its `Backup` carries no owner reference, so deleting a `BackupJob` reclaims nothing — plus an explicit delete of the throwaway `BackupStorageLocation`, sequenced after the Velero `Backup` is gone so it does not race the finalizer) — must be pruned explicitly. Do not `|| true` over a stuck delete and leave stale state for the next run. - For nested tenants, tear down **child → parent with a hard wait for deletion between** each. Deleting the parent while a child is still uninstalling wedges the parent's cleanup Job on the child namespace, and both stuck uninstalls occupy helm-controller workers past the end of the test — starving whichever suite runs next. The kubernetes suites encode this ordering in `hack/e2e-chainsaw/_lib/run-kubernetes.sh`. - A test that creates a tenant `Kubernetes` cluster waits for that release to become **Ready** before the assertions it ends on — not before every read of the cluster, which is a different rule and a false one. The chart's post-install hook (`packages/apps/kubernetes/templates/oidc-rbac-job.yaml`) polls for the Kamaji-issued admin kubeconfig in the modes that have one, and that Secret is what the test needs to reach the tenant API, so bringing up a worker or waiting on a child release happens while the parent is still installing. Reading mid-install is fine. What the rule is about is the COMPLETION path: a run that asserts, passes and ends while the parent is still installing turns a green result into a red one in teardown. A failure path that diagnoses and exits mid-install does the same to the install, but that run is already red, so the second red costs noise rather than a wrong verdict — and the script has a number of such exits between the CR and the wait, which the guard does not and should not treat as violations. - A Helm release cannot be uninstalled while its install action is running, and for this kind the action can outlive the fast assertions — by how much depends on the mode, per the bullet below: `release.cozystack.io/helm-install-disable-wait` on the `ApplicationDefinition` drops the wait on the main resources, but the chart's blocking post-install hook still holds the install. A test that asserts and ends therefore hands the remainder of the install to teardown and is reported red on a step that tests nothing. @@ -71,33 +81,37 @@ Trap-based cleanup was the single biggest source of false failures in the BATS s The install test fails if **any** HelmRelease is not Ready. A toothless gate (backgrounded `kubectl wait` discarding child exit codes + a bare `echo` instead of `exit 1`) once shipped a permanently-failing platform HR through green CI for weeks. -- Use a single `kubectl wait hr --all -A`, then an outcome-based re-list (covers HRs created after the snapshot), and `exit 1` on any non-Ready HR. -- Dump the full Ready-condition message per non-Ready HR so the real error is in the test output. See `hack/e2e-install-cozystack.bats`. +Use `cozy_wait_all_helmreleases_ready` from `hack/e2e-wait-helmreleases.sh`, as `hack/e2e-install-cozystack.bats` does, and preserve its failure status and diagnostics. -### 6. Assert the parent HelmRelease did not remediate — via `status.history` +### 6. Assert no HelmRelease failed an action it retries in place — via `status.history` -A parent HelmRelease that hit its wait timeout, uninstalled, and reinstalled is a silent race we want to catch. **Do not** check `.status.installFailures` / `.status.upgradeFailures`: Flux's `ClearFailures()` zeroes those on every successful reconcile, so checking them after the HR is Ready is **vacuous** and passes against a reverted fix. +A HelmRelease that hit its wait timeout and failed an action is a silent race we want to catch, and it stays one when a later retry recovers the release. **Do not** check `.status.installFailures` / `.status.upgradeFailures`: Flux's `ClearFailures()` zeroes those on every successful reconcile, so checking them after the HR is Ready is **vacuous** and passes against a reverted fix. -- Inspect `.status.history` instead — a `failed` or `uninstalled` Snapshot survives a later successful reconcile. Use the shared helper in `hack/e2e-chainsaw/_lib/remediation-guard.sh` (`helmrelease_has_remediation_cycle`) from a `script` step. Take the jsonpath from `HELMRELEASE_HISTORY_JSONPATH` in that same file rather than writing it out: `internal/fluxcontract` sources that file and runs the resulting value against the upstream Flux type, and a literal copied elsewhere is not covered by it. +- Inspect `.status.history` instead — a `failed` or `uninstalled` Snapshot survives a later successful reconcile, which is what makes it readable at all after the release is Ready. It does not survive an unbounded number of them: the controller truncates history on every in-sync reconcile and again before it retries or remediates a failed release, retaining the newest five Snapshots on a release whose strategy is a retry and, on any other, those down to the previous `deployed` or `superseded` Snapshot — falling back to the same newest-five cap when there is no such Snapshot to cut at. An e2e run takes only a handful of actions on each release, so the footprint is still present when the guard reads it — but a guard placed after further release actions, or one asserting on history days later, is reading a window and needs to say so. Use the shared helper in `hack/e2e-chainsaw/_lib/remediation-guard.sh` (`helmrelease_has_remediation_cycle`) from a `script` step. Take the jsonpath from `HELMRELEASE_HISTORY_JSONPATH` in that same file rather than writing it out: `internal/fluxcontract` sources that file and runs the resulting value against the upstream Flux type, and a literal copied elsewhere is not covered by it. +- **Fail on any footprint of a release that retries in place; report it on the others.** Under `RetryOnFailure` helm-controller never remediates: a failed action is retried as an upgrade with its manifests left in place, so the release never writes an `uninstalled` Snapshot of its own, and the `failed` one is the only record of the attempt. `cozy_guard_helmrelease` therefore fails the run on either status on a release whose `.spec.install.strategy.name` is `RetryOnFailure`: the parent, which the aggregated apiserver stamps that way like every Application HelmRelease (`pkg/registry/apps/application/rest.go`), and the tenant `cilium` and `csi`, whose templates set it. A retry that recovered still fails the run, by design, while the Snapshot still reads `failed`: the failed attempt happened, and on these releases nothing else records it. It does not after a failed install that the very next attempt recovers. With no deployed release to upgrade from, Helm upgrades from the failed one and marks it `superseded` on success, helm-controller rewrites that Snapshot in place, and the history reads `deployed`, `superseded` like any ordinary upgrade, so the guard passes. A failed upgrade keeps its `failed` Snapshot, since Helm supersedes the last deployed release instead, and so does an install that fails twice before recovering. That makes a late node join a red run here even when it lands inside the 29m node-join deadline: the tenant `cilium` install cannot complete before a worker registers, because its operator Deployment has nowhere to schedule, so workers arriving more than two of its 10m install timeouts after the install started leave a `failed` Snapshot, and the guard fails the run on it. This is accepted rather than carved out, since the chart itself treats an install outrunning its budget for want of a node as a problem, but the cause is the join and not the CNI. The guard's message says so and points at the Snapshot times in the describe output it prints. The other addon releases pair the default strategy with `retries: -1`, a configuration that declares repeated remediation their recovery path. Nothing in the suite measures how often they take it, and failing a whole bringup on a release doing what it is configured to do is how a guard ends up switched off, so the same footprint there is printed as a note and the run stays green. For the CRD addons that configuration is itself a defect, tracked in cozystack/cozystack#3555; tighten when a measured baseline or a strategy change makes the condition knowable. +- **The strategy is read through a jsonpath, so something has to notice when it stops resolving.** `kubectl -o jsonpath` prints nothing and exits 0 for a path that no longer matches, and empty takes the lenient branch — a rename of `spec.install.strategy` in a future helm-controller would report every footprint on the parent, `cilium` and `csi` as a note, on a green run, with the unit tests still passing because they feed the value from a fixture rather than through the jsonpath. An empty value is not by itself evidence of that, since most addons legitimately set no strategy, so the check lives on the one release whose strategy the cluster is known to set: the parent, where an empty value, or any value other than `RetryOnFailure`, fails the run. That is enough, because the same rename empties the field on every release at once. +- **"Covers the tenant addon HelmReleases" means reads and classifies, not can fail the run on.** Five conditions red a run: a `failed` or `uninstalled` Snapshot on a release that retries in place; a Ready HelmRelease reporting no history at all, which is a status shape the helper can no longer read; a read that failed, which is never folded into "no history"; an empty or non-`RetryOnFailure` `.spec.install.strategy.name` on the parent; and an addon prefix that selects no HelmRelease at all, which the passing path fails on rather than passing silently over nothing. Every other addon footprint is a note. Which releases a run has at all depends on what it enabled, since most addon templates are gated on their own `addons..enabled`, so the breadth of the reading and the breadth of the gate are not the same number. +- **The guard runs after the assertions, so the failure paths need the reading without the verdict.** Every deadline a failed child action surfaces as — a node that never turns Ready, a HelmRelease wait that expires, a PVC that never binds — ends the script under errexit well before the guard, so on exactly the runs such an action explains, the guard never executes and the history is named nowhere. `cozy_report_helmrelease_remediation` is the same classification with no verdict, called from the node-join collector and from the exit handler that covers every other failure. Arm that handler where the object it reads starts existing, not where the tenant becomes reachable: the parent HelmRelease is rendered from the CR at the apply, and everything between there and the tenant LB is a management-cluster wait on that release or on what it installs, so a handler armed after those waits misses the window in which an install action times out. It fails nothing: the run is already red, and the tenant crust-gather snapshot hangs off the caller's own exit status. It walks the releases under both the caller's diagnostics phase budget and one of its own, and names whatever it stopped short of. Both budgets decide whether the next read may *start*, not when the walk ends, so neither is a worst case: the ceiling is the budget plus the reads already committed to when it expires. Write it that way in any collector you add — a budget described as a total is a number a later reader will trust for sizing the step around it. +- **Do not infer a child release's state from the parent's.** The Kubernetes `ApplicationDefinition` sets `release.cozystack.io/helm-install-disable-wait`, which the apiserver turns into `DisableWait` on both actions, so the parent reaches Ready without waiting for the manifests it applied, the child HelmReleases included (Helm still waits on its post-install hook Job) — and the suite waits on some addons by name while never naming others. An empty `.status.history` is therefore judged against that release's own Ready condition: Ready with no history is a status shape the helper can no longer read and fails the run, not-Ready with no history is a release that never completed an action and is reported as not inspected. Read readiness before the history, not after, or a release that finishes installing between the two reads presents as Ready with an empty history and fails the run for a shape it never had. That ordering closes the truncation half of the window and not all of it: `HelmReleaseStatus.ClearHistory()` empties history outright, and the controller that calls it is not a module this tree carries. ### 7. Test-Impact Analysis (TIA), default-on -`hack/select-e2e.sh` walks the `packages/core/platform/sources/*.yaml` dependency graph and runs only the Chainsaw suites affected by a diff. A suite is a directory under `hack/e2e-chainsaw/` containing a `chainsaw-test.yaml`. +`hack/select-e2e.sh` walks the `packages/core/platform/sources/*.yaml` dependency graph and runs only the Chainsaw suites affected by a diff. A suite is a directory directly under `hack/e2e-chainsaw/` in or below which Chainsaw would find a Test: a `chainsaw-test.yaml`, or a `chainsaw-test.yml`, which Chainsaw loads when the `.yaml` is absent, or, with neither, numbered step files such as `01-install.yaml`, which Chainsaw turns into a Test on its own. Chainsaw walks every subdirectory of the directory it is handed, so a Test in a top-level directory or anywhere below it makes that directory a suite. Every one of those layouts runs, so the selector has to see it or it is never selected. -- Conservative escalation: edits to `packages/library/`, `packages/core/`, the Go trees (`api/`, `cmd/`, `internal/`, `pkg/`), the codegen under `tools/`, `go.mod`/`go.sum`, top-level `hack/*.sh` helpers, the `hack/e2e-*.bats` the sandbox runs and the `hack/lib/` they source, `hack/*.mk`, `hack/buildkitd.toml`, `hack/e2e-*.yaml`, the shared `hack/e2e-chainsaw/_lib/`, the chainsaw config `hack/e2e-chainsaw/.chainsaw.yaml`, the `Makefile`, or any workflow that runs the suite escalate to the **full suite**. Only `pull-requests.yaml` is executed from the pull request's own head, so escalating on the other three buys generic regression coverage rather than coverage of the edit; the trade and its measured cost are written next to `full_suite_pattern` rather than repeated here. A per-suite edit (any file under `hack/e2e-chainsaw//`) selects **only** that suite, with one exception: a `*.disabled` file selects nothing, because a parked suite is executed by nothing and editing it cannot regress a test. `hack/e2e-apps/.bats` — the pre-Chainsaw per-app BATS suites — maps the same way, off the basename instead of the directory. The files formerly kept there were wired to nothing after migration, and the path remains deliberately mapped rather than marked inert: inert would bake the orphan status into the rule and go quietly wrong the day a lane runs those files again. The basename is membership-tested against the suite list on the spot, and a name no suite carries escalates there and then, naming the file. Deferring that to the final intersection instead would leave the verdict to the rest of the diff — alone the selection empties and the backstop escalates, but beside any path that contributed a suite the escalation disappears and the run narrows to that suite in silence, which is the merge-before-escalate shape #3330 removed from the graph walk. Anything else under `hack/e2e-apps/` — a nested path, a non-`.bats` file — is shared material for those suites the way `hack/e2e-chainsaw/_lib/` is for the Chainsaw ones, and escalates for the same reason. -- **Every path is classified, and an unclassified one escalates.** The selector has three selection outcomes — full suite, a scoped set, or nothing — and each is reached by an explicit rule; the fourth outcome in the bullet below is not a selection but a refusal to produce one. Several rules produce the empty one, which is worth knowing before reading an empty selection as "the inert list matched": documentation, dashboards and `*.md` are dropped first wherever they live, a `*.disabled` Chainsaw suite and a `examples/backups//` edit whose app has no suite are dropped where chainsaw and backup-example paths are matched, and `inert_config_pattern` covers repo meta, agent config, `hack/testdata/`, the helm-unittest fixture charts under `packages/tests/`, the three `.gitattributes` that hold nothing but `linguist-generated` markers, which reach no build, chart or test (enumerated rather than matched by filename, because the justification is what those files contain and the name does not carry it — `.gitattributes` can also set `filter`, `eol`, `working-tree-encoding` and `export-subst`, each of which changes what lands in the working tree and therefore what gets built, so a by-name rule would make such a file inert in silence) and the top-level `hack/*.bats` that are not `hack/e2e-*.bats`. That last one is the unit lane, and the root `Makefile` is the authority on the split: `BATS_UNIT_FILES := $(filter-out hack/e2e-%.bats,$(wildcard hack/*.bats))` keeps every non-E2E file for `make unit-tests`, while `packages/core/testing` runs the E2E-prefixed files, so the sandbox never executes a unit file and no Chainsaw suite can regress from an edit to one. Being inert here does not leave them untested: the `unit-tests` job is gated on the `plan` job's `code` output, which `pull-requests.yaml` computes as "any changed path outside `docs/`" and never from `select-e2e.sh`, so a bats-only pull request still runs the whole unit lane — plus install and the OpenAPI tests, since the `e2e` job also reads `code` rather than the selection. `full_suite_pattern` covers shared build inputs and the e2e harness, and the graph lookup handles `packages/(apps|system|extra)/`. A path matching none of them escalates to the full suite and logs why, because both lanes read an empty selection as "skip Chainsaw" and then post `E2E Tests` green — so a silent default is a green gate with nothing tested (#3392). When that escalation fires for something genuinely inert, add it to `inert_config_pattern`; do not relax the fall-through. The escalation list and the inert list are checked in that order, so a specific escalation beats a broad inert directory. -- **Coverage is decided per changed path.** A path that resolves through the graph but reaches no runnable suite is covered by nothing, so it forces the full run on its own account, whatever the rest of the diff selected. Reading that off the merged selection instead let any other changed path contributing a suite name swallow the escalation, with nothing in the output to record that it happened: change a platform component, adjust the Chainsaw test beside it, and the component's escalation disappeared behind that one suite (#3330). The unit is the path rather than the source, because one path can belong to several PackageSources — `system/postgres-operator` belongs to two, one of which reaches no suite — and deciding per source would escalate on that half and run everything for every change to it. +- Conservative escalation: edits to `packages/library/`, `packages/core/`, the Go trees (`api/`, `cmd/`, `internal/`, `pkg/`), the codegen under `tools/`, `go.mod`/`go.sum`, top-level `hack/*.sh` helpers, the `hack/e2e-*.bats` the sandbox runs and the `hack/lib/` they source, `hack/*.mk`, `hack/buildkitd.toml`, `hack/e2e-*.yaml`, the shared `hack/e2e-chainsaw/_lib/`, `examples/backups/_lib/` (the place for helpers shared by the backup walkthroughs) and any file directly in `examples/backups/`, the chainsaw config `hack/e2e-chainsaw/.chainsaw.yaml`, the `Makefile`, or any workflow that runs the suite escalate to the **full suite**. Only `pull-requests.yaml` is executed from the pull request's own head, so escalating on the other three buys generic regression coverage rather than coverage of the edit; the trade and its measured cost are written next to `full_suite_pattern` rather than repeated here. A per-suite edit (any file under `hack/e2e-chainsaw//`) selects **only** that suite, with one exception: a `*.disabled` file selects nothing, because a parked suite is executed by nothing and editing it cannot regress a test. The directory name is membership-tested against the suite list on the spot, so a directory holding no suite — shared material beside `_lib/` — escalates there and then, naming the file. `hack/e2e-apps/.bats` — the pre-Chainsaw per-app BATS suites — maps the same way, off the basename instead of the directory. The files formerly kept there were wired to nothing after migration, and the path remains deliberately mapped rather than marked inert: inert would bake the orphan status into the rule and go quietly wrong the day a lane runs those files again. The basename is membership-tested the same way. Deferring either test to the final intersection instead would leave the verdict to the rest of the diff — alone the selection empties and the backstop escalates, but beside any path that contributed a suite the escalation disappears and the run narrows to that suite in silence, which is the merge-before-escalate shape #3330 removed from the graph walk. Anything else under `hack/e2e-apps/` — a nested path, a non-`.bats` file — is shared material for those suites the way `hack/e2e-chainsaw/_lib/` is for the Chainsaw ones, and escalates for the same reason. +- **Every path is classified, and an unclassified one escalates.** The selector has three selection outcomes — full suite, a scoped set, or nothing — and each is reached by an explicit rule; the fourth outcome in the bullet below is not a selection but a refusal to produce one. Several rules produce the empty one, which is worth knowing before reading an empty selection as "the inert list matched": documentation, dashboards and `*.md` are dropped first wherever they live, a `*.disabled` Chainsaw suite and a `examples/backups//` edit whose app has no suite are dropped where chainsaw and backup-example paths are matched, and `inert_config_pattern` covers repo meta, agent config, `hack/testdata/`, the helm-unittest fixture charts under `packages/tests/`, the three `.gitattributes` that hold nothing but `linguist-generated` markers, which reach no build, chart or test (enumerated rather than matched by filename, because the justification is what those files contain and the name does not carry it — `.gitattributes` can also set `filter`, `eol`, `working-tree-encoding` and `export-subst`, each of which changes what lands in the working tree and therefore what gets built, so a by-name rule would make such a file inert in silence), the top-level `hack/*.bats` that are not `hack/e2e-*.bats`, and their shared `hack/test_helper.bash`. These are the unit lane, and the root `Makefile` is the authority on the split: `BATS_UNIT_FILES := $(filter-out hack/e2e-%.bats,$(wildcard hack/*.bats))` keeps every non-E2E file for `make unit-tests`, while `packages/core/testing` runs the E2E-prefixed files, so the sandbox never executes a unit file and no Chainsaw suite can regress from an edit to one. Being inert here does not leave them untested: the `checks` job runs Bats for both code and docs-only changes. Its code path also runs the remaining unit and controller tests. A bats-only pull request still runs install and the OpenAPI tests, since the `e2e` job reads `code` rather than the selection. `full_suite_pattern` covers shared build inputs and the e2e harness, and the graph lookup handles `packages/(apps|system|extra)/`. A path matching none of them escalates to the full suite and logs why, because both lanes read an empty selection as "skip Chainsaw" and then post `E2E Tests` green — so a silent default is a green gate with nothing tested (#3392). When that escalation fires for something genuinely inert, add it to `inert_config_pattern`; do not relax the fall-through. The escalation list and the inert list are checked in that order, so a specific escalation beats a broad inert directory. +- **Coverage is decided per changed path.** A path that resolves through the graph but reaches no runnable suite is covered by nothing, so it forces the full run on its own account, whatever the rest of the diff selected. Reading that off the merged selection instead let any other changed path contributing a suite name swallow the escalation, with nothing in the output to record that it happened: change a platform component, adjust the Chainsaw test beside it, and the component's escalation disappeared behind that one suite (#3330). The unit is the path rather than the source, because one path can belong to several PackageSources, not all of which need reach a suite, and deciding per source would escalate on one that reaches none and run everything for every change to the path. - **Two sources are excluded from the reverse-dependency walk as install-ordering hubs.** Every `*-application` source depends on `cozystack.cozystack-engine` so its `*-rd` HelmRelease waits for the ApplicationDefinition CRD, and the sources that depend on `cozystack.cozystack-basics` do so to get a namespace or a platform-wide policy in place first. Neither edge says the dependent's behaviour changes when the hub does, so carrying selection across them goes wrong in both directions: through the engine a `cert-manager` change fans out to every app in the tree, and through basics the platform's namespace-and-policy package narrows to whichever single suite happens to land downstream of it — 22 suites down to one on #3426, where the new site-router suite sits under `kubevirt-cdi`, which depends on basics. Dropping the reverse edges leaves both hubs reachable and stops them propagating; a change to either still runs everything, because its own group then reaches no suite and the per-path escalation fires on it. Adding a third one is a real decision, not bookkeeping: it says every existing edge into that source is ordering rather than behaviour, so read them before extending the list. -- **There is a fourth outcome, and it is a failed step rather than a selection.** It fires when the suite list itself is unavailable: `find` cannot list `hack/e2e-chainsaw/`, or that directory holds no `chainsaw-test.yaml`. There is no fallback left to take, because escalating would print an empty list and both lanes read an empty selection as "skip Chainsaw" before posting `E2E Tests` green — the outcome meaning "run everything" would deliver a run of nothing. So the selector names what broke on stderr and exits non-zero; both lanes run the step under `bash -e`, so the job fails and the required check goes red. A red `Select E2E tests` step is a real signal, not a flake: read its stderr line before rerunning. A `yq` failure is deliberately not in this class — what is missing there is the dependency graph, not the suite list, so the selector still has a safe answer and escalates to the full suite. That is conservative but quiet: the only sign is one stderr line inside a step that passes, so a selector running blind on every PR looks exactly like a project that escalates a lot. -- **Every escalation names its cause on stderr.** "Run everything" is the same list of suite names whichever rule produced it, so a reason line is the only thing that distinguishes the branches that can reach it, and without one the answer to "why did this pull request run the whole suite" has to be re-derived by hand from the diff. Four of them used to be silent — the shared `hack/e2e-chainsaw/_lib/` and `.chainsaw.yaml` case, the `full_suite_pattern` match, a `packages/` path no PackageSource claims, and the empty-selection backstop — and `full_suite_pattern` is the commonest cause of a full run by a wide margin, so the usual answer was the one the log never carried. Each line names the path or the sources that caused it, and a unit test asserts each message, because a reason that regresses to silence changes no selection and is invisible to every other test. The lines go to **stderr** and must stay there: stdout is the suite list and both lanes parse it, so a reason line on stdout would be read as a suite name. +- **There is a fourth outcome, and it is a failed step rather than a selection.** It fires when the suite list itself is unavailable: `find` cannot list `hack/e2e-chainsaw/`, or that directory holds no suite in any of the layouts above. There is no fallback left to take, because escalating would print an empty list and both lanes read an empty selection as "skip Chainsaw" before posting `E2E Tests` green — the outcome meaning "run everything" would deliver a run of nothing. So the selector names what broke on stderr and exits non-zero; both lanes run the step under `bash -e`, so the job fails and the required check goes red. A red `Select E2E tests` step is a real signal, not a flake: read its stderr line before rerunning. A `yq` failure is deliberately not in this class — what is missing there is the dependency graph, not the suite list, so the selector still has a safe answer and escalates to the full suite. That is conservative but quiet: the only sign is one stderr line inside a step that passes, so a selector running blind on every PR looks exactly like a project that escalates a lot. +- **Every escalation names its cause on stderr.** "Run everything" is the same list of suite names whichever rule produced it, so a reason line is the only thing that distinguishes the branches that can reach it, and without one the answer to "why did this pull request run the whole suite" has to be re-derived by hand from the diff. Four of them used to be silent — the shared `hack/e2e-chainsaw/_lib/` and `.chainsaw.yaml` case, the `full_suite_pattern` match, a `packages/` path no PackageSource claims, and the empty-selection backstop — and `full_suite_pattern` is the commonest cause of a full run by a wide margin, so the usual answer was the one the log never carried. Each line names the path or the sources that caused it, and a unit test asserts each message, because a reason that regresses to silence changes no selection and is invisible to every other test. The backstop is the exception: every rule that selects a suite by name membership-tests it where the path is classified, so nothing reaches the backstop and no test asserts its line; it stays as the guard for a future rule that forgets to. The lines go to **stderr** and must stay there: stdout is the suite list and both lanes parse it, so a reason line on stdout would be read as a suite name. - **The one path the fall-through cannot catch is a new e2e workflow.** `inert_config_pattern` makes `.github/` inert as a directory, and the workflows that run the suite are exempted from it by name in `full_suite_pattern`. A workflow added under `.github/workflows/` therefore reads as inert until someone adds it to that enumeration, and the fall-through never sees it. That is why the list carries a `rg -l test-chainsaw .github/workflows/` reminder: the enumeration is the guard, not a convenience. - The `full-e2e` PR label forces the whole suite. -- The selection is passed to `make test-chainsaw CHAINSAW_SUITES=""`, which runs `chainsaw test ` from `hack/e2e-chainsaw/` (empty = the whole suite). +- The selection is passed to `make test-chainsaw CHAINSAW_SUITES=""`, which runs `hack/e2e-chainsaw-run.sh ` from `hack/e2e-chainsaw/` (empty = every directory there). The runner hands chainsaw one suite at a time and runs the tests a single `chainsaw test ` would discover, no more and no fewer. - The coverage gap TIA opens on PRs is closed at release-cut time: the "Prepare release" commit bakes image digests into `packages/core/` (and other packages), which TIA escalates to the **full** suite — so the release PR exercises the whole suite against the commit the tag will point at. When adding a new app package, confirm `select-e2e.sh` maps it correctly (it has a unit test, `hack/select-e2e_test.bats`). A new app whose suite directory does not yet exist will not be selected — add `hack/e2e-chainsaw//chainsaw-test.yaml` first. -`src_to_suites()` maps a PackageSource name to the suites it owns and is the inverse of `select-install.sh`'s `suite_to_source()`. A test walks every suite through both tables, so a source whose name fits neither convention — not `-application`, not the suite name itself — fails there rather than quietly making its own suite unreachable, which turns every change to that package into a full run (#3665). +`src_to_suites()` maps a PackageSource name to the suites it owns and is the inverse of `select-install.sh`'s `suite_to_source()`. A suite can have several owners: the Kubernetes suites create both Kubernetes and KubernetesNodes resources, and the VM suite creates both VMInstance and VMDisk. A test walks every owner through both tables, so a source whose name fits neither convention — not `-application`, not the suite name itself — fails there rather than quietly making its own suite unreachable, which turns every change to that package into a full run (#3665). Packages needed only by a suite, such as its backup APIs, belong to `suite_runtime_sources()` in the install selector; they do not change reverse ownership. #### What TIA does and does not do @@ -106,21 +120,22 @@ Be precise about TIA's scope — it is narrower than "skip E2E for unrelated PRs - **It trims only which suites `chainsaw test` runs, not the expensive stages.** `Prepare environment` and `Install Cozystack` (the full platform install) run regardless of the selection. TIA only decides the `CHAINSAW_SUITES` passed to the final E2E step. A perfect narrow saves the suite tail, not the bulk of wall-time. (Package image builds are scoped separately by `hack/build-matrix.sh`; the Talos leg runs when its direct or shared inputs changed and remains unconditional for forks, while installer/finalize runs for every non-docs PR. That is a distinct mechanism from TIA's suite trimming.) - **`Select E2E tests` runs *after* `Install Cozystack` and has no `always()`.** GitHub implicitly ANDs a step's `if:` with `success()`, so if install fails the selector (and `Run E2E tests`) are skipped entirely. On a red install you will not see TIA narrow anything — that is the ordering, not a selector bug. - **Most PRs legitimately escalate to the full suite.** Platform manifests live under `packages/core/`, Go under `api/`/`internal/`, helpers under `hack/`, plus the `Makefile` — touching any one triggers the full suite. So "all suites selected" is usually correct, not a failure to narrow. -- **Two skip layers, with a gap.** The `plan` job computes a coarse docs-only gate (`code`, true for any change outside `docs/**`) that skips the whole build+E2E pipeline for docs-only PRs, plus a per-package build matrix (`hack/build-matrix.sh`) that scopes which images build. TIA's finer skip (`select-e2e.sh` ignoring `docs/`, `dashboards/`, `*.md` and the rest of `inert_config_pattern`) only trims the suite selection. A PR touching only `dashboards/*.json` therefore still runs install, then skips just the Chainsaw suites — near-zero savings. If you need such PRs to skip the pipeline, widen the `plan` docs-gate, not `select-e2e.sh`. +- **Two skip layers, with a gap.** The `plan` job computes a coarse gate (`code`, false only when every changed path is under `docs/` or one of the CI-only Go tools no image builds, `cmd/backport-batch/` and `cmd/api-gate/`) that skips the whole build+E2E pipeline for such PRs, and `e2e-fork.yaml` skips on the same prefixes (`hack/gate-concurrency-contract.bats` holds the two lists equal), plus a per-package build matrix (`hack/build-matrix.sh`) that scopes which images build. TIA's finer skip (`select-e2e.sh` ignoring `docs/`, `dashboards/`, `*.md` and the rest of `inert_config_pattern`) only trims the suite selection. A PR touching only `dashboards/*.json` therefore still runs install, then skips just the Chainsaw suites — near-zero savings. If you need such PRs to skip the pipeline, widen the `plan` docs-gate, not `select-e2e.sh`. ### 8. Failure must be self-explanatory — diagnostics are first-class - On install failure, the CI step dumps `kubectl get hr -A -o wide`, a `describe` of each non-Ready HR, and sorted events, all under collapsible `::group::` blocks. -- On E2E failure, the CI step dumps `kubectl get hr -A`, sorted events, and COSI bucket/claim/access readiness columns (those CRDs ship no printer columns, so plain `get` shows only NAME/AGE). The `chainsaw test` run is one step, so this dump is at run level; Chainsaw's own per-`Test` `catch` blocks add scoped events/describe/podLogs for the failing suite. +- On E2E failure, the CI step dumps `kubectl get hr -A`, sorted events, and COSI bucket/claim/access readiness columns (those CRDs ship no printer columns, so plain `get` shows only NAME/AGE). The whole suite run is one CI step, so this dump is at run level; Chainsaw's own per-`Test` `catch` blocks add scoped events/describe/podLogs for the failing suite. +- **A suite whose pods outlive it fails where it leaked, not where the memory ran out.** A suite can pass and still leave its workloads running — brokers of Kafka releases whose application was deleted, a TenantControlPlane stuck on its finalizer — and the first thing to notice used to be a later suite failing on `Insufficient memory`, hours on and under the wrong name. Chainsaw v0.2.15 has no hook that runs after a test's cleanup (its Configuration carries `error.catch`, which runs only on failure), so `hack/e2e-chainsaw-run.sh` runs one `chainsaw test` per suite directory and checks between them, with `hack/e2e-chainsaw/_lib/leak-guard.sh`. A pod is charged to the suite when it is not terminal, did not exist before the suite, and the root of its ownerReferences chain was created at or after the suite started on the apiserver's clock; a platform pod replaced mid-suite still traces back to an object the install created, so it is not charged. Charged pods get the default `timeouts.cleanup` of `.chainsaw.yaml` (5m), counted from when `chainsaw test` returns and so after any per-suite cleanup override has been spent, to disappear; past that the run prints `LEAKED-PODS suite=` with one line per pod and its root, raises a `leaked-pods` error annotation, and adds a failed `leak-guard` case to `chainsaw-report.xml`. Every suite that leaves nothing behind logs how long it took to clear, and leftovers of a suite that already failed are reported once as a warning, without the wait. The wait has three outcomes, and nothing is retried. A timeout or a spent budget gives the verdict from the last good pod list, including when the re-list after it fails: a leak fails the suite. Any other error on a wait or a re-list, before the budget is spent and before any timeout, stops the waiting and is reported as `LEAKED-PODS suite= count=N inconclusive=""`, a warning rather than a failure, so an apiserver blip while waiting cannot turn into a leak red. A wait that fails only after running for its whole timeout counts as a timeout whatever kubectl printed, since kubectl reports a deadline that passes before its watch starts as the client's `context deadline exceeded`. An apiserver blip before a suite starts is different: if the reading taken ahead of the suite fails, that suite is not run and is reported as not run, which fails the run. A failed first reading after a suite leaves the suite unchecked, and it fails with a `leak-guard` annotation and a report case saying the cluster could not be read, not that it leaked. A suite with a known, filed leak is listed in `hack/e2e-chainsaw/_lib/leak-allowlist.txt` as ` `; its leak prints as a warning and does not fail. The exemption covers the whole suite, so the PR that fixes the issue deletes the line, and an entry naming a directory that is not a suite stops the run before the first suite. - Inside a suite, attach scoped diagnostics with a top-level `catch:` block (`events`, `describe`, `podLogs`, `get`) rather than letting a bare assert failure through — see `hack/e2e-chainsaw/bucket/chainsaw-test.yaml` and `hack/e2e-chainsaw/harbor/chainsaw-test.yaml`. This replaces the BATS `... || { echo …; kubectl get/describe …; false; }` idiom. -- `make collect-report` → `hack/cozyreport.sh` uploads a full `cozyreport.tgz` (operator/Flux/cert-manager logs, LINSTOR, Kamaji, Talos dmesg, COSI YAML) on every run, and the Chainsaw JUnit report (`chainsaw-report.xml`) is uploaded as its own artifact. +- `make collect-report` → `hack/cozyreport.sh` uploads a full `cozyreport.tgz` (operator/Flux/cert-manager logs, LINSTOR resources and volumes, per-node ZFS datasets in exact bytes, Kamaji, Talos dmesg, COSI YAML) on every run, and the Chainsaw JUnit report (`chainsaw-report.xml`) is uploaded as its own artifact. - **Which machine a run landed on is recorded before the sandbox container exists**, in `sandbox-host/runner-identity.txt`: the OCI shape, both region keys, the availability and fault domain, the numbers of the `shapeConfig` sizing object, and the runner VM's own kernel release, online CPU count and processor model. A lane asks for a runner class rather than for a machine — a flex shape is filled from whatever capacity the pool has, and the region is a preference with a fallback — so without this a red run and a green one cannot be compared by the hardware they ran on, which is the first question a flake that only some runs have will raise. `hack/e2e-runner-identity.sh` takes the read on the runner VM, from `packages/core/testing/Makefile`'s `apply` target, because the metadata service answers on a link-local address the sandbox container has no guaranteed route to, and an "unreachable" answered from in there would look exactly like a capture that had tried. Every e2e lane reaches the sandbox through `make prepare-env`, so the record is taken once per run in each of them, on the passing path as well as the failing one. It goes to the job log as well as to the file, and the log copy is not a convenience: a run whose sandbox never came up has no `cozyreport.tgz` at all, so on that one path the log is the only place the record exists. - **The keys are fetched one at a time and the root instance document never is.** That document carries the instance and compartment OCIDs, the image OCID, the display name, the hostname and the user-supplied metadata bag, and the report is a public artifact — so asking per key makes the privacy property something the wire settles rather than something a filter has to be trusted for. It also removes a guess: Oracle documents the shape sizing under its own `shapeConfig` subpath and the root document does not carry that object at all, so a reader hunting it inside the root document would have reported the size of every machine as unknown and blamed the service for it. From the sizing object only the numbers are kept, and only under keys shaped like field names, which makes the rule hold for keys nobody has seen yet: a size is a number, an identifier is a string, and a key is printed into the record exactly as a value is. That object is also refused whole unless it arrives as one complete JSON object, so a truncated answer or a top-level array cannot be read in part and published as a sizing record. A per-key answer that is not one scalar is named as such rather than printed, since a service answering a whole document to a key request is the one way the design could still publish what it never asked for. The first key doubles as the probe and is held to answering like this service does, so a machine that is not an OCI instance costs one ceiling rather than one per key whether the address is silent or something else is answering on it, and either way the run leaves an `imds unreachable` line to grep for. Every read is taken through a wall-clock ceiling, because a diagnostic that hangs costs the step its whole budget without ever reaching an exit status; where `timeout` is not on PATH the local reads run unbounded instead of not at all and the record says so in a `[bounds]` line, the same trade `hack/cozyreport.sh` makes for its own reads. None of it is fatal, since this runs inside the one retried step in the job — a runner that is not an OCI instance leaves an `imds unreachable` line and an exit status of 0. The report writes that filename either way, holding the record or the reason there is none, because an unidentified runner and an unremarkable one would otherwise leave the same absence. - **The report's per-pod evidence, under `kubernetes/pods/` in `cozyreport.tgz`, is selected by the READY column rather than by STATUS** — so a pod left at `0/1 Running` by a readiness probe that never passes is in scope, where before it was not. In scope is not the same as collected: the walk stops at `COZY_REPORT_PODS_MAX` pods or `COZY_REPORT_PODS_BUDGET` seconds, and what it did not reach is named in the artifact rather than dropped in silence, as the next point describes. Selecting on the STATUS column alone drops exactly that pod, and it is a common way for a suite to time out: the replica never joins, its HelmRelease sits in `InProgress`, and the artifact carries no trace of the pod the run died on. Terminal `Succeeded`/`Completed` pods stay excluded, since they legitimately end unready. Widening the selection and capping the walk are only safe together if the widening cannot displace what the uncapped walk always kept, so the collection order splits by evidence class before namespace: every pod that is not `Running` — a crash loop, `Pending`, `Error`, the class the collector took before this — is ordered ahead of every pod that is `Running` but unready, and `COZY_REPORT_PREFER_NS` orders within each of those two classes rather than across the whole selection. Otherwise a failed install with more not-Ready pods than the cap spends it on newly-in-scope tenant pods and drops the container logs of the platform pod that is actually crashing. -- **Every bound that the report's pod collection hits is named in the artifact, not only in the job log.** The pod walk stops at `COZY_REPORT_PODS_MAX` pods or `COZY_REPORT_PODS_BUDGET` seconds and leaves `COLLECTION-TRUNCATED.txt` naming whichever fired; a pod it cut off part way through leaves `CONTAINER-LOGS-TRUNCATED.txt`; a pod list that never came back leaves `COLLECTION-FAILED.txt` rather than the empty tree a healthy cluster produces; a missing local `timeout` leaves `COLLECTION-UNBOUNDED.txt`, because the reads still run, just without a ceiling, and a missing dependency on the machine writing the report is not a statement about the cluster; a kind this cluster does not serve at all — `kubectl get vm -A` on an install without KubeVirt, which exits non-zero — leaves `KIND-NOT-SERVED.txt` rather than a failure marker, since that is the cluster answering correctly and a marker that fires on healthy installs is one a reader learns to skip; and a knob value the collector could not use is named too, appended to `COLLECTION-TRUNCATED.txt` when there is one, written to `COLLECTION-NOTES.txt` when there is not, and appended to `COLLECTION-FAILED.txt` instead when the pod list itself never returned, so the note always sits beside the failure it accompanies rather than in a file the reader has no reason to open, and a bound that turns out to be the default is not mistaken for the bound that was asked for. A pod whose container list came back as a prefix — kubectl named some containers and then failed — leaves `CONTAINER-LIST-INCOMPLETE.txt` beside the logs it did manage to read, because the containers it never named have no file at all and their absence would otherwise read as containers that were silent. A read that succeeded while kubectl also wrote to stderr — a deprecation notice, a partial-result warning — leaves that message in `READ-WARNINGS.txt` beside the object rather than inside it, since `pod.yaml` and the logs are machine-read and a warning line in them costs the parser the file, while dropping it altogether would be the silent loss of evidence this tree exists to prevent. A pod directory whose containers produced any log at all also carries `CONTAINER-LOGS-BOUND.txt`, naming the `--tail` bound those logs were written under (a pod whose every container was silent has no bounded log to describe, so the file is absent), because `--tail` drops the oldest lines and nothing in a log says so; it sits beside the logs rather than inside them, since a log read in full is a complete artifact and the platform's controllers log JSON per line, so a trailing prose line would break every parser that could read the file before. A pod whose container list could not be read leaves `logs-UNAVAILABLE.txt` in its own directory, carrying kubectl's reason, because a pod directory holding `pod.yaml` and `describe.txt` and no logs at all otherwise reads as a pod whose containers were silent. The VM, VMI and services loops carry the same pair of bounds as constants rather than knobs, so a failed install that leaves every LoadBalancer without an address collects the first of them and names the rest instead of running the report step past its own `timeout-minutes: 30`, which would lose the tarball rather than truncate it, since the collector writes it on its last line. That step ceiling is the outer backstop for a read with no bound of its own; it does not save this report, it saves the steps after it, the other uploads included. It carries `continue-on-error: true` alongside, because the step's `|| true` is its standing statement that collecting diagnostics is never fatal and a step killed at its ceiling never reaches that `|| true` — without it a passing run whose collection ran long would be published as a failed one, and every later `failure()` in the job would start meaning "the tests failed or the report was slow". That tolerance also hides the overrun, since the step then renders green, so a following step turns the collect step's `outcome` into a `::warning::` annotation — a bound that fires is recorded, and the outer bound is not exempt from the rule the inner ones follow. The LINSTOR reads that run a command inside a pod carry a ceiling too — they are the only reads whose duration a workload sets rather than the apiserver, and a wedged controller holds the stream open with nothing on either end to close it — and they record a cutoff in `COLLECTION-FAILED.txt` beside their output, which for the two that stream a gzipped tarball is the only place it can go, since a line of prose inside one is an archive nothing opens; the four that produce a table carry the marker in the file as well. A LINSTOR table that got nothing at all — the wedged controller killed before it wrote a byte — says so in the file rather than shipping at zero length, and a read whose stderr could not be captured says that too instead of reporting silence. A LINSTOR table cut short carries the marker inside itself whether the clock or the command ended it, in the same `# [cozyreport]` form every other in-file marker uses so one anchored grep finds them all, and the note about a satellite pod list that came back short lands under `linstor/error-reports/` beside the bundles rather than in the shared Kubernetes file, like every other `.txt` in the tarball, because a short node list whose explanation sits one directory up reads as a small cluster; the two archives cannot take one, since a line of prose inside a gzip stream is a file nothing opens. A cut-off bundle goes one of two ways and the note names both: a stream that got members across is kept and truncated, so a short member list there is the cutoff rather than a satellite with few reports, while a stream killed before its first byte leaves zero bytes and the emptiness check at the call site removes it. The reader runs before that check, so it says which two outcomes are possible instead of asserting one. The four LINSTOR reads whose output is a table keep the remote command's whole message in the file itself when the command produced no table of its own — a partial table plus an error keeps the message beside the file instead, so the table stays a table — because `kubectl exec` appends its own `command terminated with exit code N` last — so the last line there is the one line that never carries the cause, and a listing sent away from its own error is a zero-byte file saying nothing. That note states what the status leaves open instead of resolving it: `kubectl exec` returns the remote command's own exit status, so a 124 there is either the collector's deadline firing or the command itself exiting 124, and nothing separates the two. Every other read in the collector carries a ceiling too, gates included — an `if kubectl get deploy …` that decides whether a module runs is a read, and an unbounded one ends the whole report before the module it guards. A gate cut off short is recorded rather than treated as an answer, because skipping the module produces the same empty tree as a cluster that never had the component; a gate that answers "not installed" is recorded nowhere, since that is the cluster answering correctly and a marker firing on every install without KubeVirt is one a reader learns to skip. What a per-read ceiling does **not** give you is a ceiling on the report: the pod, VM, VMI and services walks carry a count cap and a time budget, and every other per-object walk in the collector carries neither, so their cost is the cluster's to set and a failed install with a hundred not-Ready HelmReleases spends four hundred bounded reads there, four per release. Described as "the walks outside those four" rather than listed by name, because a list of them drifts and reads as complete while it does so — which is the defect this same change removed from the collector's own header. The step's `timeout-minutes` is what bounds that, not the per-read wrapper. Whichever bound stopped a walk says so in `COLLECTION-TRUNCATED.txt`, count and clock alike, because objects removed by the clock while the count note stood alone would read as a cap that never fired. The read that feeds each loop is bounded too: the budget cannot start until rows arrive, so an apiserver hanging on the cluster-wide list would otherwise spend the whole collection step with the deadline never consulted. The budget is a deadline for starting a read rather than for finishing the walk, and it is rechecked between containers but not between a container's current and previous log, so the ceiling is the budget plus one pod's object reads plus both log reads of one container, which is the price of never leaving a half-written file behind. +- **Every bound that the report's pod collection hits is named in the artifact, not only in the job log.** The pod walk stops at `COZY_REPORT_PODS_MAX` pods or `COZY_REPORT_PODS_BUDGET` seconds and leaves `COLLECTION-TRUNCATED.txt` naming whichever fired; a pod it cut off part way through leaves `CONTAINER-LOGS-TRUNCATED.txt`; a pod list that never came back leaves `COLLECTION-FAILED.txt` rather than the empty tree a healthy cluster produces; a missing local `timeout` leaves `COLLECTION-UNBOUNDED.txt`, because the reads still run, just without a ceiling, and a missing dependency on the machine writing the report is not a statement about the cluster; a kind this cluster does not serve at all — `kubectl get vm -A` on an install without KubeVirt, which exits non-zero — leaves `KIND-NOT-SERVED.txt` rather than a failure marker, since that is the cluster answering correctly and a marker that fires on healthy installs is one a reader learns to skip; and a knob value the collector could not use is named too, appended to `COLLECTION-TRUNCATED.txt` when there is one, written to `COLLECTION-NOTES.txt` when there is not, and appended to `COLLECTION-FAILED.txt` instead when the pod list itself never returned, so the note always sits beside the failure it accompanies rather than in a file the reader has no reason to open, and a bound that turns out to be the default is not mistaken for the bound that was asked for. A pod whose container list came back as a prefix — kubectl named some containers and then failed — leaves `CONTAINER-LIST-INCOMPLETE.txt` beside the logs it did manage to read, because the containers it never named have no file at all and their absence would otherwise read as containers that were silent. A read that succeeded while kubectl also wrote to stderr — a deprecation notice, a partial-result warning — leaves that message in `READ-WARNINGS.txt` beside the object rather than inside it, since `pod.yaml` and the logs are machine-read and a warning line in them costs the parser the file, while dropping it altogether would be the silent loss of evidence this tree exists to prevent. A pod directory whose containers produced any log at all also carries `CONTAINER-LOGS-BOUND.txt`, naming the `--tail` bound those logs were written under (a pod whose every container was silent has no bounded log to describe, so the file is absent), because `--tail` drops the oldest lines and nothing in a log says so; it sits beside the logs rather than inside them, since a log read in full is a complete artifact and the platform's controllers log JSON per line, so a trailing prose line would break every parser that could read the file before. A pod whose container list could not be read leaves `logs-UNAVAILABLE.txt` in its own directory, carrying kubectl's reason, because a pod directory holding `pod.yaml` and `describe.txt` and no logs at all otherwise reads as a pod whose containers were silent. The VM, VMI and services loops carry the same pair of bounds as constants rather than knobs, so a failed install that leaves every LoadBalancer without an address collects the first of them and names the rest instead of running the report step past its own `timeout-minutes: 30`, which would lose the tarball rather than truncate it, since the collector writes it on its last line. That step ceiling is the outer backstop for a read with no bound of its own; it does not save this report, it saves the steps after it, the other uploads included. It carries `continue-on-error: true` alongside, because the step's `|| true` is its standing statement that collecting diagnostics is never fatal and a step killed at its ceiling never reaches that `|| true` — without it a passing run whose collection ran long would be published as a failed one, and every later `failure()` in the job would start meaning "the tests failed or the report was slow". That tolerance also hides the overrun, since the step then renders green, so a following step turns the collect step's `outcome` into a `::warning::` annotation — a bound that fires is recorded, and the outer bound is not exempt from the rule the inner ones follow. The LINSTOR reads that run a command inside a pod carry a ceiling too — they are the only reads whose duration a workload sets rather than the apiserver, and a wedged controller holds the stream open with nothing on either end to close it — and they record a cutoff in `COLLECTION-FAILED.txt` beside their output, which for the two that stream a gzipped tarball is the only place it can go, since a line of prose inside one is an archive nothing opens; the ones that produce a table carry the marker in the file as well. A LINSTOR table that got nothing at all — the wedged controller killed before it wrote a byte — says so in the file rather than shipping at zero length, and a read whose stderr could not be captured says that too instead of reporting silence. A LINSTOR table that wrote output and then failed carries the marker inside itself whether the clock or the command ended it, in the same `# [cozyreport]` form every other in-file marker uses so one anchored grep finds them all, and the note about a satellite pod list that came back short lands under `linstor/error-reports/` beside the bundles rather than in the shared Kubernetes file, like every other `.txt` in the tarball, because a short node list whose explanation sits one directory up reads as a small cluster; the two archives cannot take one, since a line of prose inside a gzip stream is a file nothing opens. Off the clock the in-file marker on a table names the exit status and does not say `TRUNCATED`, because `kubectl exec` passes the remote status through, and a command that lists everything it can and exits 1 for one argument it could not open — `zfs list` over a missing pool — wrote a complete listing. A cut-off bundle goes one of two ways and the note names both: a stream that got members across is kept and truncated, so a short member list there is the cutoff rather than a satellite with few reports, while a stream killed before its first byte leaves zero bytes and the emptiness check at the call site removes it. The reader runs before that check, so it says which two outcomes are possible instead of asserting one. The LINSTOR reads whose output is a table keep the remote command's whole message in the file itself when the command produced no table of its own — a partial table plus an error keeps the message beside the file instead, so the table stays a table — because `kubectl exec` appends its own `command terminated with exit code N` last — so the last line there is the one line that never carries the cause, and a listing sent away from its own error is a zero-byte file saying nothing. That note states what the status leaves open instead of resolving it: `kubectl exec` returns the remote command's own exit status, so a 124 there is either the collector's deadline firing or the command itself exiting 124, and nothing separates the two. Every other read in the collector carries a ceiling too, gates included — an `if kubectl get deploy …` that decides whether a module runs is a read, and an unbounded one ends the whole report before the module it guards. A gate cut off short is recorded rather than treated as an answer, because skipping the module produces the same empty tree as a cluster that never had the component; a gate that answers "not installed" is recorded nowhere, since that is the cluster answering correctly and a marker firing on every install without KubeVirt is one a reader learns to skip. What a per-read ceiling does **not** give you is a ceiling on the report: the pod, VM, VMI and services walks carry a count cap and a time budget, and every other per-object walk in the collector carries neither, so their cost is the cluster's to set and a failed install with a hundred not-Ready HelmReleases spends four hundred bounded reads there, four per release. Described as "the walks outside those four" rather than listed by name, because a list of them drifts and reads as complete while it does so — which is the defect this same change removed from the collector's own header. The step's `timeout-minutes` is what bounds that, not the per-read wrapper. Whichever bound stopped a walk says so in `COLLECTION-TRUNCATED.txt`, count and clock alike, because objects removed by the clock while the count note stood alone would read as a cap that never fired. The read that feeds each loop is bounded too: the budget cannot start until rows arrive, so an apiserver hanging on the cluster-wide list would otherwise spend the whole collection step with the deadline never consulted. The budget is a deadline for starting a read rather than for finishing the walk, and it is rechecked between containers but not between a container's current and previous log, so the ceiling is the budget plus one pod's object reads plus both log reads of one container, which is the price of never leaving a half-written file behind. - **`COZY_REPORT_POD_TAIL` bounds each container log** at 2000 lines by default, and a log that was read successfully records which bound it was written under, since `--tail` drops the oldest lines and a file that begins mid-stream looks exactly like a complete one; `-1` restores kubectl's own default of the whole log. `COZY_REPORT_PREFER_NS` (default `tenant-`) is collected first, so a cap that only bites on a broadly degraded cluster is not spent on platform namespaces while the pod the suite died on falls off the end. - **Capture the PREVIOUS container instance, not just the current one.** For a crash-looping pod `kubectl logs` (and the Chainsaw `podLogs` collector, which in v0.2.15 has no `previous` option — it does accept `name`/`namespace`/`selector`/`container`/`tail`/`timeout`/`cluster`/`clusters`) shows the Nth restart — a fresh replay of the same startup path — while the evidence that explains the failure sits in the immediately preceding instance, reachable only via `--previous` and lost for good once the kubelet garbage-collects that container. `hack/e2e-capture-previous-logs.sh` closes this once for every suite from the global `error.catch` (and from `hack/cozytest.sh` for the e2e BATS suites) rather than per-suite: it discovers containers with `restartCount > 0` at runtime — init containers included, since an interrupted bootstrap lives there — orders the app suites' `tenant-test` namespace first (a best-effort ordering only — it never restricts the capture, and for a suite whose pods live in a child tenant namespace it simply degrades to input order), and dumps each to the job log and to `snapshots//previous-logs/`. Containers that never restarted are skipped, so a healthy run emits one line, not a page of "previous terminated container not found". Every way the capture can come up short is named rather than inferred: the `COZY_PREVLOG_MAX` overflow, a malformed cap, a `COZY_PREVLOG_TAIL` that was rejected and fell back to 200 (a zero or leading-zero tail asks kubectl for nothing, which would otherwise be reported as the container having logged nothing), the tail bound each kept log was written under — named in `capture-notes.txt` beside the logs rather than inside them, since `--tail` drops the oldest lines and nothing in the output says so while a log read in full is a complete artifact that a trailing prose line would stop any parser from reading, and suppressed on `-1` because no bound was applied then — a pod list that never returned (which is NOT the same as "nothing restarted" and must not be reported as such), a read that timed out versus one kubectl itself refused (kubelet GC, RBAC, an unreachable node — different problems that a blanket "kubelet GC" line would hide), a previous instance that produced no output, and a capture the outer backstop cut short. A partial log is kept and marked truncated, never deleted — it is the only copy of something already gone from the cluster. Each of those lines the script itself emits is written to `snapshots//previous-logs/capture-notes.txt` as well as to the job log, and the directory is created before the first of them, so a reader who has only the uploaded artifact can still tell a capture that found nothing from one that never ran. The outer backstop firing is the exception: that line comes from the callers, after the script has already been killed, and reaches the job log only. `hack/cozytest.sh` arms this capture, and the other two legs, only for suites whose own filename or whose parent directory carries the `e2e-` prefix, because all three read cluster state and a unit runner has `kubectl` on PATH with no cluster behind it, so a red unit test used to walk into the kubectl-gated legs on its way out, and into the crust-gather one as well on any machine where that binary happened to be installed. -- **The data-plane collector is the third capture leg, and the only one that reads forwarding state off the node.** `hack/e2e-capture-dataplane.sh` runs after the crust-gather snapshot, from `hack/cozytest.sh` for the e2e BATS suites and from the global `error.catch` in `hack/e2e-chainsaw/.chainsaw.yaml` for the Chainsaw ones, and it collects what an object-state snapshot structurally cannot: the cilium endpoint and BPF conntrack view from an affected pod's node, the kernel conntrack table that is the authoritative one for the host-to-local-pod path under `enable-host-legacy-routing`, and the LoadBalancer datapath. Its two callers bound it differently, 600s from `cozytest.sh` and 300s from the Chainsaw catch, so anything added to what it collects has to fit the smaller of the two rather than the one you happened to test under. It holds the same notes contract as the previous-logs collector, with one stated exception: every read carries its own ceiling, and why a read produced nothing goes to `capture-notes.txt` beside the capture rather than only to the job log, because an empty result and a read that never answered are the same bytes on disk and only the note tells them apart; the two EndpointSlice reads in the LoadBalancer path are the exception and report nothing either way, so a `` backend line there does not distinguish an endpointless Service from a read that never answered. +- **The data-plane collector is the third capture leg, and the only one that reads forwarding state off the node.** `hack/e2e-capture-dataplane.sh` runs after the crust-gather snapshot, from `hack/cozytest.sh` for the e2e BATS suites and from the global `error.catch` in `hack/e2e-chainsaw/.chainsaw.yaml` for the Chainsaw ones, and it collects what an object-state snapshot structurally cannot: the cilium endpoint and BPF conntrack view from an affected pod's node, the kernel conntrack table that is the authoritative one for the host-to-local-pod path under `enable-host-legacy-routing`, and the LoadBalancer datapath. Its two callers bound it differently, 600s from `cozytest.sh` and 300s from the Chainsaw catch, so the collector keeps its own wall-clock budget (`COZY_DATAPLANE_BUDGET`) under each: 270s by default, under the Chainsaw one, and 570s passed by `cozytest.sh`. Every call is cut to what is left, nothing starts once it is spent, and the last 90s are kept for the LoadBalancer section. It holds the same notes contract as the previous-logs collector: every read carries its own ceiling, and why a read produced nothing goes to `capture-notes.txt` beside the capture rather than only to the job log, because an empty result and a read that never answered are the same bytes on disk and only the note tells them apart. The two EndpointSlice reads in the LoadBalancer path follow it too, and write `` rather than `` when the read did not answer. - **A catch script needs an explicit `timeout:` that exceeds the inner budgets it contains.** A Chainsaw `script` op is bounded by `timeouts.exec` (5m in `.chainsaw.yaml`) unless it overrides it, so a catch whose own `timeout -k …` wrappers sum past that is *structurally guaranteed* to hit the ceiling — it reports `SCRIPT | ERROR | signal: killed` and yields little. That kill is strictly worse than an inner `timeout` firing, and worse in a way the process tree makes precise: the ceiling SIGKILLs the **shell process alone**, not its process group. Chainsaw runs the shell under `exec.CommandContext` (`pkg/engine/operations/script/operation.go`), whose default cancel is `Process.Kill()` on the shell PID, so every later step in the script is skipped but any collector the shell already spawned is orphaned rather than killed — it keeps running, and it keeps the script's stdout/stderr pipe open. Because that op wires stdout/stderr to in-process buffers, `cmd.Wait()` does not return until the pipe reaches EOF, which needs every inherited fd closed, so the op does not even come back **at** its ceiling until the orphan exits on its own — the ceiling stops being a reliable cut (#4268, where the bucket suite's `verify-every-bucket-takes-a-write` step ran 606s under a 300s ceiling because `mc` kept retrying after the shell was gone). An inner `timeout` instead kills that read at a known budget, exits 124, leaves a partial capture on disk, and lets the rest of the catch run — which is why every read must carry its own cap rather than lean on the op ceiling. Size the op timeout above the sum of the inner budgets and let the inner ones be what fires. - **When the sum cannot fit the op, bound the collection phase as a phase rather than raising the op.** The rule above assumes the inner budgets add up to something an op timeout can sit above. On a failure path that has accumulated collectors it stops being true — the tenant-Kubernetes node-join path in `hack/e2e-chainsaw/_lib/run-kubernetes.sh` sums past what is left of its 67m op once the bringup ahead of it and the snapshot behind it are counted, and several of its reads carry only `--request-timeout`, which bounds one HTTP request rather than a client retrying against a wedged apiserver, so parts of it have no ceiling to add up in the first place. Raising the op ceiling does not fix that shape, it postpones it: a larger ceiling multiplied by a sum that grows with every collector added is the same problem one collector later. What works instead is a wall-clock budget for the whole phase (`COZY_DIAG_PHASE_BUDGET`, with `cozy_diag_phase_start` / `cozy_diag_phase_has_time`): once it is spent, the collectors that have not started are declined out loud instead of attempted, so whatever must run after the phase — the tenant crust-gather snapshot, in that case — is never queued behind work begun past the deadline. Two consequences worth carrying to the next collector. The budget bounds when a collector may *start*, not when the phase ends, so it is not a worst case and the comment next to it must not be written as one. And because what runs last is what gets declined, source order becomes load-bearing: put the cheap reads that discriminate between failure modes ahead of the collectors that cost minutes, or the budget will spend itself on the expensive ones and drop the evidence the path exists to produce. - **Set `crust-gather --duration` explicitly.** It is crust-gather's own budget for the collection phase and it defaults to **60s**; on elapse it abandons the collection and skips its finish step, leaving a partial tree with nothing to say the rest is missing. The outer wall-clock must exceed it, because the API discovery crust-gather runs *first* is not covered by that budget at all — with an unhealthy aggregated APIService (the state a failed e2e is usually in) aggregated discovery times out and the fallback re-walks every group, which can consume the entire outer timeout before a single object is written. Do not diagnose a killed snapshot by bumping the outer number alone; the two budgets bound different phases. Send the collector's output to a log inside the snapshot rather than `/dev/null` so "complete or truncated?" is answerable from the artifact. @@ -133,7 +148,7 @@ Be precise about TIA's scope — it is narrower than "skip E2E for unrelated PRs - **Pre-pull** every kubeovn / linstor / cert-manager image onto all nodes before those HelmReleases install (`hack/e2e-prepull-images.sh`), so clustered workloads (OVN raft, LINSTOR, the cert-manager webhook) do not fail on per-node image-pull stagger. - **Exclude loop devices** from host LVM scanning in the Talos machine config so the host does not activate volume groups inside loop-mounted e2e disk images. - **Fail fast on node readiness** (≈5m, then bail) rather than marching into LB/NFS tests that will also fail — it saves several minutes per attempt and keeps the real failure at the top of the log. -- **Give the sandbox a runner class strictly larger than its guests.** `hack/e2e-prepare-cluster.bats` boots the management nodes with fixed `-smp` and `-m`, and those resources are committed for the whole run, so a lane whose runner only just covers them leaves the host nothing for QEMU's own threads, containerd and the runner agent. A new e2e lane picks its `runs-on` accordingly; `hack/sandbox-runner-headroom.bats` derives both sides and fails the unit suite when any lane loses that margin. +- **Give the sandbox a runner class strictly larger than its nodes.** The management nodes get fixed CPU and memory (`hack/e2e-compose.yaml`, holding the same figures `hack/e2e-prepare-cluster.bats` gives its QEMU guests), and those resources are committed for the whole run, so a lane whose runner only just covers them leaves the host nothing for containerd and the runner agent. A new e2e lane picks its `runs-on` accordingly; `hack/sandbox-runner-headroom.bats` derives both sides and fails the unit suite when any lane loses that margin. ### 10. The E2E workflow split: same-repo vs fork, and the "E2E Tests" commit status @@ -144,21 +159,32 @@ A fork's `pull_request` run carries no registry credentials, so it cannot push t Consequences to keep in mind when touching either workflow: +- **A `workflow_run` workflow always runs the default branch's copy of itself.** An edit to `e2e-fork.yaml` therefore has no effect on any fork PR, the one carrying the edit included, until it is merged to `main`. To see it work, merge first and then push to a fork PR: re-running an existing `e2e-fork` run replays the commit and workflow file it was first triggered with. - **Fork builds export, they do not push (`OCI_EXPORT_DIR`).** The fork's unprivileged build sets `OCI_EXPORT_DIR` (see `hack/common-envs.mk`) so every image is written to a per-image OCI archive artifact instead of being pushed; the privileged `e2e-fork.yaml` later pushes those archives to the registry **by digest**. Any build recipe that shells out to push directly — e.g. a `skopeo copy … docker://…` that bypasses the `image-tags`/`oci-output` macros — must honour `OCI_EXPORT_DIR` too, or a fork build dies with an anonymous-push `denied` (#3257). This is covered by `hack/common-envs_test.bats`. - **"E2E Tests" is a commit status — not a job, and not a check-run.** The required merge-gate context named `E2E Tests` is a GitHub **commit status**, posted by the `plan`/`e2e-report` pair for same-repo PRs and by `e2e-fork.yaml`'s `resolve`/`report` pair for forks — **not** the `e2e` job itself. Each lane opens the context with `pending` and concludes it when the suite is done, and the opener is not optional: a commit status never expires, so a head SHA that already went green would otherwise keep reading green from the moment a re-run, a reopen or a `full-e2e` label starts a new run until that run reports, leaving the pull request mergeable across a suite that may be about to fail. While the gate was a job, a fresh non-success check run appeared automatically and closed that window. The two lanes close it at different speeds, and the fork lane does not close it entirely. Same-repo, the opener is `plan`'s first step, so the window lasts seconds. On a fork the opener is `resolve`, which cannot run until the unprivileged build has finished, so re-running an already-green fork head leaves the old green readable for the length of that build. The gap is structural rather than an oversight: a fork's `pull_request` token is read-only and cannot write a status at all, which is the same property the rest of this design relies on. It is bounded by the build and it is the one case where "the opener closes the window" is not literally true. Two reasons it is a status: - *Not a job:* a required *job* that is skipped (as the `e2e` job is for forks) counts as passed by branch protection — exactly how fork PRs used to merge with e2e never run (#3257). A status is `success` only when the report step posts it; a never-posted required status stays "Expected" and blocks the merge. If you rename the `e2e` job, do **not** name it `E2E Tests` and do not wire branch protection to a job name — the status must stay the gate. - *Not a check-run:* a check-run created with the default `GITHUB_TOKEN` floats into an arbitrary GitHub Actions check-suite (in practice the earliest-registered one, a tiny labeler — that is why `E2E Tests` once rendered under "PR size label"), and an app-token check-run would need the COZYSTACK_CI app granted `checks: write`. A commit status has neither problem: branch protection matches it by context name and it carries no check-suite grouping. It is safe to post with the default token because a fork's `pull_request` token is **read-only** and cannot post a status — so only same-repo runs (`plan`'s opener and `e2e-report`, both guarded `!fork`) and the privileged `workflow_run` in `e2e-fork.yaml` can set it. Each publishing job carries `permissions: statuses: write` and calls `repos.createCommitStatus`. `plan`'s opener is additionally `continue-on-error`, since every build and test job hangs off `plan` and a transient status-API failure there must not discard the run; losing it only restores the stale-green window for that one run. **Consequence for branch protection:** require the `E2E Tests` **status context** (no GitHub App and no app-id pin needed). + **This pattern now has a second consumer — change it in both places.** `.github/workflows/api-review-gate.yaml` publishes the `API Review Gate` context the same way for same-repo PRs, from an `api-gate-report` job, and `api-review-gate-fork.yaml` publishes it for forks. Two details measured while wiring it up are worth recording here, because they are the load-bearing reason the gate cannot be a job. First, check runs are **not** deduplicated per name: each workflow run gets its own check suite, so `GET /commits/{sha}/check-runs?filter=latest` returns the same set as `filter=all`, and two runs on one head SHA leave two verdicts standing for one context name — the aggregate is worst-of, so a cancelled run poisons the context until the next push. Commit statuses **are** deduplicated per context, newest wins. Second, the read-only-token restriction on fork PRs covers `pull_request_review` as well as `pull_request`, so an approval arriving on a fork PR cannot publish a status either. Together these give the invariant both gates rely on: a run that posts nothing preserves whatever verdict a real run last reached, and can never invent one. + + The fork half of the API gate departs from `e2e-fork.yaml` in three ways, each forced by a measurement. It does not take a fork from `workflow_run.head_repository` or `workflow_run.pull_requests`: for a `pull_request_review` run on a fork PR the first names the base repository and the second is empty, so it resolves the PR from the base repo's open PR list by head SHA instead. It does not relay the triggering run's conclusion, because a fork's run executes the fork's copy of the gate workflow; it builds the detector from the default branch, not from the merge base a fork's author chooses, runs it over the fetched head as data, and reads the reviews API itself. And it also runs on a schedule, because the repository makes every run from an external contributor wait for a maintainer's approval and a run in `action_required` never fires `workflow_run`, so an API owner's approval on such a PR reaches the status only through the sweep, scheduled every fifteen minutes (GitHub may start a scheduled run late). The sweep moves only a status the full evaluation already set after finding a sizeable change, between "needs an approving review" and "approved"; a fork PR whose push run still awaits approval has no status for it to move, and stays unmergeable until a maintainer lets that run execute, as it does for `E2E Tests`. A status lives on the commit, not on a PR, so a head that an open same-repo PR carries is left to that PR's own reporter, however many fork PRs carry it too, and a fork PR on such a head shows whichever verdict stands there even when its base differs, as two same-repo PRs at different bases already do, because one commit status cannot hold a verdict per base. A head carried only by fork PRs fails closed, since their bases can differ: `resolve` writes the failure and the sweep turns a success already standing there into the same one, and it recovers on the next evaluation once all but one of them are closed. + - **Fork TIA reads trusted inputs, but the fork still writes the selector.** `e2e-fork.yaml`'s `e2e` job runs the same `select-e2e.sh` TIA as in-tree (§7), and its inputs are hardened: the changed-file list and the `full-e2e` label come from `resolve`'s base-repo API lookups (`pulls.listFiles` / the PR's labels), the same trusted source as the docs-only decision, passed in as outputs (`changed_b64`, `full_e2e`) rather than re-derived from a `git diff` of the fork-controlled merge ref. Keep that part as it is: re-deriving the selection from the checked-out tree would add a second bypass for no gain. - **What the fork lane is, and is not.** The `e2e` job runs from the fork's tree, so `select-e2e.sh`, the suites under `hack/e2e-chainsaw/`, `hack/e2e-install-cozystack.bats` and `packages/core/testing`'s recipes are all fork-authored. A fork that wants its own suite to report green can edit any of them, and hardening the TIA inputs does not change that. Read the lane accordingly: it is a correctness gate that stops an honest contributor shipping a regression, not a boundary against a hostile one. What contains a hostile fork is that no fork run executes without maintainer approval (below), that the job holds no push credential, and that a diff editing the test harness is visible in review. -- **A fork PR that adds a new image cannot go green until that image exists on the base branch.** `publish` derives the set of archive names it will accept from the base parent (`HEAD^1`), so that a fork cannot mint arbitrary repositories under the CI registry by naming an artifact. An image the PR itself introduces is therefore not in that set, and the job fails with `image '' is not in the base-tree allowlist`. This is fail-closed by design and there is no label override — land the image on the base branch first, or run the suite from a same-repo branch. If a fork e2e run fails on that line, the contribution is not broken; the allowlist is doing its job. +- **A fork PR that adds a new image cannot go green until that image exists on the base branch.** `publish` derives the set of archive names it will accept from the base parent (`HEAD^1`), so that a fork cannot mint arbitrary repositories under the CI registry by naming an artifact. An image the PR itself introduces is therefore not in that set, and the job fails with `image '' is not in the base-tree allowlist`. This is fail-closed by design and there is no label override — land the image on the base branch first, or run the suite from a same-repo branch. If a fork e2e run fails on that line, the contribution is not broken; the allowlist is doing its job. So that a contributor learns this before the build rather than after it, `plan` in `pull-requests.yaml` runs `hack/fork-new-images.sh` on fork PRs and fails with the names of the new images. That check runs from the fork's tree and is a courtesy, not the boundary; `hack/fork-new-images.bats` holds its derivation to the one `publish` uses. - **`labeled` events run in their own concurrency group, and a cancelled run reports nothing.** Because the gate is a status rather than a job, a run that dies without posting leaves the head SHA at "Expected" — which blocks the merge rather than passing it. Several separate pieces implement it, and weakening any one of them reopens the gap. Each lane's terminal reporter runs under `!cancelled()` rather than `always()`, so a run that was cancelled publishes nothing at all and the `pending` it opened stands until the run that superseded it reports. Each lane's concurrency key then keeps a run that is going to publish nothing out of the group of the run that is: `pull-requests.yaml`'s appends `-label` for a `labeled` event that `plan` discards, so labelling an open PR cannot cancel a live `opened`/`synchronize` run (the replacement run would never post the status the cancelled run was going to) — the condition is the complement of `plan`'s guard, so a `full-e2e` label, which does publish, stays in the main group and supersedes the head run instead of racing it, `e2e-fork.yaml`'s concurrency key appends the triggering run's id when that run concluded `cancelled` or `skipped` so a privileged run that is going to post nothing cannot cancel the one that is going to post, and `e2e-fork.yaml`'s `resolve` returns early on a `cancelled`/`skipped` triggering run instead of posting `failure` for it. If you touch any of them, keep the invariant: exactly one run per head SHA is responsible for the status, and a run that is not that one must post nothing at all. **Security prerequisite (repo setting).** The split is only safe if fork runs require maintainer approval before they execute. The repository must keep **Settings → Actions → "Require approval for all outside collaborators"** enabled, so a fork's `pull_request` run — which produces the artifacts `e2e-fork.yaml` consumes — cannot run untrusted code (or feed the privileged run) without a maintainer's go-ahead. +### 11. Never negate a BATS assertion with `!` + +An assertion spelled `! cmd` inside an `@test` body can silently pass. POSIX exempts a command whose return value is inverted with `!` from `set -e`, so a failing inverted status does not stop the test body. `hack/cozytest.sh` then appends `return 0` to every test function, so it never resurfaces as the test's own status. The `bats` binary looks stricter and mostly is not: its ERR trap carries the identical exemption, and `bash -c 'set -eE; trap "echo TRAP" ERR; ! true; echo REACHED'` prints `REACHED`, runs no trap, and exits zero. The one shape `bats` does catch is a negated assertion standing **last** in the body, where the inverted status is what the function returns — put any statement below it and `bats` passes the test too. This is the same family as the ban on test-level `EXIT`/`RETURN` traps, and unlike that one it is not settled by preferring the stricter runner, because there is no stricter runner to prefer. + +The exemption applies to any inverted command, not just pipelines: `! true`, negated `[ … ]`, negation inside a `for` body, and negation following `;`, `&&` or `||` do not trigger errexit. A later successful statement can hide their failure. Write the absence so that it fails — `if cmd; then echo "FAIL: "; false; fi` — and let the `false` carry the verdict. `hack/bats-no-negated-assert.bats` enforces this across every `hack/**/*.bats`, subdirectories included. Inverted **conditions** (`if !`, `elif !`, `while !`, `until !`) are untouched, because `set -e` is not what decides a condition. `[ ! -f x ]` is untouched for a different reason and stays a normal, failing assertion: the `!` there is an operator of `test`, not negation of a command, so nothing exempts its status. The scan is lexical, with the limits that implies: a statement assembled at runtime is invisible to it, and the form is counted inside a heredoc or a fixture string where no command exists — which reports a file holding nothing rather than passing one that does, and is why that guard's own fixtures build the token from a separate `printf` argument. + ## Chainsaw v0.2.15 gotchas The suite is pinned to Chainsaw **v0.2.15** (the latest release as of May 2026); none of the traps below are fixed upstream yet, so the workarounds stay until a bump is possible. Each one has already cost a debugging session — this is the "no one gets it right the first time" list, worth a read before writing a new assert. @@ -179,10 +205,11 @@ The suite is pinned to Chainsaw **v0.2.15** (the latest release as of May 2026); 3. Imperative-only waits live in a `script` step; any bare `sleep` carries a `TODO(e2e-replace-fixed-timeouts):` justification, unless it is a measurement interval, which §2 carves out by name and which takes no marker because no event can replace it. 4. No test-level `EXIT`/`RETURN` trap — rely on Chainsaw cleanup; a self-contained trap is allowed inside a single `script` step (port-forward / temp dir), and inside an explicit subshell within a BATS `@test`, where it does not displace the runner's own handler. A BATS file that still carries test-level traps declares the count itself in `# EXIT-TRAP DEBT: N`; do not ask for one to be removed without checking that line, because the count is exact in both directions. 5. Controller-created artifacts the test cannot reclaim are pruned explicitly; nested tenants delete child → parent with a wait-for-deletion between. -6. An HR-Ready assert has a floor: the release's own install timeout, not only the app's boot time. Below it a failed install reports as a bare assert timeout, so **a number under the floor buys a shorter red run at the price of the diagnosis**. Whether to raise a given suite to clear it is a per-suite call, made against what that suite's red runs cost; most of the tree currently sits under it. Derive the floor from [Sizing an HR-Ready budget](#sizing-an-hr-ready-budget) rather than copying a neighbour's number, and justify a raise in-line. The same goes for any other wait longer than the ones around it, HR-Ready or not: it carries its reason in-line. +6. An HR-Ready assert has a floor: the release's own install timeout, not only the app's boot time. Below it a failed install reports as a bare assert timeout, and above it by less than a start margin it can, so **a number under the floor buys a shorter red run at the price of the diagnosis**. Whether to leave a suite under it is a per-suite call, made against what that suite's red runs cost; either way, a Chainsaw assert left under it says why in-line. Derive the floor from [Sizing an HR-Ready budget](#sizing-an-hr-ready-budget) rather than copying a neighbour's number, and justify a raise in-line. The same goes for any other wait longer than the ones around it, HR-Ready or not: it carries its reason in-line. 7. Failure path attaches scoped diagnostics via a `catch:` block, never a silent pass. The node-join deadline is no exception, and no longer has one: with the soft-red marker gone it fails its suite like any other deadline and its diagnostics run from the same `catch:`. -8. If it touches parent-HR behavior, add the `status.history` remediation guard (`hack/e2e-chainsaw/_lib/remediation-guard.sh`). +8. If it touches HelmRelease install/upgrade behavior, add the `status.history` guard: fail the run on a `failed` or `uninstalled` Snapshot of a release whose install strategy is `RetryOnFailure`, fail it on a parent whose strategy is anything else, and report the footprint of every other release without failing. What is reusable today is the predicate and the jsonpath in `hack/e2e-chainsaw/_lib/remediation-guard.sh`; the policy that weighs the footprint against `.spec.install.strategy.name`, judges an empty history against the release's own readiness, and keeps each read's exit status apart from its output lives in `cozy_guard_helmrelease` in `hack/e2e-chainsaw/_lib/run-kubernetes.sh` — read it before rebuilding any of that for another suite. If the suite has a failure path that exits before the guard, give that path `cozy_report_helmrelease_remediation` as well, or the runs the guard exists for are the runs it does not see. 9. A test that creates a tenant `Kubernetes` cluster waits for its release to reach `Ready` **before the assertions it ends on**, with a `--timeout` the guard can read as positive and no longer than a day. Reads earlier in the run are expected and are not what this bounds. The mechanism, how to size the budget and what the guard does with it are under "Do not mask cleanup or teardown failures". One thing to carry from there rather than look up: the naming is part of the rule, not a detail of the check, so an end-assertion added under any name outside the `cozy_assert_*` / `cozy_switch_and_assert_*` convention is invisible to it and passes before the wait without reddening anything — as long as one recognised call site is left behind it. Rename every recognised call and the guard reds instead, on finding none at all, which is the one shape of this mistake it does catch. +10. No BATS assertion begins with `!` — an inverted status is exempt from `set -e` and can be silently ignored; use `if cmd; then echo "FAIL: …"; false; fi`. ## The container lane: what the srv nodes are, and what that costs @@ -192,7 +219,7 @@ What that buys, measured in CI on commits where both substrates ran: the two ten Three properties of container mode drive the whole design, and each one fails quietly rather than loudly if ignored. `machine.kernel.modules` is a **silent no-op** — `kernel_module_spec.go` returns early on `ModeContainer` with no error and no event — so the host must load `openvswitch` and `zfs` before the nodes start, and both the host script and the BATS file assert it rather than trusting it. Docker gives a privileged container its **own tmpfs `/dev`, seeded once at creation**, so `/dev/kvm` works but ZFS zvols created later never appear and linstor-csi fails `ControllerPublishVolume`; the compose file binds the host devtmpfs instead, which is also why `talosctl cluster create docker` can never carry LINSTOR. And container mode has **no ARP VIP**, so `192.168.123.11` stands in for the QEMU lane's `192.168.123.10` and `hack/e2e-install-cozystack.bats` takes the endpoint from `COZY_APISERVER_ENDPOINT`, defaulting to the unchanged QEMU value. -In CI this is the `e2e` job in `.github/workflows/pull-requests.yaml` and the `e2e` job in `e2e-fork.yaml` — the two lanes that gate a merge. The QEMU substrate is wired into neither of them any more, and the PR path no longer builds or downloads a nocloud disk at all. `make -C packages/core/testing prepare-cluster` and `hack/e2e-prepare-cluster.bats` stay in the tree because `nightly.yaml` and `e2e-tag.yaml` still run the suite on QEMU: nightly and release-candidate coverage is where DRBD, the `replicated` StorageClass and the Cozystack Talos node image keep being exercised, since none of the three can run on containers. +In CI this is every lane that runs the suite: the `e2e` jobs in `.github/workflows/pull-requests.yaml` and `e2e-fork.yaml`, which gate a merge, and the `e2e` jobs in `nightly.yaml` and `e2e-tag.yaml`. No workflow boots the QEMU substrate or downloads a nocloud disk any more. `make -C packages/core/testing prepare-cluster` and `hack/e2e-prepare-cluster.bats` stay in the tree because unit tests still read the node sizing and addressing from that file, but nothing in CI runs them, so DRBD, the `replicated` StorageClass and the Cozystack Talos node image have no e2e coverage until a lane with a kernel per node exists (cozystack/cozystack#4642). Root entry points are `make prepare-env-container` (host-side compose plus the in-sandbox BATS file) and `make -C packages/core/testing delete-cluster-container`, which is also the retry cleanup: a half-started compose project the next attempt adopts is not a fresh try. @@ -200,11 +227,11 @@ The nodes run as **siblings on the runner's docker daemon**, not nested inside t What the lane gives up is **DRBD, and with it more than the `replicated` StorageClass**. DRBD's resource registry is global per kernel, so three containers sharing one kernel cannot represent three DRBD nodes — a second `new-resource` for the same name returns success while changing nothing, which is worse than an error because LINSTOR then records a replica it does not have. It applies to kind equally; it is a property of one kernel, not of Talos. `linstor` must therefore run with `drbd.enabled: false`, without which every satellite CrashLoops and no PVC binds at all. Because linstor-csi couples RWX to DRBD, tenant worker disks become RWO and **live migration is unavailable on this lane**, which nothing in the tree tests today either way. Everything else survives: kube-ovn runs the real OVS dataplane, and LINSTOR keeps real ZFS pools and the production `local` StorageClass. -Two further things move off the per-PR path with the substrate, and both keep their nightly and release-candidate coverage rather than losing it. `replicated` is `volumeBindingMode: Immediate` while `local` is `WaitForFirstConsumer`, so the Immediate binding path is not exercised per PR; and tenant StorageClass propagation only applies to classes that are not `allowRemoteVolumeAccess: "false"`, which on this lane is none of them. The management nodes also boot upstream `ghcr.io/siderolabs/talos` rather than the Cozystack image, so the extensions that image carries — `drbd`, `zfs`, `openvswitch` — and the LVM filter are validated nightly rather than on every pull request. Tenant worker nodes still import a Talos disk, so that half of the Talos path is unaffected. +Two further things go with the substrate, and no lane covers them. `replicated` is `volumeBindingMode: Immediate` while `local` is `WaitForFirstConsumer`, so the Immediate binding path is not exercised; and tenant StorageClass propagation only applies to classes that are not `allowRemoteVolumeAccess: "false"`, which on this lane is none of them. The management nodes also boot upstream `ghcr.io/siderolabs/talos` rather than the Cozystack image, so the extensions that image carries — `drbd`, `zfs`, `openvswitch` — and the LVM filter are not validated by e2e. Tenant worker nodes still import a Talos disk, so that half of the Talos path is unaffected. One property of container mode has no fix here and is worth knowing before reading a red run: a node reports the **host's** CPU and memory as its capacity. `hack/e2e-container-up.sh` counterbalances that with kubelet `systemReserved` so the scheduler sees 8 CPU / 24 GiB per node, which corrects the scheduler and not what a pod reads from `/proc`. A workload that sizes itself from `/proc/cpuinfo` or `/proc/meminfo` is therefore configured for the whole runner. -The local-only mode has two mandatory install-time adaptations. CDI otherwise ranks `ReadWriteMany`/`Block` first for any LINSTOR StorageClass, so post-install prep waits for `StorageProfile/local` and pins it to `ReadWriteOnce`/`Block` before any tenant DataVolume is created; without that override linstor-csi rejects the first worker disk because RWX requires DRBD. Root VictoriaLogs is the only install workload that explicitly defaults to `replicated` instead of inheriting the default class, so the E2E installer adds its `logsStorages` override to `tenant-root/cozystack-values` before enabling monitoring; patching the generated monitoring HelmRelease afterward is unsafe because it can create an immutable replicated PVC first. +The local-only mode has one mandatory install-time adaptation and keeps a second for a run that turns root monitoring on. CDI otherwise ranks `ReadWriteMany`/`Block` first for any LINSTOR StorageClass, so post-install prep waits for `StorageProfile/local` and pins it to `ReadWriteOnce`/`Block` before any tenant DataVolume is created; without that override linstor-csi rejects the first worker disk because RWX requires DRBD. Root VictoriaLogs is the only root-tenant workload that explicitly defaults to `replicated` instead of inheriting the default class. The installer leaves root monitoring off, so VictoriaLogs does not render by default, but it still writes a `logsStorages` override into `tenant-root/cozystack-values` before the Tenant patch, so a run that enables monitoring gets local claims on the first render; patching the generated monitoring HelmRelease afterward is unsafe because it can create an immutable replicated PVC first. Two capacity edges are handled explicitly. A container node reports the **host's CPU and memory** as capacity rather than its compose cgroup limits, so `hack/e2e-container-up.sh` computes kubelet `systemReserved` from the host totals and caps each node's scheduler-visible allocatable near 8 CPU / 24 GiB; it refuses a host without strict aggregate headroom, and the live preparation suite asserts every Node's resulting allocatable. Each ZFS pool uses a sparse 200 GB backing file, matching the QEMU lane's per-node data disk: root-tenant reservations can otherwise leave less than the ~21 GiB required by CDI scratch on the node where its 20 GiB target disk is already bound. The apparent 600 GB is not preallocated, but blocks written during the run consume the shared runner disk until teardown destroys the pools and backing files. @@ -212,19 +239,19 @@ That second point used to be much worse than a sizing note. An importer pod moun ## Sizing an HR-Ready budget -Give an HR-Ready wait a budget strictly above both the app's first-boot budget and the install timeout of the release it waits on, read off the ApplicationDefinition for a generated release and off the rendering template otherwise; the rest of this section is how to find those two numbers. +Give an HR-Ready wait a budget that clears, by a start margin, both the app's first-boot budget and the install timeout of the release it waits on, read off the ApplicationDefinition for a generated release and off the rendering template otherwise; the rest of this section is how to find those two numbers. -A HelmRelease install waits through kstatus unless the ApplicationDefinition carries `release.cozystack.io/helm-install-disable-wait`. `kubernetes-rd` and `kubernetes-nodes-rd` are the only two that do, so their installs never poll at all — though the `kubernetes` chart's blocking post-install hook still holds its install open, and sizing a wait on that kind is covered under "Do not mask cleanup or teardown failures" rather than here. Two other things would take an install off kstatus and onto helm's own readiness logic, neither of them in effect: a `spec.release.waitStrategy` of `legacy`, which no ApplicationDefinition sets at all — the only two places in the tree setting a strategy are hand-written HelmRelease templates under `packages/extra/`, and both set `poller` — and the `UseHelm3Defaults` feature gate, which flips the controller-wide default to `legacy` and is not among the gates helm-controller runs with here. Every other release therefore polls, and the wait in front of it has two floors. It has to beat both, and beat them strictly. A wait equal to the install-timeout floor does not merely tie with it: the two clocks start at different moments, the wait's when the step runs and the install's once the Application has been reconciled and the chart artifact fetched, so at equal budgets the wait is the one that expires, and it expires before the release has recorded anything about the failure. +A HelmRelease install waits through kstatus unless the ApplicationDefinition carries `release.cozystack.io/helm-install-disable-wait`. `kubernetes-rd`, `kubernetes-nodes-rd` and `vm-instance-rd` are the only three that do, so their installs never poll at all — though the `kubernetes` chart's blocking post-install hook still holds its install open, and sizing a wait on that kind is covered under "Do not mask cleanup or teardown failures" rather than here. Two other things would take an install off kstatus and onto helm's own readiness logic, neither of them in effect: a `spec.release.waitStrategy` of `legacy`, which no ApplicationDefinition sets at all — the only two places in the tree setting a strategy are hand-written HelmRelease templates under `packages/extra/`, and both set `poller` — and the `UseHelm3Defaults` feature gate, which flips the controller-wide default to `legacy` and is not among the gates helm-controller runs with here. Every other release therefore polls, and the wait in front of it has two floors. It has to beat both by a start margin. A wait equal to the install-timeout floor does not merely tie with it: the two clocks start at different moments, the wait's when the step runs and the install's once the Application has been reconciled and the chart artifact fetched, so at equal budgets the wait is the one that expires, and it expires before the release has recorded anything about the failure. The margin has to cover that gap, the helm-controller queue included; nothing in the tree bounds any part of it, so it is a policy value, held in `MBW_START_MARGIN` in `hack/mariadb-first-boot-waits.bats`. The first floor is the app's own first boot. For a chart that sets `startupProbe` it is `initialDelaySeconds + (failureThreshold - 1) * periodSeconds`; for a chart that does not, it is whatever its operator needs, and only a measurement will say. mariadb is the case in this tree where this floor is real rather than nominal: its chart grants a 310s startup budget, so a wait that fails earlier fails a boot the probe was still willing to wait for. -The second floor is the release's own install timeout, and it is usually the binding one. Where to read it depends on who created the release, and getting this wrong under-budgets rather than over-budgets. For a release cozystack-api generated from an ApplicationDefinition the default is 10m (`pkg/cmd/server/start.go`), overridden per definition by `release.cozystack.io/helm-install-timeout` — `kubernetes-rd` at 20m, `kubernetes-nodes-rd`, `tenant-rd` and `monitoring-rd` at 15m, `kafka-rd` at 7h, a floor no suite clears inside the E2E job's 215-minute cap; the first two also disable the wait, so for `kubernetes` the override bounds its blocking post-install hook rather than a kstatus poll, and `kubernetes-nodes`, which renders no post-install hook, has nothing in its install for the override to bound. For a HelmRelease an app chart renders itself there is no ApplicationDefinition to read and that default never applies: the floor is the `spec.install.timeout` on the template that renders it, which takes precedence over its `spec.timeout`, and where a template sets neither, helm-controller's own documented default of 5m applies instead. There is deliberately no count of that population here. Read the value off the template you are waiting on: they range from 5m to 30m, they are spread across `packages/apps`, `packages/extra` and `packages/system`, and a release carrying `spec.kubeConfig` installs into a tenant cluster and is not one of these at all. A number in this sentence would be an obligation to revisit it whenever a template is added, and its three qualifiers are each easy to drop from a recursive grep. The nested `-system` releases the app charts wrap their workloads in are all of this second kind. At or below whichever floor applies, a failed install is reported as a bare assert timeout, because the release has not yet recorded why it failed. +The second floor is the release's own install timeout, and it is usually the binding one. Where to read it depends on who created the release, and getting this wrong under-budgets rather than over-budgets. For a release cozystack-api generated from an ApplicationDefinition the default is 10m (`pkg/cmd/server/start.go`), overridden per definition by `release.cozystack.io/helm-install-timeout` — `kubernetes-rd` at 20m, `kubernetes-nodes-rd`, `tenant-rd` and `monitoring-rd` at 15m; the first two also disable the wait, so for `kubernetes` the override bounds its blocking post-install hook rather than a kstatus poll, and `kubernetes-nodes`, which renders no post-install hook, has nothing in its install for the override to bound. For a HelmRelease an app chart renders itself there is no ApplicationDefinition to read and that default never applies: the floor is the `spec.install.timeout` on the template that renders it, which takes precedence over its `spec.timeout`, and where a template sets neither, helm-controller's own documented default of 5m applies instead. There is deliberately no count of that population here. Read the value off the template you are waiting on: they range from 5m to 30m, they are spread across `packages/apps`, `packages/extra` and `packages/system`, and a release carrying `spec.kubeConfig` installs into a tenant cluster and is not one of these at all. A number in this sentence would be an obligation to revisit it whenever a template is added, and its three qualifiers are each easy to drop from a recursive grep. The nested `-system` releases the app charts wrap their workloads in are all of this second kind. A HelmRelease that cozystack-operator builds for a `Package` is a third kind: its `spec.install.timeout` comes from the operator's `--helmrelease-install-timeout`, 10m unless `cozystackOperator.helmReleaseInstallTimeout` in the installer chart overrides it. At or below whichever floor applies, a failed install is reported as a bare assert timeout, because the release has not yet recorded why it failed. What holds the install open is anything in the rendered manifests kstatus reports InProgress, which is wider than a `Ready` condition. kstatus carries built-in rules for a list of kinds — the workloads, but also `Service`, `Pod`, `PersistentVolumeClaim` and `CustomResourceDefinition` — and falls through to reading `Ready` only for kinds it has no rule for. Read that list rather than recalling it: `legacyTypes` in `pkg/kstatus/status/core.go` of `fluxcd/cli-utils`, at whatever version the helm-controller image in `internal/fluxinstall/manifests/fluxcd.yaml` was built against — nothing in this repository vendors it, so there is no local copy to open and the version has to come from that image. It does not divide the way intuition suggests, because `Secret`, `ConfigMap` and `batch/CronJob` are in the table and map to always-ready, so being in it is not the same as gating on it. The practical consequence is that "renders no CR publishing `Ready`" does not exempt a release, and `tcp-balancer` and `vpn` show why: each renders a `WorkloadMonitor`, whose status type declares no `conditions` at all, so kstatus falls past the `Ready` fallback and reads that CR as Current — and then gates the install on the Deployment beside it through a built-in rule. The CR is present and contributes nothing; the workload is what holds the install open. -Every mistake in this derivation under-budgets, which is the harmful direction — but the floor is not free either, because a wait that must exceed its release's install timeout means a genuinely failing suite burns that long before it says so, and `.chainsaw.yaml` already warns about diagnostics eating the job's own 215m — for scale, the timeouts written on the mariadb suite's own steps come to 114m of that, before the defaults its untimed steps inherit from `.chainsaw.yaml`, and a job cancelled at the cap loses both its log and `cozyreport.tgz`. Raise a suite when a failed install there needs to say why; leave one alone when the diagnosis is not worth ten minutes added to every red run in that suite. That is the trade, and it is per suite — "only the ones kstatus polls" is not a filter, because almost everything polls. Two waits are worth reading before writing a new one, and deliberately not as a list of every wait above the band: a hand-written list of them is incomplete in a way its author cannot see, and goes stale without saying so — a `grep` for the call misses the invocations split across lines, and reading for it by eye misses the single-release waits among the `--all` ones. Enumerate with `grep -rnE 'kubectl +wait.*(^|[^[:alnum:]])hr([^[:alnum:]]|$)' hack/` and the chainsaw asserts on `kind: HelmRelease`, not from memory and not from here. mariadb's 11m in `hack/e2e-chainsaw/mariadb/chainsaw-test.yaml` is the worked example of the derivation above. harbor's two 10m asserts carry an in-line justification but are not models: one sits exactly on its release's 600s floor rather than above it, and the other gates on the chart-rendered `harbor-test-system`, whose own `spec.timeout` of 15m puts it five minutes under. +Every mistake in this derivation under-budgets, which is the harmful direction — but the floor is not free either, because a wait that must exceed its release's install timeout means a genuinely failing suite burns that long before it says so, and `.chainsaw.yaml` already warns about diagnostics eating the job's own 215m — for scale, the timeouts written on the mariadb suite's own steps come to 120m of that, before the defaults its untimed steps inherit from `.chainsaw.yaml`, and a job cancelled at the cap loses both its log and `cozyreport.tgz`. Raise a suite when a failed install there needs to say why; leave one alone when the diagnosis is not worth ten minutes added to every red run in that suite. That is the trade, and it is per suite — "only the ones kstatus polls" is not a filter, because almost everything polls. Two suites are worth reading before writing a new wait, and deliberately not as a list of every wait and its floor: a hand-written list of them is incomplete in a way its author cannot see, and goes stale without saying so — a `grep` for the call misses the invocations split across lines, and reading for it by eye misses the single-release waits among the `--all` ones. Enumerate with `grep -rnE 'kubectl +wait.*(^|[^[:alnum:]])hr([^[:alnum:]]|$)' hack/` and the chainsaw asserts on `kind: HelmRelease`, not from memory and not from here. mariadb's 11m in `hack/e2e-chainsaw/mariadb/chainsaw-test.yaml` is the worked example of the derivation above. harbor's two asserts show why one literal cannot serve a whole suite: `harbor-test` is generated and clears its 600s floor at 11m, while `harbor-test-system` is rendered by the app chart with a `spec.timeout` of 15m and needs 16m. -Two things this derivation does not give you. Readiness *may* span a first boot rather than always doing so — a poll landing before the operator's first status write reads a condition-less resource as Current and can end the wait early, which is why a suite keeps an endpoint assert after the HR-Ready one rather than treating it as redundant. And most budgets already in the tree sit under the floor, by per-suite choice or by default, so a number copied from a neighbouring suite says nothing about the release you are waiting on. Scanning `hack/e2e-chainsaw/*/chainsaw-test.yaml` for HR-Ready asserts whose timeout is at or below 600s finds them across more than a dozen suites, of which mariadb is the only one raised so far; the count is left to that scan rather than written out here, because a list of them goes stale silently while the scan does not. Chainsaw asserts are not the whole surface: `wait_hr_ready` calls under `examples/backups/` carry the same floor, not all of them from a `run-all.sh`, and the bucket waits are under it even in the examples whose database waits clear it, so scan both places. Derive the budget from the release you are waiting on. +Two things this derivation does not give you. Readiness *may* span a first boot rather than always doing so — a poll landing before the operator's first status write reads a condition-less resource as Current and can end the wait early, which is why a suite keeps an endpoint assert after the HR-Ready one rather than treating it as redundant. And a number copied from a neighbouring suite says nothing about the release you are waiting on, even where it clears the neighbour's floor: the floor depends on who rendered the release, and kafka's assert sits under its own on purpose. Scan `hack/e2e-chainsaw/*/chainsaw-test.yaml` for HR-Ready asserts and hold each against its own release's floor plus the start margin; the result is left to that scan rather than written out here, because a list of them goes stale silently while the scan does not. Chainsaw asserts are not the whole surface: `wait_hr_ready` calls under `examples/backups/` carry the same floor, not all of them from a `run-all.sh` and not all of them with a literal budget — a call that passes none takes the helper's own default, which a grep for the number misses — so scan both places. Derive the budget from the release you are waiting on. ## In-flight direction (not yet the merged standard) diff --git a/docs/agents/image-refs.md b/docs/agents/image-refs.md index b85c79e72..191bc62c2 100644 --- a/docs/agents/image-refs.md +++ b/docs/agents/image-refs.md @@ -22,7 +22,7 @@ Which tag an image carries depends on what versions it. Confusing these classes | **Component-versioned** | upstream version + cozystack suffix | `cluster-api-control-plane-provider-kamaji:v0.19.0-cozystack.0` | No | | **Third-party pass-through** | whatever upstream publishes | `docker.io/library/busybox:1.37.0` | No | -Version-line images are first-party builds whose version *is* the cozystack version; they are the ones a release rewrites and retags. Component-versioned images are first-party rebuilds of an upstream component, versioned by that component so the provenance stays legible — kamaji keeping `v0.19.0-cozystack.0` across a cozystack release is correct, not a missed rewrite. Third-party images are vendored by digest from registries cozystack cannot push to; they are never retagged and never mirrored. +Version-line images are first-party builds whose version *is* the cozystack version; they are the ones a release rewrites and retags. Component-versioned images are first-party rebuilds of an upstream component, versioned by that component so the provenance stays legible — kamaji keeping `v0.19.0-cozystack.0` across a cozystack release is correct, not a missed rewrite. Only a release build pushes that tag (`PUBLISH_VERSIONED=1`); every other build pushes the image under its build-unique `IMAGE_TAG`, so in a CI registry the component tag in the ref may not exist and the digest is what resolves. Third-party images are vendored by digest from registries cozystack cannot push to; they are never retagged and never mirrored. Only class 1 is touched by a promotion. A tool that "fixes" a class 2 or 3 tag to the cozystack version is introducing a bug, not removing one. @@ -30,7 +30,7 @@ Only class 1 is touched by a promotion. A tool that "fixes" a class 2 or 3 tag t A reference can be stored in three different kinds of file, and **all three are first-class**. Every consumer must read all three. The single most repeated defect in this area is a tool that knows about one shape and silently ignores another; it does not fail, it just quietly skips images, and the gap surfaces a release later. -1. **`packages///values.yaml`** — the common case, in five YAML sub-shapes (single string, split map with `digest`, split map with the digest inside `tag`, chart-global `global.registry.address` + `global.images[]`, and the OCI-artifact `platformSourceUrl`/`platformSourceRef` pair). The sub-shapes exist because vendored upstream charts choose their own values layout; the list is empirical, not closed. +1. **`packages///values.yaml`** — the common case, in the YAML sub-shapes listed here: single string, split map with `digest`, split map with the digest inside `tag`, chart-global `global.registry.address` + `global.images[]`, the OCI-artifact `platformSourceUrl`/`platformSourceRef` pair, and upstream ingress-nginx's split map with the repository in `image` and a separate `digest`. The sub-shapes exist because vendored upstream charts choose their own values layout; the list is empirical, not closed. 2. **`packages///images/.tag`** — a plain file holding one reference, read by templates via `.Files.Get` rather than through values. Easy to forget precisely because it never appears in a values file; otherwise an ordinary first-party reference that carries the cozystack version like any other. 3. **A declared file that embeds a reference in surrounding text** — used when a package vendors an upstream manifest and its `image:` target `sed`s the built reference straight into it. `packages/system/multus/templates/multus-daemonset-thick.yml` is the only instance today. It is vendored *and* patched: it carries Helm conditionals, so `yq` cannot parse it at all and the YAML pass yields nothing for it. What keeps its reference visible is the textual scrape `collect_image_refs` runs over every declared extra — for this entry that leg is not a backstop but the only one that works. @@ -42,11 +42,12 @@ If a package stamps a reference somewhere the two globs do not cover, add that f ## Invariants -- **Every first-party reference is tag+digest.** A bare tag with no digest is not reproducible and must not be committed. `securitygroup-controller:v0.0.0` is a live violation. -- **Exactly one producer stamps each reference.** A reference no `Makefile` writes will never be refreshed by anything, including release preparation — `chBackupClientImage` in `packages/system/backupstrategy-controller/values.yaml` is a live violation, still pinned to `platform-migrations:v1.4.0-rc.2`. -- **A package that stamps a reference is in the root `Makefile` `build:` list.** `build-matrix.sh`, the main build and release preparation all iterate that one list, so a package outside it is never rebuilt by any path and its pin freezes permanently. `flux-plunger`, `keycloak-operator` and `kilo` are live violations (tracked in #3416). +- **Every first-party reference is tag+digest.** A bare tag with no digest is not reproducible and must not be committed. The one exception is the first commit of a new image: it has no digest until it is built, so it lands as a bare `:` that the producing `make image` replaces. PR CI and release preparation both stamp it before anything pulls it, but a tree applied without a build pulls a tag that does not exist. In PR CI the stamp comes from `hack/overlay-main-images.sh` when the PR does not rebuild the package, and it takes a bare first-party ref even from a file whose configuration drifted from the artifact, because a tag that was never pushed cannot install. The cost is that any other digest-less first-party ref in such a file also runs main's image with the PR's older config; third-party refs in it keep their committed pair. +- **Exactly one producer stamps each reference.** A reference no `Makefile` writes will never be refreshed by anything, including release preparation. +- **A package that stamps a reference is in the root `Makefile` `build:` list.** `build-matrix.sh`, the main build and release preparation all iterate that one list, so a package outside it is never rebuilt by any path and its pin freezes permanently. `hack/build-matrix_test.bats` computes the set of packages whose Makefile runs `docker buildx build` and fails on any the list misses. - **Every consumer of references reads all three storage shapes**, via `hack/lib/image-refs.sh`. - **Scan wider than you rewrite.** A rewrite is deliberately narrow to avoid corrupting vendored defaults, so the check that follows it must not share that blind spot. `hack/promote-rewrite-tags.sh` rewrites the enumerated files, then greps the whole tree and fails if any reference to the release candidate survives. +- **A pin can name an index that carries attestation manifests.** An image built with `SBOM=1` is pushed as an index of the image and its attestation manifest, and the ref pins that index, not a single-platform manifest. A consumer that reads a pin's manifest takes the entries with `platform.os == "linux"` as its platforms: an entry whose platform is `unknown/unknown` is an attestation, not a platform. `hack/stitch-multiarch.sh` and `hack/verify-multiarch.sh` read pins this way, and `skopeo copy --multi-arch all`, which the retag and the mirror run, copies the attestation with the image. ## What each consumer does @@ -58,6 +59,13 @@ If a package stamps a reference somewhere the two globs do not cover, add that f | `hack/promote-retag.sh` | all three shapes | copy each digest to its stable tag in the registry | | `hack/nightly-mirror.sh` | all three shapes | copy each digest to the public registry, then rewrite hosts in the same file set | | `hack/overlay-main-images.sh` | `values.yaml` + `*.tag` | overlay current-main references onto packages a PR did not rebuild | +| `hack/stitch-multiarch.sh` | all three shapes | join each amd64 image and its `-arm64` twin into one index, each side an image or, built with `SBOM=1`, an index of the image and its attestation that the result keeps, repin the tree on it, then fail if any old digest survives | +| `hack/retention-packages.sh` | all three shapes, in the published nightly tree | name the GHCR packages the retention workflow prunes (those linked to another repository are then skipped); a ref it cannot see is a package whose nightlies are never pruned | +| `hack/verify-multiarch.sh` | all three shapes, first- and third-party | fail a release unless every pinned image is an index with `linux/amd64` and `linux/arm64`, attestation entries not counted, bar the repositories in `hack/multiarch-allowlist` | + +`hack/multiarch-allowlist` is the only bypass for that gate, and it is for images that cannot exist for arm64, not for images nobody has rebuilt yet. An entry is a repository with no tag or digest, so bumping an allowed image needs no edit, and it must carry a reason after `#` on the same line: the script refuses an entry without one. Allowed refs are still printed, under their own "allowed single-arch" heading, and in tree mode an entry that matches no ref that failed the check is reported as stale without changing the exit status, so it gets removed once the image is multi-arch or gone. `--refs-file` reports no stale entries, since a list of pulled images omits everything the run did not pull. + +The gate reads this enumeration, so it covers exactly the refs pinned by digest in the three storage shapes. An image a vendored chart renders from its own defaults, or one an operator launches, is outside it. `verify-multiarch.sh --refs-file` checks a plain list of refs instead, tag-only ones resolved by tag, and the rc e2e feeds it `image-refs.txt` from `hack/collect-images.sh`: every image the sandbox nodes pulled, by the digest each pull resolved to. Neither covers a package that e2e never installs and the tree does not pin by digest. Two rows do not source the shared library, for opposite reasons. `hack/overlay-main-images.sh` reads references and walks the tree itself, so it is a real exception to the invariant above: a file newly declared in `IMAGE_REF_EXTRA_FILES` does not automatically reach it. Its line classifier also has to know the bare-reference shape by itself: a `*.tag` file holds one reference with no YAML key around it, and until a build stamps it there is no `@sha256:` either, so a changed line there is recognised by shape rather than by key, scoped to `*.tag` because only there is a whole line known to be a reference and nothing else. `hack/promote-rewrite-tags.sh` carries a second match branch for that same shape and for the same reason. `hack/promote-packages-artifact.sh` is not a consumer of references at all — it hands the whole packages tree to `flux push artifact` and touches exactly one reference, the installer's own `platformSourceUrl`/`platformSourceRef` pair, by key with `yq`. Every shape travels inside the artifact because every file does, so there is nothing there for the enumeration to widen and no gap for a newly declared file to fall into. @@ -65,17 +73,17 @@ Two rows do not source the shared library, for opposite reasons. `hack/overlay-m ## Known gaps -These are real, currently unfixed, and predate the shared enumeration. They are recorded here so nobody rediscovers them as surprises. +These predate the shared enumeration. Each entry says whether the tree works around it today; they are recorded here so nobody rediscovers them as surprises. -**The nightly host rewrite cannot reach a host split across two keys.** The primary pass is a literal `/` substring replace, so it only rewrites a reference whose host sits contiguously in front of the repository. Two layouts defeat it, and only one is now handled. +**The nightly host rewrite cannot reach a host split across two keys.** The primary pass is a literal `/` substring replace, so it only rewrites a reference whose host sits contiguously in front of the repository. Two layouts in the tree defeated it; one is handled by a second expression and the other was removed from the tree. `kubeovn` puts the whole host in `global.registry.address` with the bare repository in a sibling key, so there is no trailing slash to match. This one **is** rewritten now, by a second, end-of-line-anchored expression that fires only when the source registry is the complete scalar value — a contiguous `/@` ref continues past the host, so the two expressions can never both fire on one reference. It had to be fixed when kubeovn's image build moved into this repository: until then the image was built and pushed to the public registry by cozystack/kubeovn-chart, the baked ref kept the committed public-registry host, and the ownership filter skipped it. The moment a CI build stamps the build-registry host into that key, the image is mirrored but the host is not rewritten, and the published tree points at the private build registry. Covered by `hack/nightly-mirror_test.bats`. -`keycloak-operator` remains unfixed. It splits at a different boundary — `registry: iad.ocir.io` beside `repository: idyksih5sir9/cozystack/` — so neither key holds the source registry as a whole and no anchored replace can reach it; rewriting it needs a structure-aware pass that knows how the destination host splits. The gap stays dormant because no CI path rebuilds the package (#3416), and turns live the moment one does. +`keycloak-operator` split at a different boundary: `registry: ghcr.io` beside `repository: cozystack/cozystack/`, with an `image:` target that stamped only `tag`. A CI build would have rendered the committed public host with a digest that exists only in the build registry, and stamping the build host into `registry` instead would spread the source registry across two keys (`iad.ocir.io` and `idyksih5sir9/cozystack/`), where no anchored replace can reach it. Rather than a structure-aware rewrite pass, the package now sets `registry: ""` and keeps the whole host in `repository`, which renders the same image string because the upstream chart joins the two keys, and its `image:` target stamps `repository` the same way. The rewrite still cannot reach a host split at that boundary, so a package must not stamp one: keep the host inside `repository`, or make it the complete value of its key as kubeovn does. Covered by `hack/nightly-mirror_test.bats`. Collection understands both shapes — the host is rejoined, so a split-key ref carrying the source-registry host is still selected and mirrored. This is a defect in the host dimension; the version dimension the promote rewrite handles is unaffected, because the version always lives in a `tag` key regardless of where the host is. -**A reference inside a gzip is invisible.** `capi-providers-cpprovider` stamps its kamaji reference into `files/control-plane-components.yaml` and into the `files/components.gz` built from it, and the chart ships the `.gz`. Nothing enumerates either: declaring only the readable copy would rewrite what nothing consumes and diverge it from what does. Note the promote postcondition cannot catch this class at all — `grep -rIl` skips binary files — so it fails silently rather than loudly. No tag rewrite is owed (kamaji is component-versioned) and the image is still mirrored and retagged via its `.tag` file, so the residual is that a nightly's kamaji ConfigMap keeps the build-registry host. The fix is decompress, rewrite, recompress with `gzip -n` for reproducibility. +**A reference inside a gzip is invisible.** `capi-providers-cpprovider` stamps its kamaji reference into `files/control-plane-components.yaml` and into the `files/components.gz` built from it, and the chart ships the `.gz`. Nothing enumerates either: declaring only the readable copy would rewrite what nothing consumes and diverge it from what does. Note the promote postcondition cannot catch this class at all — `grep -rIl` skips binary files — so it fails silently rather than loudly. No tag rewrite is owed (kamaji is component-versioned) and the image is still mirrored and retagged via its `.tag` file, so the residual is that a nightly's kamaji ConfigMap keeps the build-registry host. The fix is decompress, rewrite, recompress with `gzip -n` for reproducibility. `hack/stitch-multiarch.sh` does exactly that for its digest rewrite: it declares the `.gz` together with its plain source in its own `GZIP_COPIES`, rewrites both, and looks inside every `.gz` in the tree both before rewriting, to skip an image pinned in an undeclared one, and after, in its leftover-digest check. The rewritten `.gz` is byte-identical to what the package's `image` target writes only when both use GNU gzip, as CI does; Apple's gzip compresses to different bytes, so a stitch run on macOS rewrites the right content into a different file. The other consumers still leave both copies alone. **`charts/` is excluded, and is almost always right.** Vendored upstream chart values are regenerated by `make update` and their images are neither built nor pushed here. The one exception is `packages/system/cozystack-scheduler/charts/cozystack-scheduler/values.yaml`, which pins a first-party-namespace image. Excluding it is still correct — it is built by a separate repository, component-versioned, and already published to the public registry, so no retag or mirror is owed — but "everything under `charts/` is third-party" is not literally true. diff --git a/docs/agents/overview.md b/docs/agents/overview.md index db8b0081a..c1bec109d 100644 --- a/docs/agents/overview.md +++ b/docs/agents/overview.md @@ -16,7 +16,7 @@ The platform exposes infrastructure services via the Kubernetes API with ready-m ## Code Layout -``` +```text . ├── packages/ # Main directory for cozystack packages │ ├── core/ # Core platform logic charts (installer, platform) @@ -50,7 +50,7 @@ The platform exposes infrastructure services via the Kubernetes API with ready-m Every package is a Helm chart following the umbrella chart pattern: -``` +```text packages/// ├── Chart.yaml # Chart definition and parameter docs ├── Makefile # Development workflow targets @@ -69,7 +69,7 @@ Root targets (run from the repo root): ```bash make build # Build all Docker images (needs: docker, skopeo, jq, gh, helm, yq, GNU tar/sed/awk) -make unit-tests # Run the unit tests (Helm, BATS, Go, etc.); does not reach ./internal/... +make unit-tests # Run unit tests (requires bats-core >= 1.5; GNU parallel is optional) make test-controllers # Run the Go tests under ./internal/... (controllers, contract tests) make generate # Code generation (hack/update-codegen.sh) — CRDs, DeepCopy, clients, RBAC make manifests # Generate CRD manifests and operator YAML variants @@ -93,7 +93,10 @@ Build environment variables: - `REGISTRY` — Docker registry (default `ghcr.io/cozystack/cozystack`). - `PUSH=1` / `LOAD=0` — control buildx push/load behaviour. -- `LOAD=1 PUSH=0` — load images locally instead of pushing. +- `LOAD=1 PUSH=0` — load images locally instead of pushing. Builds for the host architecture only, because the classic docker image store cannot load a multi-platform index. +- `PLATFORM` — the buildx platforms. Defaults to `linux/amd64,linux/arm64` for anything but `LOAD=1`, so a push from either architecture publishes an index both can run. Needs a `docker-container` builder (`BUILDER`) or a docker daemon on the containerd image store, with QEMU registered for the non-native half. Compiling builder stages run natively on `$BUILDPLATFORM` and cross-compile for the target, but every `RUN` step of a stage that runs on the target platform (package installs, `setcap`, install scripts, patch steps) still runs emulated. `packages/core/testing` pins `linux/amd64`, because it carries an x86 KVM sandbox. `packages/core/talos` builds the Talos installer and release assets for the arches in `PLATFORM` with the upstream imager, which needs no QEMU for either; its matchbox image carries the amd64 and arm64 kernel and initramfs whatever `PLATFORM` says, because it network-boots machines of either arch. +- `PUSHED_TAGS_LOG` — a file the `image-tags` macro appends every pushed `:` to, one per line. Unset by default; the release build sets it so `hack/stitch-multiarch.sh` can move every tag it pushed, versioned ones included, onto the multi-arch index. The append happens at recipe expansion, so `make -n` writes it too. +- `CACHE_TAG` — the tag of the mode=max build cache each image reads (and writes under `WRITE_CACHE=1`). Defaults to `buildcache`. Apart from the Talos installer and matchbox in the release job, CI builds one architecture per job, and builds arm64 images only for pre-release tags and in a nightly build of main: the images are built again on native arm64 runners under `-arm64` with `CACHE_TAG=buildcache-arm64`, which only the nightly writes. The talos and testing packages get no arm64 leg: the release job builds the Talos installer and matchbox for both arches itself, and testing is amd64 only. For a pre-release, `hack/stitch-multiarch.sh` then joins each pair into one index, `hack/verify-multiarch.sh` fails the rc on any pinned image that is not an amd64+arm64 index, and the packages artifact is republished pinned on the index digests; see `docs/release/ci-pipeline.md`. The stitch skips any image whose digest is also pinned in a file it does not rewrite, which then fails that gate; the kamaji control-plane provider's gzipped manifest is the one such copy it does rewrite (see `docs/agents/image-refs.md`). ### Values schema generation @@ -103,19 +106,58 @@ A chart also declares the limits on its own resource name there, with `## @name ## Testing -- **Helm unit tests:** `make helm-unit-tests` (runs `hack/helm-unit-tests.sh` over every package that defines a `test` target). A `test` target is expected to run helm-unittest: the sweep fails a package whose run reports no suite, because exiting 0 having asserted nothing is indistinguishable from passing. A target that drives something else belongs under another name, as `packages/core/testing` already does with its sandbox flow. `make unit-tests` runs the unit suite — Helm, BATS, Go, and the preset/readiness checks. It does not reach the controller and contract tests under `./internal/...`, which have their own target, `make test-controllers`, so covering both locally means running that target as well; CI runs them as two steps of one job. +- **Helm and BATS unit tests:** `make helm-unit-tests` runs `hack/helm-unit-tests.sh` over every package that defines a `test` target. A `test` target is expected to run helm-unittest: the sweep fails a package whose run reports no suite, because exiting 0 having asserted nothing is indistinguishable from passing. A target that drives something else belongs under another name, as `packages/core/testing` already does with its sandbox flow. `make bats-unit-tests` requires bats-core 1.5 or newer; GNU parallel is optional and the target runs serially without it. Run the complete local BATS and POSIX-compatibility pass with `pre-commit run bats-unit-tests --hook-stage manual --all-files`; pull-request CI runs both lanes for code changes and the BATS contracts for docs-only changes. On a host whose `/bin/sh` differs from CI, `make BATS_POSIX_SHELL=dash bats-posix-compat-tests` selects the same interpreter explicitly. `make unit-tests` runs the full unit suite — Helm, BATS, the targeted POSIX-shell compatibility pass, Go, and the preset/readiness checks. It does not include the controller tests under `./internal/...`; run `make test-controllers` as well. CI invokes both targets together. The backport-batch tests are not part of it: run `make test-backport-batch` after changing anything listed in `cmd/backport-batch/test-inputs.txt`, which is also what CI keys them on. - **E2E tests:** Kyverno Chainsaw suites in `hack/e2e-chainsaw/` (one directory per app), run with `chainsaw test`. Cluster bootstrap (`hack/e2e-install-cozystack.bats`) and the OpenAPI checks (`hack/e2e-test-openapi.bats`) remain BATS. Conventions for writing and stabilising them — and the CI that runs them — live in [`e2e-testing.md`](./e2e-testing.md). - **Go tests:** standard `go test`, with Ginkgo/Gomega for controllers. +### Test first, failure path first + +These rules apply to changes with testable behavior. Documentation-only edits and unmodified upstream updates need the relevant checks, not an artificial failing test. First-party adaptations made during a dependency bump remain covered by these rules. + +1. Write the test before changing the implementation and watch it fail for the intended reason, not on a typo or a missing fixture. Then make it green, then refactor under it. +2. Cover relevant failure paths before the happy path: empty or null values, invalid input, a number where a string is expected, a missing resource, a timeout or an API error. Assert the resulting message, exit status and post-failure state required by the operation's contract. +3. Fix regressions in the implementation. Do not skip, weaken or delete a test, or silence a linter, merely to get a green run. When the intended contract changes, update or replace the obsolete assertions and retain coverage of applicable failure cases. +4. A stub needs a failing test for the intended behavior during development. Finish that behavior and make the test pass before merge; do not make the test accept an unintended not-implemented result just to get green CI. +5. A bug found along the way that is out of the PR's scope gets an issue and a test pinning the current broken behaviour, marked `FIXME(#N)`. The PR that fixes the bug flips the test to pin the fixed behaviour. + +Do not negate a BATS assertion with `!`: it can silently pass. Bats catches a failing negation only when it is the last command in the test body; `hack/cozytest.sh` appends a successful return and misses it there too. See [§11 of `e2e-testing.md`](./e2e-testing.md#11-never-negate-a-bats-assertion-with-). + +### Linters + +Fix every linter finding before pushing, the cosmetic ones included. When a rule genuinely conflicts with the project, change the linter configuration and state the reason there, instead of suppressing the finding inline. + +Markdown follows these markdownlint rules: every code fence names a language (`text` when nothing else fits), table separators have spaces around the pipes (`| --- |`), and there is a blank line before and after every list and after every heading. Line length (MD013) is the exception: prose stays one line per paragraph, as [Prose Formatting](../../AGENTS.md#prose-formatting) explains. + ## Conventions ### Helm Charts + - Follow **umbrella chart** pattern for system components - Include upstream charts in `charts/` directory (vendored, not referenced) - Override configuration in root `values.yaml` - Use `values.schema.json` for input validation and dashboard UI rendering +- An unquoted numeric value (`name: 123`) reaches a template as a number: `len` on it aborts the render with `len of type float64` (`int64` for a value given with `--set`) before any `fail` message is reached, and `if not $v` treats `0` as unset. For fields validated as text that permit numeric inputs, reject missing or null values with `kindIs "invalid"`, then coerce with `printf "%v"` and check emptiness with `eq $v ""`. Coercing null first produces the non-empty string ``. +- For integer fields, keep string inputs on their lexical validation path. Validate numeric inputs for type, integrality and bounds before conversion, then format the validated integer in decimal. Generic `printf "%v"` can emit exponent notation for a float (`4200000000` becomes `4.2e+09`), so it is not integer normalization. +- For nested values, validate or normalize each parent map before reading its children; checking only the leaf cannot prevent a nil-pointer error from a missing or null parent. + +**No `lookup` that copies another object into the render.** A `lookup` reads cluster state at render time, and nothing re-renders the HelmRelease when that state changes, so whatever it copied into the output (a bucket name, an endpoint, a CA, a list of StorageClasses) stays stale until something unrelated upgrades the release. Lookups of this kind already in the charts have caused failures, and several have since been moved to values, so they are not precedent: do not add one of this kind unless a maintainer has authorized that specific one. + +A `lookup` is fine when a repeated render gives the same output and carries nothing from another object into it: checking that an object exists, keeping a generated Secret's value, keeping an immutable field of the chart's own live object, or a guard that `fail`s on an unsafe change. Keep its empty branch rendering, because offline `helm template` and helm-unittest without a `kubernetesProvider` mock see only that branch; test the other branch with such a mock. + +To use a fact about the cluster instead, read it from values: `_cluster` and `_namespace` in the `cozystack-values` Secret, or `valuesFrom` on a specific Secret, whose content change is a values change and so upgrades the release. Ask whether an API is served with `.Capabilities.APIVersions.Has`, since a `lookup` on an unserved group aborts the whole render. Otherwise check at run time in a hook or Job, or let a controller own the object. + +### Container images + +For a new container image built from source maintained in this repository, name the build definition `Containerfile` and pass it to `docker buildx build` with `--file` in the package `Makefile`. Keep existing `Dockerfile`s and vendored build definitions unchanged. + +### Examples and fixtures + +Illustrative addresses and names in docs, examples and test fixtures come from the reserved documentation ranges, never from a routable value that merely looks realistic: IPv4 from RFC 5737 (`192.0.2.0/24`, `198.51.100.0/24`, `203.0.113.0/24`), IPv6 from RFC 3849 (`2001:db8::/32`), domains from RFC 2606 and RFC 6761 (`example.com`, `.example`, `.test`, `.invalid`), ASNs from RFC 5398 (`64496`–`64511`, `65536`–`65551`), MAC addresses from RFC 7042 (`00:00:5E:00:53:00`–`00:00:5E:00:53:FF`). Where no reserved range exists, use an obviously synthetic placeholder such as ``. + +When a test depends on a protocol-defined address's behavior, use that value, such as `127.0.0.1` or `localhost` for a local test server. Keep network tests isolated; this exception does not permit arbitrary live endpoints. ### Go Code + - Follow standard **Go conventions** and idioms - Use **controller-runtime** patterns for Kubernetes controllers - Prefer **kubebuilder** for API definitions and controllers @@ -133,13 +175,25 @@ Set `upgradeCRDs: CreateReplace` for operators whose upstream regularly adds new Do **not** set `CreateReplace` blindly: it overwrites every CRD in `crds/` and can cause silent data loss if upstream drops a field from a CRD that has live objects. Only enable it for operators whose schema evolution is additive-only. When in doubt, leave it unset and apply new CRDs manually. -### Documentation +### Documentation — where a new document goes -Documentation is organized as follows: -- `docs/` - General documentation -- `docs/agents/` - Instructions for AI agents -- `docs/changelogs/` - Release changelogs -- Main website: https://github.com/cozystack/website +Product documentation lives in [`cozystack/website`](https://github.com/cozystack/website), not here. This repository holds only documentation that something in the repository references by path, or that describes the repository's own machinery. Pick the destination before writing, because moving a document later means chasing every `@param`, template comment and test comment that points at it. + +| Destination | What belongs there | +| --- | --- | +| `packages///README.md` | Anything scoped to a single package. Prose goes **above** `## Parameters`; that section is `cozyvalues-gen` output and is never hand-edited. The website's `make update-apps` / `update-vms` / `update-networking` / `update-k8s` / `update-services` targets append the whole README onto a published page, but only for the packages named in the `APPS`, `VMS`, `NETWORKING`, `K8S` and `SERVICES` lists of the website `Makefile`, and only from `packages/apps/` and `packages/extra/`: nothing under `packages/system/` is ever imported, and neither is a package that is not on those lists. The sync runs when a release is promoted or tagged, or by hand in the website repository, not when a pull request merges here. Use this route only for a package that is on the lists; for any other the prose reaches no reader, so put it on the website instead. | +| `cozystack/website`, under `content/en/docs/` | Operator- and tenant-facing content that spans packages or is task-shaped: guides, how-tos, troubleshooting runbooks, reference tables. Which version directory a page goes into is set by the website's own [`CONTRIBUTING.md`](https://github.com/cozystack/website/blob/main/CONTRIBUTING.md); follow that file rather than a copy of its rules here. | +| `docs/` | Documentation that a chart template, migration, script or workflow references by repo-relative path, plus this repository's own process docs (`docs/agents/`, `docs/changelogs/`, `docs/release.md` and the pages under `docs/release/`). | +| `api///DESIGN.md`, `pkg/apis//DESIGN.md` | Design of an API group, beside the types it describes. | +| [`cozystack/community`](https://github.com/cozystack/community) | Design proposals and RFCs. Not this repository. | + +When a document could go in either `docs/` or the website, the test is whether a non-documentation file has to link to it by path. `docs/operations/seaweedfs-431-rename-recovery.md` stays because `packages/*/seaweedfs/templates/_naming.tpl` and a platform migration point at it. A guide referenced only from a `values.yaml` `@param` does not qualify — put it on the website and link the URL. + +Documenting a feature's current limitations is useful and belongs with the feature. Documenting the *development process* around it does not: no "What is NOT in Phase N", no "out of scope for this PR", no "this PR" phrasing, no action plans or review negotiation. A merged document describes what the code does now, and states a limitation as a limitation rather than as a roadmap position. Scope, phasing and follow-ups belong in the pull request description or an issue. + +An app's README and the field descriptions in its `values.yaml` describe what the app does now, for the person using it: no history ("moves from", "previously", "used to", rollout phase names) and no account of how another chart behaved before. A change users must act on is announced by a `!` in the pull request title and described on the website's per-version upgrade page (`content/en/docs/next/operations/cluster/upgrade-to-vX.Y.md`), so an app README carries no history or breaking-changes section. A description says what the field does, what it accepts and what it refuses, not what it replaced, and does not tell the reader to keep it in sync with another chart; when two charts have to agree, a test says so. A change that touches a README or a description fixes what is wrong in that place while it is there. + +A document that names an unmerged pull request or an unreleased dependency needs a tracking issue, because nothing re-checks that claim later and it silently becomes false once the thing ships. ### Domain references for specific tasks @@ -151,6 +205,7 @@ Before working on these areas, read the relevant doc first: ## Things Agents Should Not Do ### Never Edit These + - Do not modify files in `/vendor/` (Go dependencies) - Do not edit generated files: `zz_generated.*.go` - Do not change `go.mod`/`go.sum` manually (use `go get`) @@ -158,14 +213,16 @@ Before working on these areas, read the relevant doc first: - Do not modify image digests in `values.yaml` (generated by build) ### Version Control + - Do not commit built artifacts from `_out` - Do not commit test artifacts or temporary files ### Git Operations + - Do not force push to main/master - Do not update git config - Do not perform destructive operations without explicit request ### Core Components -- Do not modify `packages/core/platform/` without understanding migration impact +- Do not modify `packages/core/platform/` without understanding migration impact diff --git a/docs/agents/releasing.md b/docs/agents/releasing.md index d37e3e952..547e89c04 100644 --- a/docs/agents/releasing.md +++ b/docs/agents/releasing.md @@ -12,7 +12,7 @@ Follow these instructions when the user asks to: ## Instructions -For detailed release process instructions, follow the steps documented in: +For detailed release process instructions, follow the steps documented in the pages under `docs/release/`, starting from their index: **[docs/release.md](../release.md)** @@ -25,5 +25,7 @@ The release process is promotion-based — a stable release is a renamed release 4. Finalize on merge (CI cuts the write-once tag, publishes the release from the merged changelog, and retags the rc images to stable by digest). 5. Merging the parked website docs PR once the release is published. -All detailed steps, workflows, and failure modes are documented in `docs/release.md`. +All detailed steps, workflows, and failure modes are documented in the pages under `docs/release/`, one per topic, and `docs/release.md` links each of them. + +What a patch release carries is decided by the rules in [`docs/release/backports.md`](../release/backports.md), not per pull request: fixes reach the release lines through the backport batch, and nobody labels or opens a backport. For a patch release, or any rc cut from a `release-X.Y` branch, check the branch before tagging: build the batch tool with `go build ./cmd/backport-batch`, then run `./backport-batch check --line release-X.Y --cut`. It exits 1 while a pull request the rules take is not on the line, including one that is only on the open batch pull request, which the cut would not carry, and prints the URLs; what the batch deferred prints as warnings. See [`cmd/backport-batch/README.md`](../../cmd/backport-batch/README.md) and [Cherry-pick triage before a patch](../release/backport-mechanics.md#cherry-pick-triage-before-a-patch). Do not report a branch as ready to cut on the strength of a list of merged pull requests or of the batch pull request's description — they list what merged or was picked, not what arrived. diff --git a/docs/changelogs/v1.6.0.md b/docs/changelogs/v1.6.0.md index b9141a1d3..8b26f5426 100644 --- a/docs/changelogs/v1.6.0.md +++ b/docs/changelogs/v1.6.0.md @@ -186,7 +186,7 @@ Two symmetric Phase 1 features let a tenant opt an individual workload into the **Grafana.** Each `Monitoring` CR gains the same `spec.oidc.mode` selector. `System` wires a per-instance confidential Keycloak client with audience binding; authorization is app-side, with `spec.oidc.users: [{email, role: Admin|Editor|Viewer}]` reconciled into Grafana's Main Org. by a chart-owned post-install/post-upgrade Job that pre-provisions users, adds them to the org, PATCHes their role and prunes stale members. `CustomConfig` accepts a tenant-supplied `[auth.generic_oauth]` payload, either inline as a map (the chart merges the two contract-critical settings on top) or as a Secret with an `auth.ini` key — in which case `spec.oidc.users` is unsupported and the chart fails the render on that combination rather than silently ignoring it. The `admin_user`/`admin_password` Secret remains a documented break-glass path in every mode ([**@IvanHunters**](https://github.com/IvanHunters) in #3176). -Both are documented in-repo at [`docs/oidc-tenant.md`](../oidc-tenant.md) and [`docs/oidc-grafana.md`](../oidc-grafana.md). +Both are documented at [OIDC authentication for kubectl](https://cozystack.io/docs/v1.6/kubernetes/oidc-authentication/) and [OIDC authentication for Grafana](https://cozystack.io/docs/v1.6/operations/services/monitoring/oidc-authentication/). ### SecurityGroup: Tenant-Managed Network Policy @@ -582,7 +582,7 @@ A sweep of platform components that previously ran without resource requests or * **[docs] Route bugs, features, and proposals to the right repository**: Issue templates and contribution docs now direct reporters to the correct Cozystack repository ([**@myasnikovdaniil**](https://github.com/myasnikovdaniil) in #2854). -* **[vm-instance] Document attaching a VM to an external VLAN**: New `docs/vm-external-vlan.md` covering the Linux-bridge and bridge-type `NetworkAttachmentDefinition` path ([**@lexfrei**](https://github.com/lexfrei) in #3196). +* **[vm-instance] Document attaching a VM to an external VLAN**: New guide on [attaching a VM to an external VLAN](https://cozystack.io/docs/v1.6/networking/vm-external-vlan/), covering the Linux-bridge and bridge-type `NetworkAttachmentDefinition` path ([**@lexfrei**](https://github.com/lexfrei) in #3196). * **[harbor] Fix the SeaweedFS discovery key described as an annotation**: It is the `namespace.cozystack.io/seaweedfs` namespace **label** ([**@lexfrei**](https://github.com/lexfrei) in #3293). diff --git a/docs/changelogs/v1.6.4.md b/docs/changelogs/v1.6.4.md new file mode 100644 index 000000000..2858cd80a --- /dev/null +++ b/docs/changelogs/v1.6.4.md @@ -0,0 +1,154 @@ + + +# v1.6.4 (2026-09-28) + +A patch release with backported fixes for VM live migration during eviction and scheduling, Kafka release deletion, KubeVirt-related billing labels, ingress client-IP trust, PostgreSQL-adjacent LINSTOR/CDI/ZFS reliability, MongoDB and RabbitMQ defaults, and a batch of e2e hardening, plus a new `talm` documentation site, an NVIDIA vGPU restore role for `ansible-cozystack`, and a large Marketplace documentation section on the website. + +## Fixes + +* **fix(cluster-api): backport live migration before host eviction**: `cluster-api-provider-kubevirt` now attempts live migration before falling back to drain and delete when a guest node is evicted, uses the guest node's own name for the drain fallback instead of the wrong identifier, and uncordons a recreated guest — so an eviction no longer forces an unnecessary VM restart when a live migration would have sufficed ([**@yankawai**](https://github.com/yankawai) in #4291, backport #4474). + +* **fix(kubeovn): retry VM migration setup after scheduling**: Retries the VM migration network setup when the target Pod or source/target scheduling information is not yet available, instead of failing outright, and folds the Kube-OVN image into the regular in-tree build matrix — so a migration that starts before Kube-OVN has finished scheduling both endpoints no longer aborts ([**@yankawai**](https://github.com/yankawai) in #4253, backport #4328). + +* **feat(kubevirt): expose migration configuration through platform values**: Cluster-wide KubeVirt migration settings (bandwidth per migration, parallel migrations per cluster, parallel outbound migrations per node) can now be set through the platform value `kubevirt.migrations` instead of hand-patching the generated `Package`, which the platform undoes on every render; leaving the value unset preserves existing defaults ([**@yankawai**](https://github.com/yankawai) in #4254, backport #4402). + +* **fix(linstor): add opt-in graceful satellite shutdown on Talos**: Adds an opt-in Talos satellite `preStop` hook that releases unused Secondary DRBD resources, ZFS zvols included, before the satellite stops, without forcing, demoting or calling the Kubernetes API. Enable it with `talos.gracefulShutdown.enabled` for sequential node maintenance; existing installations keep today's behavior by default, and the hook also runs on ordinary pod restarts so it should be enabled only where node restarts are serialized ([**@yankawai**](https://github.com/yankawai) in #4292, backport #4401). + +* **fix(workloadmonitor): populate VM instance-profile label from the KubeVirt preference annotation**: `WorkloadMonitor` read a `kubevirt.io/cluster-instanceprofile-name` annotation that KubeVirt never writes; the real annotation is `kubevirt.io/cluster-preference-name`. Reading the correct key means a VM's instance profile — a Windows guest, for example — now reaches the billing metric pipeline instead of being silently dropped ([**@IvanHunters**](https://github.com/IvanHunters) in #4448, backport #4454). + +* **fix(opensearch-operator): name the component reconciler a stall sits in**: The OpenSearch cluster controller now logs a watchdog report naming which of its nine component reconcilers has been running for over a minute, and keeps reporting on an interval while it stays stuck, instead of leaving a stalled reconcile with no trace in the operator log at all ([**@IvanHunters**](https://github.com/IvanHunters) in #4333, backport #4377). + +* **fix(manifestutil): report one message when the CRD wait is cancelled**: A CRD wait cut short by a cancelled context now always reports one error naming the CRD it was waiting on, instead of sometimes including the name and sometimes not, depending on which of two exit paths the scheduler happened to pick ([**@lexfrei**](https://github.com/lexfrei) in #3742, backport #4475). + +* **fix(kafka): delete release topics before the topic operator is removed**: Deletes release-owned `KafkaTopic`s with a pre-delete hook before the Strimzi topic operator is removed, and fixes the hook's own `--request-timeout` flag, which made it skip in-cluster credentials and fail every deletion outright. Together these mean a Kafka release with the `strimzi.io/topic-operator` finalizer no longer leaves stray topics behind on reinstall, and release deletion itself no longer wedges ([**@yankawai**](https://github.com/yankawai), [**@IvanHunters**](https://github.com/IvanHunters) in #3938, #4280, backport #4456). + +* **fix(ingress): trust CF-Connecting-IP only from Cloudflare ranges**: With `cloudflareProxy` enabled, `CF-Connecting-IP` is now trusted only from Cloudflare's published address ranges. Previously the ranges were passed under a key `ingress-nginx` ignores, so any client that reached the load balancer directly could set the header itself and bypass the ingress IP `whitelist` ([**@lexfrei**](https://github.com/lexfrei) in #4444, backport #4445). + +* **fix(apps): let the cleanup hooks watch the objects they delete**: The Harbor, ClickHouse, MariaDB and Qdrant cleanup hooks now wait for the objects they delete to actually disappear, with the wait bounded so a stuck claim cannot hang the whole uninstall ([**@yankawai**](https://github.com/yankawai) in #4135, backport #4369). + +* **fix(registry): preserve write options in aggregated storage**: The application, tenant-secret and security-group APIs now preserve Kubernetes write options (dry-run, field manager, field validation, delete propagation, grace periods, preconditions) when delegating to controller-runtime, instead of silently dropping them; a rejected write also keeps its machine-readable status, so a quota or admission failure now answers 403/409 with a reason instead of a generic 500 ([**@yankawai**](https://github.com/yankawai) in #3937, backport #4370). + +* **fix(dashboard): let dashboard users read backup CRD schemas**: Grants dashboard users read access to the backup CRD schemas, fixing the backup create/edit forms that previously returned 403 ([**@androndo**](https://github.com/androndo) in #4236, backport #4307). + +* **fix(backups): give the barman-cloud sidecar its own resources**: The barman-cloud sidecar previously had no resource requests or limits, so in tenant namespaces it inherited a 128Mi `LimitRange` default and was OOMKilled during backups even while the surrounding `ObjectStore` and `Cluster` stayed healthy. It now requests 100m/256Mi and is capped at 1Gi on both the chart and the platform's Go rendering path ([**@yankawai**](https://github.com/yankawai) in #4220, backport #4336). + +* **fix(linstor): reconnect only the stalled peer in the satellite plunger**: The satellite plunger disconnected a stalled DRBD peer but then tried to reconnect every peer of the resource at once, which failed with "Device has a net-config" for peers that were never disconnected and left the stalled one permanently unreconnected. It now reconnects only the peer pair it disconnected, so a stalled resync actually recovers ([**@yankawai**](https://github.com/yankawai) in #4184, backport #4319). + +* **fix(foundationdb): let tenant roles read the connection ConfigMap**: Tenants previously had no way to obtain their FoundationDB connection string: the cluster file lives in a ConfigMap tenant subjects could not read and the dashboard resource map did not expose. The ConfigMap is now in the dashboard resource map with a Role/RoleBinding granting the tenant `use` access level get/list/watch on it ([**@yankawai**](https://github.com/yankawai) in #4148, backport #4315). + +* **fix(opensearch): remove the data PVCs when the application is deleted**: Adds a post-delete hook that reclaims an OpenSearch application's data PVCs when it is removed, instead of leaving them orphaned ([**@yankawai**](https://github.com/yankawai) in #4136, backport #4368). + +* **fix(nats): merge config.merge.accounts with the generated accounts map**: `config.merge.accounts` is now merged into the generated NATS accounts map instead of being rendered as a second, conflicting copy of the same key ([**@yankawai**](https://github.com/yankawai) in #4134, backport #4321). + +* **fix(clickhouse): keep the Keeper name inside the StatefulSet volume-name limit**: Shortens the generated Keeper name for application names longer than 15 characters, fixing the Keeper `StatefulSet` failing to create for those names ([**@yankawai**](https://github.com/yankawai) in #4133, backport #4314). + +* **fix(linstor): wait for temporary probe devices**: Backports a LINSTOR upstream fix that waits for a ZFS probe device to appear before reading its I/O properties, instead of racing udev; without the wait, a pool could be left with incorrect block sizes and failed replica placement on 4K pools ([**@yankawai**](https://github.com/yankawai) in #4100, backport #4335). + +* **fix(mongodb): fill the dashboard credentials on a first install**: The dashboard credentials Secret is now filled with the database password and connection URI on first install; previously it shipped empty until someone ran `helm upgrade` by hand, because the lookup it relied on could only see users the Percona operator had not yet created ([**@yankawai**](https://github.com/yankawai) in #4014, backport #4330). + +* **fix(rabbitmq): right-size the default resources preset to s1.nano**: Raises the default `resourcesPreset` from `t1.nano` (128Mi) to `s1.nano` (250m CPU, 512Mi), because a default-sized RabbitMQ 4.2 broker was OOMKilled on `t1.nano` and never became Ready. Brokers with no stored preset are restarted on upgrade and gain a larger guaranteed memory reservation — check node headroom, and tenants near a `resourceQuotas` memory ceiling, before upgrading; brokers with an explicit `resourcesPreset` already set keep their existing size ([**@yankawai**](https://github.com/yankawai) in #3936, backport #4393). + +* **fix(kafka): make topics[].config optional**: Kafka topics can now omit the optional Strimzi config map entirely, instead of the chart requiring one even when there is nothing to set ([**@yankawai**](https://github.com/yankawai) in #3935, backport #4334). + +* **fix(kubernetes): pin KubeVirt CSI sidecars to SIG Storage releases**: Pins the KubeVirt CSI sidecars to versioned SIG Storage images, fixing sidecars that previously would not run on pre-x86-64-v3 CPUs ([**@yankawai**](https://github.com/yankawai) in #3934, backport #4313). + +* **fix(cdi): update CDI to v1.66.1**: Updates CDI to v1.66.1, fixing HTTP imports that block volumes on 4Kn devices (DRBD/LINSTOR) via a repaired `qemu-img`, and a `resourceVersion` update storm on prime PVCs during `WaitForFirstConsumer` imports ([**@lexfrei**](https://github.com/lexfrei) in #3920, backport #4156). + +* **feat(etcd-operator): bump to v0.5.5 and vendor EtcdDefragPolicy CRDs**: Bumps `etcd-operator` to v0.5.5, adding the `EtcdDefrag` and `EtcdDefragPolicy` APIs for on-demand and scheduled etcd defragmentation ([**@androndo**](https://github.com/androndo) in #3968, backport #4151). + +## Development, Testing, and CI/CD + +* **test(e2e): run the merge-gating lanes on Talos containers**: Moves the merge-gating E2E lanes onto Talos containers, fixing tenant node-join failures that were happening in 8 of the last 11 runs because tenant workers sat one virtualization level too deep on the shared runners and had their CSR signed after the readiness window closed ([**@myasnikovdaniil**](https://github.com/myasnikovdaniil) in #4020, backport #4437). + +* **chore(e2e): ignore the artifacts the sandbox bringup writes to the repo root**: Adds `.gitignore` entries for the Talos secrets bundle, rendered machine configs, kubeconfigs, boot image and per-VM directories a local e2e sandbox bringup writes to the repo root, closing a path where a broad `git add` could have staged cluster private keys ([**@lexfrei**](https://github.com/lexfrei) in #3891, backport #4438). + +* **fix(e2e): budget tenant scheduling separately from workload readiness**: Waits for a tenant node to actually accept a Pod, on its own budget, before creating the workload used by the kubernetes suites, instead of sharing one 300s deadline between node scheduling and workload readiness — fixing intermittent timeouts where scheduling alone consumed most of the shared window ([**@lexfrei**](https://github.com/lexfrei) in #3579, backport #4435). + +* **fix(e2e): budget each linstor wait separately in post-install-prep**: Gives each of the two LINSTOR waits in the post-install-prep script its own deadline, started when the previous one finishes, instead of sharing a single 15-minute window anchored at the script's start — fixing failures where a slow HelmRelease left the following Deployment wait too little time ([**@lexfrei**](https://github.com/lexfrei) in #3715, backport #4434). + +* **fix(reloader): add startupProbe to survive slow first start under load**: Adds a startup probe to `cozy-reloader` so a slow first start is no longer killed by the liveness probe and left crash-looping, which also unblocks the LINSTOR stack that depends on it starting cleanly ([**@lexfrei**](https://github.com/lexfrei) in #3470, backport #4433). + +* **fix(e2e): stop the sandbox cluster CIDR overlapping the pod range**: Moves the e2e sandbox's Kubernetes cluster CIDR off the range Kube-OVN uses for pod IPAM, fixing intermittent Cilium/Kube-OVN IP collisions that either refused a pod outright with "IP already in use" or silently broke host-to-pod traffic ([**@lexfrei**](https://github.com/lexfrei) in #3750, backport #4432). + +* **fix(e2e): disable guest fsync on ephemeral CI VM disks**: Boots e2e QEMU guests with `cache=unsafe` so ephemeral CI VM fsyncs no longer stall the management-cluster etcd, removing cross-operator leader-election flakiness that was failing a different chainsaw suite on every run ([**@kvaps**](https://github.com/kvaps) in #3455, backport #4431). + +## Documentation + +* **[website] feat(compliance): surface AI Conformance page, mark submission accepted**: Publishes the AI Conformance results page and marks the platform's submission as accepted ([**@tym83**](https://github.com/tym83) in cozystack/website#706). + +* **[website] fix(docs): refresh trunk version pins to Cozystack v1.6.3**: Updates the documentation's trunk version references to Cozystack v1.6.3 ([**@lexfrei**](https://github.com/lexfrei) in cozystack/website#618). + +* **[website] docs(platform-package): sync the publishing.\* table with the platform values**: Keeps the platform values reference's `publishing.*` table in sync with the actual platform values ([**@lexfrei**](https://github.com/lexfrei) in cozystack/website#679). + +* **[website] docs(networking): GatewayClass selection, edge TLS mode, and the Cloudflare Tunnel package**: Documents GatewayClass selection, the edge TLS certificate mode, and the Cloudflare Tunnel Gateway API package ([**@lexfrei**](https://github.com/lexfrei) in cozystack/website#655). + +* **[website] docs(platform-package): document KubeVirt migration settings**: Documents the new `kubevirt.migrations` platform value from the corresponding fix above ([**@yankawai**](https://github.com/yankawai) in cozystack/website#697). + +* **[website] fix(demo): keep the screen when the demo is reloaded**: Fixes the live console demo losing its current screen on a browser reload ([**@kvaps**](https://github.com/kvaps) in cozystack/website#701). + +* **[website] docs(platform-package): document kubevirt.disabledFeatureGates**: Documents the `kubevirt.disabledFeatureGates` platform value ([**@lexfrei**](https://github.com/lexfrei) in cozystack/website#678). + +* **[website] chore(demo): refresh the console demo from the cozystack monorepo**: Refreshes the live demo's bundled `cozystack-ui` console from the monorepo ([**@kvaps**](https://github.com/kvaps) in cozystack/website#698). + +* **[website] fix(site): point the Certified Kubernetes badge at the live landscape entry**: Fixes the Certified Kubernetes badge linking to a stale landscape entry ([**@tym83**](https://github.com/tym83) in cozystack/website#699). + +* **[website] docs(compliance): add AI Conformance page, update Kubernetes Conformance**: Adds the initial AI Conformance page and updates the Kubernetes Conformance page ([**@tym83**](https://github.com/tym83) in cozystack/website#693). + +* **[website] docs(blog): route independent-adopter replies to the project**: Redirects independent-adopter reply channels on the blog to the project instead of an individual ([**@tym83**](https://github.com/tym83) in cozystack/website#696). + +* **[website] fix(site): resolve /roadmap and move the vendor logo off a project path**: Fixes the `/roadmap` link and moves a vendor logo off a project-owned path ([**@tym83**](https://github.com/tym83) in cozystack/website#695). + +* **[website] feat(home): add a "where Cozystack fits" section**: Adds a "where Cozystack fits" section to the home page ([**@tym83**](https://github.com/tym83) in cozystack/website#694). + +* **[website] fix(site): give the live-demo band its own layout**: Gives the live-demo band on the home page its own layout instead of sharing one with unrelated content ([**@tym83**](https://github.com/tym83) in cozystack/website#692). + +* **[website] feat(site): verify the @cozystack.io Bluesky handle over HTTPS**: Serves the Bluesky handle DID at `/.well-known/atproto-did` to verify the `@cozystack.io` Bluesky handle over HTTPS ([**@kvaps**](https://github.com/kvaps) in cozystack/website#691). + +* **[website] docs(marketplace): add Application Marketplace section**: Adds a large new Application Marketplace documentation section covering the CLI reference, package taps, subscriptions, trust model, and catalog behavior ([**@lexfrei**](https://github.com/lexfrei), [**@IvanHunters**](https://github.com/IvanHunters) in cozystack/website#672). + +* **[website] fix(site): replace vendor social accounts in the footer with project channels**: Replaces vendor-owned social accounts in the site footer with the project's own channels ([**@tym83**](https://github.com/tym83) in cozystack/website#690). + +* **[website] fix(networking): correct what disabledPackages does to ouroboros**: Corrects the documented effect of `disabledPackages` on the `ouroboros` package ([**@lexfrei**](https://github.com/lexfrei) in cozystack/website#683). + +* **[website] docs(virtualization): add a VMware vSphere migration guide**: Adds a guide for migrating VMware vSphere VMs into Cozystack, including the VDDK image build ([**@kvaps**](https://github.com/kvaps) in cozystack/website#673). + +* **[website] docs(kubernetes): add OIDC authentication guide**: Adds a guide for configuring OIDC authentication on managed Kubernetes clusters ([**@IvanHunters**](https://github.com/IvanHunters) in cozystack/website#596). + +* **[website] ci(telemetry): put the monthly refresh back on a schedule**: Restores the scheduled monthly refresh of the telemetry dashboard data ([**@tym83**](https://github.com/tym83) in cozystack/website#645). + +* **[website] docs: update managed apps reference for v1.6.3**: Refreshes the managed applications reference for the v1.6.3 release ([**@app/cozystack-ci**](https://github.com/apps/cozystack-ci) in cozystack/website#681). + +* **[talm] docs: publish the manual as a documentation site**: Publishes `talm`'s manual as a documentation site at talm.cozystack.io, with a CLI reference generated from the Cobra command tree ([**@lexfrei**](https://github.com/lexfrei) in cozystack/talm#235). + +* **[talm] ci: unbreak the lint job under Go 1.27**: Fixes the `talm` lint job under Go 1.27 and requires Go 1.27 for the build ([**@lexfrei**](https://github.com/lexfrei) in cozystack/talm#237). + +* **[talm] chore(deps): bump Talos to v1.14.0**: Bumps the Talos dependency to v1.14.0, along with fixes so `applycheck` and `meta --insecure` keep working against it and a rendered config keeps every document instead of dropping some ([**@sircthulhu**](https://github.com/sircthulhu) in cozystack/talm#223). + +* **[ansible-cozystack] feat(roles): restore NVIDIA vGPU host state across reboots**: Adds a role that restores NVIDIA vGPU host state after a reboot, instead of requiring it to be reconfigured by hand ([**@lexfrei**](https://github.com/lexfrei) in cozystack/ansible-cozystack#70). + +* **[ansible-cozystack] chore(deps): track cozystack installer v1.6.3**: Renovate dependency bump of the `cozy-installer` Docker image tag to follow the v1.6.3 Cozystack release ([**@app/renovate**](https://github.com/apps/renovate) in cozystack/ansible-cozystack#71). + +* **[ansible-cozystack] chore(deps): update k3s to v1.37.0+k3s1**: Renovate dependency bump of the k3s Kubernetes distribution used by the management-cluster bootstrap role ([**@app/renovate**](https://github.com/apps/renovate) in cozystack/ansible-cozystack#72). + +## Contributors + +Thanks to everyone who contributed to this patch release: + +* [**@androndo**](https://github.com/androndo) +* [**@IvanHunters**](https://github.com/IvanHunters) +* [**@kvaps**](https://github.com/kvaps) +* [**@lexfrei**](https://github.com/lexfrei) +* [**@myasnikovdaniil**](https://github.com/myasnikovdaniil) +* [**@sircthulhu**](https://github.com/sircthulhu) +* [**@tym83**](https://github.com/tym83) +* [**@yankawai**](https://github.com/yankawai) + +### New Contributors + +We're excited to welcome our first-time contributor: + +* [**@yankawai**](https://github.com/yankawai) - First contribution! + +**Full Changelog**: https://github.com/cozystack/cozystack/compare/v1.6.3...v1.6.4 diff --git a/docs/changelogs/v1.6.5.md b/docs/changelogs/v1.6.5.md new file mode 100644 index 000000000..c9158e5a3 --- /dev/null +++ b/docs/changelogs/v1.6.5.md @@ -0,0 +1,157 @@ + + +# v1.6.5 (2026-10-16) + +A patch release with backported fixes for tenant Kubernetes cluster bootstrap, Application updates through the API, suspended `HelmRelease` handling, Cilium and Kube-OVN address allocation, `tcp-balancer` on HAProxy 3.3+, Alertmanager delivery, and a batch of PostgreSQL, MongoDB, NATS, etcd, Velero and dashboard fixes, plus optional email alert delivery, OpenBao static-key auto-unseal and zone placement for Keycloak. **This release contains a breaking change on the Kube-OVN platform variants — read the upgrade notes before upgrading.** + +## Features and Improvements + +* **feat(monitoring): add optional email receiver to alertmanager**: Alerta alerts can now be delivered by email through an optional receiver configured in the monitoring application values, with the alert severity guard tightened so rules using non-Alerta severities are caught ([**@yankawai**](https://github.com/yankawai) in #3800, backport #4614). + +* **feat(openbao): optional static-key auto-unseal and apiserver egress label**: OpenBao can now be auto-unsealed with a static key instead of manual Shamir unseal, with the seal values constrained so only valid settings reach the server config, and the pods can carry an apiserver egress label for network-policy setups. The static seal trade-off and the Shamir migration path are documented in the chart ([**@yankawai**](https://github.com/yankawai) in #4766, backport #4906). + +* **feat(keycloak): expose zone placement for Keycloak and the database proxy**: Keycloak, its database proxy and the `keycloak-db` instances can now be spread across zones, so a zone outage no longer takes the identity provider down with it ([**@sircthulhu**](https://github.com/sircthulhu) in #4606, backport #4856). + +## Fixes + +* **fix(kubernetes): break bootstrap-token Job out of Helm hook to unblock fresh installs**: The bootstrap-token Job is no longer a `post-install,post-upgrade` Helm hook, which deadlocked the chart: the release waited for workers, workers could not register without the bootstrap-token Secret, and the Secret was only created after the wait succeeded. Tenant Kubernetes clusters on fresh installs and upgrades no longer get stuck with `Provisioned` machines that never join ([**@IvanHunters**](https://github.com/IvanHunters) in #3887, backport #4541). + +* **fix(api): keep a suspended HelmRelease suspended across an app update**: Updating an Application through the API no longer resumes a `HelmRelease` that an operator or controller suspended. This fixes backup restores of PostgreSQL stalling at `TargetPurged` because the release was resumed and re-rendered before the purge finished ([**@myasnikovdaniil**](https://github.com/myasnikovdaniil) in #4411, backport #4928). + +* **fix(api): preserve foreign HelmRelease metadata and repair empty required fields**: `Update` on an Application now carries over finalizers, owner references and foreign labels/annotations from the live `HelmRelease`, so a delete racing an update no longer orphans every resource of the release; and a required field written with nothing under it (`replicas:`) is dropped so the chart default applies, with a warning to the client, instead of failing the release with a "missing property" error ([**@mattia-eleuteri**](https://github.com/mattia-eleuteri), [**@myasnikovdaniil**](https://github.com/myasnikovdaniil) in #2914, #3956, backport #4919). + +* **fix(api): let the garbage collector finalize Applications**: Deleting an Application no longer leaves the garbage-collection finalizer behind, so Applications finalize instead of hanging in `Terminating` ([**@yankawai**](https://github.com/yankawai) in #4610, backport #4683). + +* **fix(cilium)!: take cilium's own addresses from a block kube-ovn does not hand out**: On the Kube-OVN variants (`isp-full`, `isp-full-generic`) Cilium now runs `ipam.mode: cluster-pool` with a /29 per node out of the last /21 of `networking.podCIDR`, and the same block is excluded from Kube-OVN, so Kube-OVN can no longer hand a pod an address Cilium already holds for its router or Gateway API ingress. A post-upgrade hook migrates existing clusters. **Breaking, see "Migration and Upgrades" below** ([**@yankawai**](https://github.com/yankawai) in #4778, backport #4918). + +* **fix(tcp-balancer): rename backends and pin HAProxy so the chart starts on 3.3+**: Backend names no longer collide with frontend names, HAProxy is pinned to 3.4.4, and an empty whitelist leaves Kubernetes and Talos frontends unfiltered. Enabling `whitelistHTTP` without a whitelist now fails at render time instead of producing a configuration that rejects all traffic ([**@yankawai**](https://github.com/yankawai) in #4366, backport #4516). + +* **fix(monitoring): send alerts to every Alertmanager replica**: Alerts are now sent to every Alertmanager replica instead of a single one, so alerts are not lost when the replica receiving them is not the active one ([**@yankawai**](https://github.com/yankawai) in #4889, backport #4890). + +* **fix(velero): bump velero-plugin-for-aws to v1.14.4 so backups work on R2**: Updates the AWS plugin so Velero backups to Cloudflare R2 (and compatible S3 stores) work again ([**@yrahman82**](https://github.com/yrahman82) in #4834, backport #4854). + +* **fix(postgres): read the live Cluster when deciding the WAL-archive prefix**: The WAL-archive prefix is now decided from the live CNPG `Cluster`, so upgrades and restores keep archiving WAL to the right location instead of switching prefix ([**@mattia-eleuteri**](https://github.com/mattia-eleuteri) in #4299, backport #4592). + +* **fix(postgres): cap the default shared_buffers at a quarter of the memory limit**: The default `shared_buffers` is capped at a quarter of the memory limit (and at the memory request), so small PostgreSQL instances no longer start with a buffer size that causes out-of-memory kills ([**@yankawai**](https://github.com/yankawai) in #4724, backport #4725). + +* **fix(mongodb): set the s3 bucket and prefix on the bootstrap restore**: The bootstrap restore now gets the S3 bucket and prefix, so restoring a new MongoDB from a backup actually finds the data ([**@yankawai**](https://github.com/yankawai) in #4779, backport #4780). + +* **fix(nats): enable JetStream for the generated account**: JetStream is now enabled for the generated NATS account, so streams and consumers work out of the box ([**@yankawai**](https://github.com/yankawai) in #4675, backport #4677). + +* **fix(etcd): leave compaction to etcd and pass the real quota to defrag**: etcd compaction is left to etcd itself and defragmentation is given the real backend quota, so etcd no longer compacts redundantly or defragments against the wrong size ([**@yankawai**](https://github.com/yankawai) in #4873, backport #4874). + +* **fix(platform): keep the legacy etcd-operator stopped after etcd adoption**: After etcd is adopted by the new operator, the legacy `etcd-operator` stays stopped instead of being scaled back up and fighting over the same clusters ([**@yankawai**](https://github.com/yankawai) in #4738, backport #4739). + +* **fix(linstor): use severity warning in piraeus-datastore alerts**: The `piraeus-datastore` alerts now use the `warning` severity instead of `warn`, which Alerta did not recognise, so these alerts arrive with the correct severity ([**@yankawai**](https://github.com/yankawai) in #3799, backport #4740). + +* **fix(dashboard): allow editing free-form objects in application forms**: Free-form object fields in application forms can now be edited, and a field is marked invalid when the schema rejects it, instead of being locked or silently accepted ([**@yankawai**](https://github.com/yankawai) in #4682, backport #4905). + +* **fix(dashboard, foundationdb): show the connection ConfigMap to tenants**: The application page gets a ConfigMaps tab, with a copy button per value, for ConfigMaps in the application's resource map, and tenant roles may read the FoundationDB connection ConfigMap — so tenants can obtain their FoundationDB connection string. The tab goes away if the resource map becomes unreadable instead of showing stale names ([**@yankawai**](https://github.com/yankawai) in #4612, backport #4684). + +* **fix(cert-manager): enable the Gateway API solver in the host cert-manager**: The host cert-manager controller now has the Gateway API solver enabled, so ACME HTTP-01 challenges can be solved through Gateway API routes ([**@lexfrei**](https://github.com/lexfrei) in #4039, backport #4808). + +* **fix(kubernetes): apply worker TalosConfigTemplate server-side**: The worker `TalosConfigTemplate` is applied server-side, avoiding conflicts and field ownership problems when it is updated on existing tenant clusters ([**@mattia-eleuteri**](https://github.com/mattia-eleuteri) in #4163, backport #4575). + +* **fix(kubernetes): probe Keycloak CRDs by output in oidc-bootstrap cleanup**: The OIDC bootstrap cleanup now probes for Keycloak CRDs by their output, so it no longer fails on clusters where those CRDs are absent ([**@mattia-eleuteri**](https://github.com/mattia-eleuteri) in #3520, backport #4571). + +* **fix(cozy-lib): round the sanitized CPU request up to a whole milli-CPU**: Sanitized CPU requests are rounded up to a whole milli-CPU, so fractional requests no longer produce invalid values that Kubernetes rejects ([**@mattia-eleuteri**](https://github.com/mattia-eleuteri) in #3522, backport #4590). + +## Dependencies + +* **chore(hetzner-robotlb): update robotlb to 0.1.0**: Updates `hetzner-robotlb` to robotlb 0.1.0 ([**@sircthulhu**](https://github.com/sircthulhu) in #4557, backport #4560). + +## Development, Testing, and CI/CD + +* **ci(e2e): run nightly and release-tag e2e on the container lane**: Nightly and release-tag E2E runs now use the Talos container lane, with the nightly runner given headroom over its nodes, matching the merge-gating lanes ([**@lexfrei**](https://github.com/lexfrei) in #4828, backport #4913). + +* **fix(e2e-sandbox): install mc from its GitHub release**: The sandbox image installs the final `mc` release from its pinned GitHub asset and verifies its per-architecture checksum, because `dl.min.io` now returns HTTP 410 and the release-line image build was failing ([**@lexfrei**](https://github.com/lexfrei) in #4447, backport #4535). + +## Documentation + +* **[website] docs(platform-package): note the /21 the kube-ovn variants keep for cilium**: Documents the /21 of `networking.podCIDR` that the Kube-OVN variants now reserve for Cilium ([**@yankawai**](https://github.com/yankawai) in cozystack/website#739). + +* **[website] docs(platform-package): document kubevirt.migrations for v1.6**: Documents the `kubevirt.migrations` platform value in the v1.6 docs ([**@yankawai**](https://github.com/yankawai) in cozystack/website#705). + +* **[website] docs(platform): document the monitoring platform values**: Documents the monitoring platform values ([**@scooby87**](https://github.com/scooby87) in cozystack/website#738). + +* **[website] docs(platform-package): add publishing.serviceDomain**: Adds `publishing.serviceDomain` to the platform values reference ([**@lexfrei**](https://github.com/lexfrei) in cozystack/website#724). + +* **[website] docs(variants): document the slim platform variants**: Documents the `isp-slim`, `isp-slim-generic` and `isp-hosted-slim` variants ([**@lexfrei**](https://github.com/lexfrei) in cozystack/website#718). + +* **[website] docs(talm): document the ZFS export-on-shutdown knob**: Documents the `talm` knob controlling ZFS pool export on shutdown ([**@lexfrei**](https://github.com/lexfrei) in cozystack/website#721). + +* **[website] docs(install): note the talm version pins on the update path**: Notes the `talm` version pins that apply when updating ([**@lexfrei**](https://github.com/lexfrei) in cozystack/website#703). + +* **[website] docs(gpu): select the container variant from bundle values**: Documents selecting the GPU container variant from bundle values ([**@lexfrei**](https://github.com/lexfrei) in cozystack/website#714). + +* **[website] fix(operations): replace the component removal recipe that undoes itself**: Replaces a component removal recipe that reverted itself, and warns what removing a v0 component destroys ([**@lexfrei**](https://github.com/lexfrei) in cozystack/website#684). + +* **[website] fix(docs): correct stale hairpin-proxy uninstall claim and package names**: Corrects a stale hairpin-proxy uninstall claim and package names in `enabledPackages` examples ([**@lexfrei**](https://github.com/lexfrei) in cozystack/website#709). + +* **[website] docs(development): describe the multi-arch default of make image**: Describes the multi-arch default of `make image` ([**@lexfrei**](https://github.com/lexfrei) in cozystack/website#711). + +* **[website] docs: move the next docs to Talos v1.14.2**: Moves the next docs version to Talos v1.14.2 ([**@lexfrei**](https://github.com/lexfrei) in cozystack/website#720). + +* **[website] fix(versions): pin the trunk to published releases and fix released pin headers**: Pins the docs trunk to published releases and fixes released pin file headers ([**@lexfrei**](https://github.com/lexfrei) in cozystack/website#710). + +* **[website] docs(marketplace): point the Repositories view to Admin**: Points the Marketplace docs at the Admin page for the Repositories view ([**@kvaps**](https://github.com/kvaps) in cozystack/website#700). + +* **[website] fix(llms): point llms.txt docs links at the current release**: Makes `llms.txt` link to the current release docs ([**@themoriarti**](https://github.com/themoriarti) in cozystack/website#737). + +* **[website] fix(footer): use the LF Projects copyright notice on every page**: Uses the LF Projects copyright notice in the footer on every page ([**@themoriarti**](https://github.com/themoriarti) in cozystack/website#736). + +* **[website] docs(community): drop the Russian-language Telegram channel**: Removes the Russian-language Telegram channel from the community pages ([**@tym83**](https://github.com/tym83) in cozystack/website#744). + +* **[website] feat(i18n): automated translation pipeline with machine review gate**: Adds an automated documentation translation pipeline with a machine review gate ([**@tym83**](https://github.com/tym83) in cozystack/website#623). + +* **[website] feat(blog): announce the CNCF General Technical Review and compliance results**: Publishes news and a page on the CNCF General Technical Review and conformance results ([**@tym83**](https://github.com/tym83) in cozystack/website#722). + +* **[website] blog: Oberon RISC5 machine as a Cozystack catalog app**: Publishes a news post on the Oberon RISC5 machine as a catalog app ([**@tym83**](https://github.com/tym83) in cozystack/website#723). + +* **[website] docs: update managed apps reference for v1.6.4**: Refreshes the managed applications reference for v1.6.4 ([**@app/cozystack-ci**](https://github.com/apps/cozystack-ci) in cozystack/website#712). + +* **[cozy-proxy] feat(image): publish a linux/amd64 and linux/arm64 index**: `cozy-proxy` v0.4.0 publishes a multi-architecture image index for linux/amd64 and linux/arm64 ([**@lexfrei**](https://github.com/lexfrei) in cozystack/cozy-proxy#22). + +## Migration and Upgrades + +**Breaking change on the Kube-OVN variants (`isp-full`, `isp-full-generic`)** — introduced by #4778 / #4918 (`fix(cilium)!`): + +* `networking.podCIDR` must be /20 or wider; otherwise the platform refuses to render and the upgrade stops before anything changes. Widening the value later does not help, because the migration hook refuses a block outside the subnet the cluster was installed with. +* A /21 of /29 blocks caps these variants at 256 nodes. +* Every Cilium agent restarts twice, once for the configuration change and once in the migration hook. While the `cilium` release is failed, packages that depend on networking wait for it. +* If Kube-OVN has already handed out an address from the last /21, the hook names that address and stops before moving any node. Recreate the pods holding it and the next retry succeeds. +* Rolling back to v1.6.4 restores `ipam.mode: kubernetes`, but the exclusions stay in the `ovn-default` subnet and have to be removed by hand. +* `isp-hosted` is not affected. + +Other upgrade notes: + +* `tcp-balancer`: enabling `whitelistHTTP` now requires a non-empty whitelist; rendering fails otherwise. +* Tenant Kubernetes clusters stuck on v1.6.3/v1.6.4 because of the missing bootstrap-token Secret recover on upgrade; no manual Secret creation is needed. +* PostgreSQL restarts on upgrade for small clusters: a cluster with a memory limit below 512Mi and no explicit `shared_buffers` (the `t1.nano` preset and the default `t1.micro`) now gets `shared_buffers` set to a quarter of the limit, 64MB for `t1.micro`, where PostgreSQL used its built-in 128MB before. The setting needs a restart, so CloudNativePG restarts the replicas first and then the primary in place: writes pause for one restart, and a single-instance cluster is unavailable during it. Upgrade in a quiet window, or set `postgresql.parameters.shared_buffers` yourself beforehand to take the restart on your own schedule. Clusters with 512Mi or more are unchanged. + +## Contributors + +Thanks to everyone who contributed to this patch release: + +* [**@IvanHunters**](https://github.com/IvanHunters) +* [**@kvaps**](https://github.com/kvaps) +* [**@lexfrei**](https://github.com/lexfrei) +* [**@mattia-eleuteri**](https://github.com/mattia-eleuteri) +* [**@myasnikovdaniil**](https://github.com/myasnikovdaniil) +* [**@scooby87**](https://github.com/scooby87) +* [**@sircthulhu**](https://github.com/sircthulhu) +* [**@themoriarti**](https://github.com/themoriarti) +* [**@tym83**](https://github.com/tym83) +* [**@yankawai**](https://github.com/yankawai) +* [**@yrahman82**](https://github.com/yrahman82) + +### New Contributors + +We're excited to welcome our first-time contributors: + +* [**@themoriarti**](https://github.com/themoriarti) - First contribution! +* [**@yrahman82**](https://github.com/yrahman82) - First contribution! + +**Full Changelog**: https://github.com/cozystack/cozystack/compare/v1.6.4...v1.6.5 diff --git a/docs/changelogs/v1.7.1.md b/docs/changelogs/v1.7.1.md new file mode 100644 index 000000000..500735d9f --- /dev/null +++ b/docs/changelogs/v1.7.1.md @@ -0,0 +1,82 @@ + + +# Cozystack v1.7.1 + +Cozystack v1.7.1 is a patch release on the v1.7 line. It fixes the COSI driver bug that could leave freshly granted S3 keys rejected for good, makes marketplace taps digest-pinned, makes MariaDB, PostgreSQL and ClickHouse backups report their real outcome, and repairs several tenant-facing issues: tenant cluster metrics, SecurityGroups on Kubernetes workers, Redis with a single replica, the Proxmox cloud-controller-manager and the tcp-balancer. Read the Migration and Upgrades section before upgrading. + +## Fixes + +* **SeaweedFS COSI driver v0.4.0**: bucket users granted together could get S3 keys that never work (`403 InvalidAccessKeyId`) because the v0.3.1 driver rewrote a legacy IAM file the S3 gateways were migrating. The driver is bumped to v0.4.0, which writes each grant to a per-identity IAM file. Keys already lost on running clusters stay broken: remove the user from the Bucket, wait until its BucketAccess is gone, and add it back ([**@myasnikovdaniil**](https://github.com/myasnikovdaniil) in #5284, backport #5290). +* **Marketplace taps are pinned to a digest**: a tapped repository no longer follows a mutable tag, so moving the tag upstream cannot change what runs in the cluster. `tap connect` accepts `oci://...@sha256:...` references and an optional keyless cosign verify policy, anchored to an exact identity and preserved across re-connects; with the verify flags the CLI verifies the signature and pins the verified digest at tap time. Community index entries can record a digest too ([**@IvanHunters**](https://github.com/IvanHunters) in #5082, backport #5246). +* **Tenant cluster metrics reach the tenant's Monitoring**: the vmagent of tenant Kubernetes clusters now writes to the tenant's vminsert and labels series with the owning tenant instead of `cozy-monitoring`; before, no tenant cluster metric reached the tenant's Monitoring ([**@mattia-eleuteri**](https://github.com/mattia-eleuteri) in #5024, backport #5246). +* **SecurityGroups apply to Kubernetes worker nodes**: the virt-launcher pods of Kubernetes worker nodes are now resolved to their Kubernetes application and marked as managed by Cozystack, so a SecurityGroup attached to a Kubernetes cluster applies to its workers, not only to its control plane ([**@mattia-eleuteri**](https://github.com/mattia-eleuteri) in #5124, backport #5246). +* **Membership-only SecurityGroups**: a SecurityGroup with attachments and no rules no longer leaves an invalid CiliumNetworkPolicy behind; its backing policy is accepted by Cilium and still allows or denies nothing ([**@mattia-eleuteri**](https://github.com/mattia-eleuteri) in #5133, backport #5246). +* **Proxmox CCM and CSI images**: the Proxmox cloud-controller-manager runs v0.16.1 and the Proxmox CCM and CSI driver images are pinned by digest. The v0.15.0 tag was re-pushed upstream to a build that panics on start, which left every new Proxmox worker with the uninitialized taint ([**@themoriarti**](https://github.com/themoriarti) in #4917, backport #5246). +* **Autoscaler capacity of KubernetesNodes pools**: on the kubevirt substrate the cluster-autoscaler capacity annotation is planned on the cores the VM actually gets, so a leading-zero `resources.cpu` such as `"010"` (decoded as YAML, eight cores) no longer yields a wrong capacity. No pool rolls ([**@themoriarti**](https://github.com/themoriarti) in #4974, backport #5246). +* **Tenant quota admission counts extended resources**: admission now reads the parent pool's usage of extended resources and hugepages under the `requests.*` key the controller counts, so a child tenant can no longer get a share the parent has already used ([**@lexfrei**](https://github.com/lexfrei) in #5184, backport #5246). +* **Postgres backup jobs fail as soon as the CloudNativePG Backup fails**: a Postgres `BackupJob` now fails with the recorded error instead of after 30 minutes, and reports a `WaitingForCNPGBackup` condition with the Backup's phase while it waits ([**@scooby87**](https://github.com/scooby87) in #5211, backport #5246). +* **MariaDB backups and restores report real failures**: a `BackupJob` or `RestoreJob` whose operator Job failed now ends Failed instead of Succeeded, and a failed backup no longer creates a Ready Backup without an archive ([**@scooby87**](https://github.com/scooby87) in #5207, backport #5246). +* **ClickHouse restores use the right archive**: a `RestoreJob` restores the archive its Backup was taken as, not the newest one. New Backups record the archive name; Backups taken before this release are restored best effort from the newest archive stamped no later than their `takenAt`, with a warning in the restore pod log. A ClickHouse `BackupJob` created under a name whose Backup still exists now fails instead of reporting that Backup as its result ([**@myasnikovdaniil**](https://github.com/myasnikovdaniil) in #5208, backport #5246). +* **Backup S3 endpoint changes are followed**: the backup controller re-renders the Velero BSL, the default backup strategies and the platform bucket's credentials Secret when their S3 endpoint is stale, so after the platform bucket's BucketAccess is re-granted for a new `publishing.host`, backups move to the new endpoint without forcing releases by hand ([**@scooby87**](https://github.com/scooby87) in #5230, backport #5246). +* **Backup clients run on a dedicated image**: the ClickHouse (Altinity) and RabbitMQ backup strategy Pods now run a small `backup-http-client` image instead of the 349 MB `platform-migrations` image, so a platform migration change no longer re-digests the backup clients. Air-gapped mirrors need the new `ghcr.io/cozystack/cozystack/backup-http-client` repository ([**@androndo**](https://github.com/androndo) in #4756, backport #5246). +* **PostgreSQL system databases**: `databases` refuses `postgres`, `template0` and `template1`, and the init job never runs `DROP DATABASE` on them, which used to fail the init job on every upgrade and leave the HelmRelease in `UpgradeFailed` ([**@mattia-eleuteri**](https://github.com/mattia-eleuteri) in #5155, backport #5246). +* **PostgreSQL init script is stable**: the declared databases render in a stable order, so an upgrade that leaves the databases unchanged no longer rewrites the init-script Secret ([**@mattia-eleuteri**](https://github.com/mattia-eleuteri) in #5091, backport #5246). +* **Redis with a single replica**: an instance with `replicas: 1` runs one Sentinel instead of three, without a Sentinel PodDisruptionBudget, so node drains are no longer blocked by it; instances with two replicas or more are unchanged ([**@mattia-eleuteri**](https://github.com/mattia-eleuteri) in #5151, backport #5246). +* **MariaDB operator on a custom cluster domain**: the operator uses the platform's `networking.clusterDomain` instead of a hard-coded `cozy.local`, so replication and User/Database/Grant reconciliation work on clusters with a non-default domain ([**@mattia-eleuteri**](https://github.com/mattia-eleuteri) in #5123, backport #5246). +* **tcp-balancer no longer OOMs**: HAProxy takes its fd and thread caps from the replica's own memory and CPU limits instead of the node, so a `t1.nano` balancer is no longer OOMKilled on nodes with many CPUs ([**@yankawai**](https://github.com/yankawai) in #5005, backport #5246). +* **etcd alert noise**: `etcdHighNumberOfFailedGRPCRequests` counts only the gRPC codes the etcd mixin counts, so the Canceled watch streams of a stopping Kubernetes API server no longer fire it on every member ([**@yankawai**](https://github.com/yankawai) in #4985, backport #5246). +* **Cilium IPAM hook on larger clusters**: the hook passes the CiliumNode list to `jq` on stdin and no longer fails with "Argument list too long" on clusters with more than a few nodes, which blocked the cilium upgrade and every package depending on networking ([**@myasnikovdaniil**](https://github.com/myasnikovdaniil) in #5212, backport #5246). +* **OIDC bootstrap Job with many users**: the Job no longer fails to start for a tenant cluster with about 240 or more `oidc.users`; the bindings now come from a ConfigMap the Job mounts ([**@myasnikovdaniil**](https://github.com/myasnikovdaniil) in #5213, backport #5246). +* **Dashboard tenant list links to the tenant page**: the tenant name in the tenant list opens its detail page, where Delete lives, and top-level tenants get their Edit button back ([**@myasnikovdaniil**](https://github.com/myasnikovdaniil) in #4004, backport #5246). +* **Dead `registries` platform value removed**: the platform chart no longer has the `registries` value or the `patch-containerd` Secret, which nothing read. Mirrors for tenant workers are the per-pool `talos.registryMirrors` of `KubernetesNodes` ([**@myasnikovdaniil**](https://github.com/myasnikovdaniil) in #5190, backport #5246). + +## Security + +* **Marketplace digest pinning and signature verification**: see the marketplace entry under Fixes (#5082). + +## Development, Testing, and CI/CD + +* **Chainsaw asserts survive transient API errors**: an e2e assert keeps polling through an error such as an etcd leader change instead of failing the suite early ([**@lexfrei**](https://github.com/lexfrei) in #4867, backport #5246). +* **Proxmox e2e hygiene**: the Proxmox tenant kubeconfig is kept per run and removed afterwards, the HelmRelease guard reads the `KubernetesNodes` pool release, and the leak allowlist is validated against every suite layout ([**@themoriarti**](https://github.com/themoriarti) in #4971, #4970 and #4972, backports #5246). +* **Frozen-line builds start with `GITHUB_TOKEN`**: the initial packages build dispatched when a release line is frozen now runs ([**@myasnikovdaniil**](https://github.com/myasnikovdaniil) in #4888, backport #5246). +* **Unit tests after the release image restamp**: two unit tests that read fields the release build rewrites stay green on `release-1.7`; this is a release-branch-only fix ([**@themoriarti**](https://github.com/themoriarti) in #5179). + +## Documentation + +* **[website] Documentation**: the v1.7 docs gain the guides that lived only in the cozystack repository, the pending v1.7 docs PRs, a DRBD note for the replicated storage class, a refreshed Chainsaw e2e guide, restored legacy URLs and a grouping of older doc versions ([**@myasnikovdaniil**](https://github.com/myasnikovdaniil) in cozystack/website#763, cozystack/website#782, cozystack/website#675, cozystack/website#611, cozystack/website#775 and cozystack/website#767). +* **[website] Blog and demo**: a full-stack observability post for v1.7, the Cozystack 1.7 announcement, a three-board Raspberry Pi 5 post, and a collapsible navbar with a closable hint on the live demo page ([**@tym83**](https://github.com/tym83) in cozystack/website#790, cozystack/website#801 and cozystack/website#802; [**@kvaps**](https://github.com/kvaps) in cozystack/website#789). +* **[website] Pages deploy**: the deploy workflow drops the Dart Sass install ([**@kvaps**](https://github.com/kvaps) in cozystack/website#798). +* **[ansible-cozystack] Installer v1.7.0**: tracks the Cozystack installer image at v1.7.0, released in ansible-cozystack v1.7.0 ([**@app/renovate**](https://github.com/apps/renovate) in cozystack/ansible-cozystack#89). + +## Migration and Upgrades + +Platform migrations do not change in this release: `migrations.targetVersion` stays at 61. + +* **Remove system databases from PostgreSQL `databases` before upgrading (#5155).** A release that declares `postgres`, `template0` or `template1` under `databases` is refused at render; remove the entry first. A system database a previous version took over is handed back to the superuser on the next upgrade: the event trigger is removed, ownership and the `public` schema are restored, and its `_admin` and `_readonly` roles are dropped. +* **Tenant quota updates can be rejected after upgrading (#5184).** Admission now counts the parent's usage of extended resources and hugepages, so an update to an existing tenant can be rejected when its quota for these resources exceeds the parent's remaining budget, including an update that leaves the quota unchanged. +* **Air-gapped mirrors need `backup-http-client` (#4756).** Mirror `ghcr.io/cozystack/cozystack/backup-http-client` before upgrading, or ClickHouse and RabbitMQ backup Pods cannot pull their image. +* **tcp-balancer pods roll once (#5005).** The new HAProxy `global` section changes the rendered config; `maxconn` follows the memory limit at about 16 connections per MiB (2035 on `t1.nano`). +* **Redis scaled to one replica loses its Sentinel PDB (#5151).** A post-upgrade hook deletes the Sentinel PodDisruptionBudget the operator created earlier for an instance with `replicas: 1`; scaling an instance between 1 and 2 replicas scales its Sentinel Deployment between 1 and 3. +* **Backups created by failed MariaDB runs are not cleaned up (#5207).** Backups made by failed runs before this fix are not removed; restoring from one can fail or select another dump from the shared prefix. +* **Keys lost to the COSI grant bug stay lost (#5284).** Re-add the affected user to the Bucket as described in the Fixes entry. +* **`registries` in the platform Package is ignored (#5190).** A Package that still sets it keeps installing; the `patch-containerd` Secret in `cozy-system` is deleted by the release. +* **SecurityGroups now reach Kubernetes workers (#5124).** A SecurityGroup attached to a `Kubernetes` application starts applying to its worker nodes after the upgrade, so review attached groups before upgrading. + +## Contributors + +We'd like to thank all contributors who made this release possible: + +* [**@androndo**](https://github.com/androndo) +* [**@IvanHunters**](https://github.com/IvanHunters) +* [**@kvaps**](https://github.com/kvaps) +* [**@lexfrei**](https://github.com/lexfrei) +* [**@mattia-eleuteri**](https://github.com/mattia-eleuteri) +* [**@myasnikovdaniil**](https://github.com/myasnikovdaniil) +* [**@scooby87**](https://github.com/scooby87) +* [**@themoriarti**](https://github.com/themoriarti) +* [**@tym83**](https://github.com/tym83) +* [**@yankawai**](https://github.com/yankawai) + +**Full Changelog**: https://github.com/cozystack/cozystack/compare/v1.7.0...v1.7.1 diff --git a/docs/gateway-classes.md b/docs/gateway-classes.md deleted file mode 100644 index d018035fd..000000000 --- a/docs/gateway-classes.md +++ /dev/null @@ -1,124 +0,0 @@ -# GatewayClass selection and TLS termination for tenant Gateways - -A tenant that owns a Gateway (`tenant.spec.gateway: true`) gets one `Gateway` object bound to one `GatewayClass`. Which class that is decides who programs the dataplane and, with it, whether TLS is terminated by the Gateway itself or by something in front of it. This page covers the operator-facing surface: the platform values that bound the choice, the tenant field that makes it, what each resulting certificate mode implies, what a move between classes does to certificates and Secrets, and how the mechanism fails when the configured names and the installed classes disagree. - -The chart-level reference for the per-tenant Gateway — inheritance, listener shapes, the security model, ACME rate limits — is [`packages/extra/gateway/README.md`](../packages/extra/gateway/README.md). - -## Platform values - -Three keys under `gateway` in the platform values bound which class a tenant Gateway can land on: - -```yaml -gateway: - enabled: true - className: cilium - tenantSelectableClasses: [] - edgeTerminatedClasses: [] -``` - -- `className` — the class every tenant Gateway uses unless the tenant names another one. Defaults to the Cilium class the platform ships. -- `tenantSelectableClasses` — the additional class names a tenant may name for itself. Empty (the default) means a tenant cannot name anything but the platform default. -- `edgeTerminatedClasses` — the class names whose provider terminates TLS upstream of the Gateway. Membership in this list is the only thing that puts a tenant into edge mode. - -All three reach the per-tenant gateway chart through the platform values channel, as `_cluster.gateway-class-name`, `_cluster.gateway-tenant-classes` and `_cluster.gateway-edge-classes`. The two lists are joined with commas on the way, so a name containing a comma is rejected at platform render time rather than silently split into two names. - -`gateway.enabled` is a separate switch and not a prerequisite for any of this: it moves the platform's own published services from Ingress onto Gateway API and points the ACME `ClusterIssuer`s' HTTP-01 solver at the publishing tenant's Gateway. A tenant Gateway is created from `tenant.spec.gateway` alone. - -## How a tenant picks a class - -```yaml -apiVersion: apps.cozystack.io/v1alpha1 -kind: Tenant -metadata: - name: acme - namespace: tenant-root -spec: - gateway: true - gatewayClass: edge-tunnel -``` - -`edge-tunnel` throughout this page stands for the name of a GatewayClass whose controller terminates TLS outside the cluster and forwards cleartext to the Gateway. Substitute the name your own edge-terminating controller registers. - -The field is read only for a tenant that owns a Gateway. A tenant that inherits — `gateway` left unset or set to `false` — publishes through the nearest ancestor that owns one and runs on that ancestor's class, so its own `gatewayClass` has no effect. Leaving `gatewayClass` empty selects `gateway.className`. - -The set a tenant may name is `gateway.tenantSelectableClasses` plus the current `gateway.className`, so a tenant may always name the default explicitly. Anything else fails that tenant's own gateway release at render time, with a message naming the class and the allowed set, and reaches no other tenant. The allowlist exists because `Tenant` is a tenant-writable object while a `GatewayClass` is cluster-scoped: without it a tenant could attach its Gateway to any class the cluster registers, including one an admin keeps for internal-only traffic. - -## What the class decides: the certificate mode - -`TenantGateway.spec.certMode` is derived, never written by the tenant. The gateway chart resolves it in this order, first match winning: - -| Condition | `certMode` | What the controller issues | -| --- | --- | --- | -| the resolved class is in `gateway.edgeTerminatedClasses` | `edge` | nothing | -| `publishing.certificates.wildcardSecretName` is set | `existingSecret` | nothing; the operator's Secret is referenced | -| `publishing.certificates.solver: dns01` | `dns01` | one wildcard `Certificate` per tenant | -| otherwise | `http01` | one `Certificate` per published hostname, except the passthrough names below | - -Under `http01` a hostname held by a TLS-passthrough listener is the exception to the per-hostname rule. Once a `TLSRoute` is served on that listener and forwards to a backend, the hostname earns neither an HTTPS-terminate listener nor a `Certificate`, because the backend presents its own certificate and the Gateway never holds a key for the name. The shipped `tlsPassthroughServices` defaults put `api`, `vm-exportproxy` and `cdi-uploadproxy` in that position on the publishing tenant, and the `Certificate` objects that covered them are collected on upgrade; `packages/extra/gateway/README.md` carries what that changes and the ways forward. - -Edge therefore wins over an operator-supplied wildcard Secret, which wins over the solver. In edge mode the solver, DNS-01 provider and issuer-name inputs are not read at all, so an unsupported value in any of them does not fail the tenant's release. `existingSecret` skips the same validations; only `http01` and `dns01` reject a bad solver, provider or issuer name. - -## What edge mode changes on the Gateway - -- The Gateway serves port 80 only. Its listeners are `edge` for `*.`, `edge-apex` for ``, and one `edge-child-*` per inheriting child tenant carrying that child's `*.`. There is no port-443 listener, and no hostname-less port-80 listener either. -- No per-tenant ACME `Issuer` and no `Certificate` are created. -- No http-to-https redirect `HTTPRoute` is created. The edge is expected to perform that redirect. -- `tlsPassthroughServices` is not written onto the `TenantGateway` and no passthrough listener is rendered, so the tenant Kubernetes API, VM export and CDI upload endpoints are not published through such a Gateway. The packages that own those endpoints still create their `TLSRoute` objects, which then match no listener on that Gateway. -- Application `HTTPRoute`s attach by hostname exactly as in the other modes — the edge listeners carry the same namespace selector the HTTPS listeners carry elsewhere. - -That last point has a blast radius worth stating on its own, and it applies only where those endpoints are published through the Gateway at all. Each of them renders its `TLSRoute` only when `gateway.enabled` is on and its name is still in `publishing.exposedServices`; at the default `gateway.enabled: false` there is no such route and nothing to lose. Where both hold, setting `gateway.className` to an edge-terminated class puts the publishing tenant on it too, and then the endpoints that go unpublished are the platform's own: the `TLSRoute` for `api.` is pinned to a `tls-api` listener, an edge Gateway has no such listener, so the tenant Kubernetes API stops being served — VM export and CDI upload go the same way. Nothing fails at render time, and the loss surfaces only on the routes themselves, which the controller flips to `Accepted=False` with reason `NoMatchingParent`. Putting only child tenants on the edge class avoids it, because the platform's routes keep pointing at the publishing tenant's Gateway. - -Listing a class in `gateway.edgeTerminatedClasses` is an assertion about that class, and nothing verifies it. Put the bundled `cilium` class in the list and its Gateways serve every application hostname over plain HTTP on a public address, with no redirect and no certificate. Only list a class whose provider really does terminate TLS in front of the Gateway. - -## Moving a tenant between classes - -Onto an edge-terminated class, on the next reconcile: - -| Object | What happens | -| --- | --- | -| the per-tenant ACME `Issuer` | deleted | -| per-listener and wildcard `Certificate` objects | deleted | -| the TLS Secrets those `Certificate`s issued | left in the namespace, unreferenced | -| the http-to-https redirect `HTTPRoute` | deleted | -| the replica of `publishing.certificates.wildcardSecretName` | deleted from that tenant's namespace | -| route status conditions the controller wrote earlier | an attached `TLSRoute` that declares hostnames is flipped to `Accepted=False`, reason `NoMatchingParent`; on a hostname-less `TLSRoute`, and on every attached `HTTPRoute`, the controller's own entry is removed instead | - -Every deletion is guarded by ownership: an object of the same name that the controller did not create is left in place. - -The TLS Secrets survive because cert-manager ships here with `enableCertificateOwnerRef: false`, so a `Certificate` does not own the Secret it issued into. That is how every mode transition behaves and is not something edge introduces. Removing the leftovers is an operator action. - -The wildcard replica is withdrawn because the namespace stops counting as a TLS termination point. Three things keep it anyway: a namespace that also owns an ingress controller still terminates locally; a namespace holding more than one `TenantGateway` keeps the replica while any of them is not on an edge-terminated class; and a namespace whose `TenantGateway` objects cannot be listed, or which carries the Gateway owner label but has no `TenantGateway` yet, keeps it as well, so that a transient read failure never withdraws a key a Gateway may still be serving. - -Moving back off an edge-terminated class restores whatever the new mode calls for: the ACME `Issuer` and its `Certificate`s under `http01` or `dns01`, the redirect route under any non-edge mode, and the wildcard replica whenever `publishing.certificates.wildcardSecretName` is set. The `TLSRoute` conditions go back too, since the passthrough listeners do: `http01` judges those routes again from the hostname claims it collects, while `dns01` and `existingSecret` collect none and so drop the entry rather than leave a withdrawal standing on a listener that is serving. `existingSecret` mints no `Issuer` and no `Certificate` of its own, so a move from `edge` into it brings back the replica and the redirect route and nothing else. - -The two halves of the move are not ordered against each other. The wildcard-secret controller watches the `TenantGateway` and prunes the replica as soon as `certMode` changes, while the `Gateway` itself is re-rendered when the tenant's HelmRelease reconciles, and the class controller reprograms after that. A tenant leaving `existingSecret` can therefore be briefly serving HTTPS listeners whose Secret has already gone. - -## When the configured names and the installed classes disagree - -Nothing in this mechanism checks that a class name corresponds to a `GatewayClass` the cluster actually has. Run `kubectl get gatewayclass` before putting a name into any of the three values. - -- **A name in `className` or `tenantSelectableClasses` that matches no installed class.** The tenant's release renders and the `Gateway` object is created, but no controller claims it, so it gets no address and no listener status. Nothing fails at render time; the symptom is the `TenantGateway` holding `Ready=False` with reason `GatewayNotAccepted`. -- **A misspelled name in `edgeTerminatedClasses`.** It matches no class, so edge mode never engages for it and nothing says so. A tenant whose TLS really is terminated upstream stays in whichever mode the solver and wildcard-secret settings select, and its Gateway keeps terminating TLS itself. -- **A class removed from `tenantSelectableClasses` while a tenant still names it.** That tenant's gateway release starts failing to render. Other tenants are unaffected. -- **`className` changed while a tenant pins the outgoing name.** The allowed set is the *current* default plus `tenantSelectableClasses`, so the pin stops being valid and that tenant's gateway release fails. Add the outgoing class to `tenantSelectableClasses` before changing the default, or update the tenant first. -- **The publishing tenant selecting a class that terminates TLS differently from `className`.** Refused at render time, in both directions. The cluster-wide ACME `ClusterIssuer`s point their HTTP-01 solver at the publishing tenant's Gateway, and whether that solver pins `sectionName: http` is decided from `gateway.className` alone — a tenant's own choice does not travel on that channel. A publishing tenant that moved itself onto an edge class would keep a solver pinned to the `http` listener its Gateway no longer renders, and every HTTP-01 certificate in the cluster would stop issuing with nothing in any status naming the cause. Change `gateway.className` instead. The publishing tenant is the namespace named by `publishing.ingressName`, `tenant-root` by default. -- **A comma or a non-string entry in either list.** The platform chart fails to render, naming the entry. - -## Checking what a tenant landed on - -```bash -kubectl get gatewayclass - -kubectl --namespace tenant-acme get tenantgateway cozystack \ - --output jsonpath='{.spec.gatewayClassName}{"\t"}{.spec.certMode}{"\n"}' - -kubectl --namespace tenant-acme get tenantgateway cozystack \ - --output jsonpath='{range .status.conditions[?(@.type=="Ready")]}{.status}{"\t"}{.reason}{"\n"}{end}' - -kubectl --namespace tenant-acme get gateway cozystack \ - --output jsonpath='{range .spec.listeners[*]}{.name}{"\t"}{.port}{"\t"}{.hostname}{"\n"}{end}' - -kubectl --namespace tenant-acme get certificate,issuer -``` - -A tenant on an edge-terminated class reports `certMode: edge`, shows port-80 listeners only, and has no `Certificate` or `Issuer` that this controller created. Leftover TLS Secrets from an earlier mode are not shown by the last command — list Secrets of type `kubernetes.io/tls` in the namespace to find those. diff --git a/docs/gpu-vgpu.md b/docs/gpu-vgpu.md deleted file mode 100644 index af6e574f2..000000000 --- a/docs/gpu-vgpu.md +++ /dev/null @@ -1,398 +0,0 @@ -# GPU Operator: passthrough and vGPU - -This document describes how to configure the GPU Operator package with NVIDIA vGPU support so that a single physical GPU can be sliced and shared across multiple virtual machines. - -**Last verified:** 2026-04-29 against KubeVirt `main` (`virt-handler` nightly `20260429_74d7c52588`) + the `vgpu` variant + NVIDIA vGPU 20.0 host driver `595.58.02` + GRID guest driver `595.58.03`. - -## Two driver models - -NVIDIA's vGPU driver uses two different host-side models depending on GPU generation: - -- **Mediated devices (mdev)** — Pascal / Volta / Turing / Ampere up to A100 / A30. The driver creates `mdev` parent devices under `/sys/class/mdev_bus/`; KubeVirt advertises them via `permittedHostDevices.mediatedDevices`. -- **SR-IOV with per-VF sysfs** — Ada Lovelace (L4, L40, L40S, …) and Blackwell (B100, …) on the vGPU 17/20 driver branch. The driver creates SR-IOV virtual functions; profile selection happens via `/sys/bus/pci/devices//nvidia/current_vgpu_type`. KubeVirt advertises VFs via `permittedHostDevices.pciHostDevices` after [kubevirt/kubevirt#16890](https://github.com/kubevirt/kubevirt/pull/16890). - -This guide focuses on the **SR-IOV path**, which is the only model NVIDIA supports for current data-centre GPUs. Mdev is mentioned for completeness; for Pascal–Ampere refer to the upstream NVIDIA GPU Operator docs. - -## Prerequisites - -- An Ada Lovelace (or newer) NVIDIA GPU that supports SR-IOV vGPU (L4, L40, L40S, etc.). -- Ubuntu 24.04 host OS. Older Ubuntu releases also work if the upstream `gpu-driver-container` repo has a matching `vgpu-manager/` Dockerfile. **Talos Linux is not recommended** for vGPU. NVIDIA does not publicly distribute the vGPU guest driver — it requires NVIDIA Enterprise Portal access — and Sidero [closed siderolabs/extensions#461](https://github.com/siderolabs/extensions/issues/461) noting that they cannot support vGPU "unless NVIDIA changes their licensing terms or provides us a way to obtain, test, and distribute the software". Building a Talos system extension that includes the driver in-tree is therefore not feasible without a private fork that violates the EULA. -- KubeVirt v1.9.0 or newer, which is the release the platform bundles. [kubevirt/kubevirt#16890](https://github.com/kubevirt/kubevirt/pull/16890) ("vGPU: SRIOV support") shipped in v1.9.0; v1.8.x and older do not include it and backports are not planned. -- An NVIDIA vGPU Software / NVIDIA AI Enterprise subscription (the `.run` is not redistributable). -- A reachable NVIDIA Delegated License Service (DLS) instance and a matching `client_configuration_token.tok` file. - -## Variants - -The `gpu-operator` package exposes three variants. This document is vGPU-focused; the variant inventory is shared. - -- **`default`** — passthrough mode (`vfio-pci`). Whole GPU goes to a single VM. Talos is supported here; the kernel module is the open-source `vfio-pci`, no proprietary driver is needed on the host. -- **`vgpu`** — SR-IOV vGPU mode. One physical GPU is sliced into multiple VFs, each VF bound to a vGPU profile that the guest sees as its own GPU. -- **`container`** — containerized GPU workloads (CUDA pods, ML training) via the standard NVIDIA device plugin on hosts that already provide both the NVIDIA driver and `nvidia-container-toolkit` (the typical apt-installed Ubuntu/Debian shape). Sandbox workloads are off, `devicePlugin` is on, `driver` / `toolkit` / `vfioManager` / `cdi` are off so that the operator does not fight the host install. Orthogonal to the two VM variants — it does not pass GPUs to KubeVirt VMs. Note that `apt install nvidia-container-toolkit` installs binaries only — it does not configure containerd. Because this variant disables the operator's toolkit component (which would normally do that wiring), the host must additionally have run `nvidia-ctk runtime configure --runtime=containerd` (followed by a containerd restart) and exposed the `nvidia` runtime as the default or via a RuntimeClass before the device plugin can serve GPUs. - -## Passthrough variant: host preparation - -**Last verified:** 2026-05-28 against `cozystack.gpu-operator` chart `gpu-operator` v26.3.1 + image `nvcr.io/nvidia/cloud-native/k8s-driver-manager:v0.10.0` (distroless image with a Go ELF binary `/usr/bin/driver-manager`, entrypoint `["driver-manager", "preflight_check"]`; verified via `crane export … | tar -x usr/bin/driver-manager` and `strings` over the resulting binary) + Ubuntu 24.04 host with `nvidia-driver-580-open` 580.82.07 pre-installed. Tracks [#2763](https://github.com/cozystack/cozystack/issues/2763). - -The `default` (passthrough) variant assumes the GPU is **owned by the host kernel's `vfio-pci` driver and nothing else**. - -**How the operator detects a pre-installed host driver.** The chart's `vfio-manager` DaemonSet runs the upstream NVIDIA `k8s-driver-manager` init container with the `uninstall_driver` subcommand; that path calls the Go method `(*DriverManager).isHostDriver`, which runs `chroot /host nvidia-smi --query-gpu=driver_version --format=csv,noheader` and treats any non-empty stdout as "host driver present" (file-existence is not pre-tested — if `nvidia-smi` is missing, the chroot exec errors and `isHostDriver` returns false, which is the intended path on a clean host: the operator then proceeds with the uninstall flow and `vfio-manager` binds `vfio-pci` as designed). On a positive detection the binary logs `Host driver detected: `, labels the node `nvidia.com/gpu.deploy.driver=pre-installed`, exits, and `nvidia-sandbox-validator` then crashloops with `device not bound to 'vfio-pci'`. - -**`FORCE_REINSTALL` does not bypass this.** `k8s-driver-manager` v0.10.0 exposes a `FORCE_REINSTALL` / `--force-reinstall` env+flag pair (visible in the binary's strings table), but it gates a later "same-config already loaded" branch inside `uninstallDriver`, not the `isHostDriver` short-circuit at the top — operators who set it and expect a bypass will report a false bug. There is currently no opt-out for the `isHostDriver` guard itself. - -**Current mitigation.** The only mitigation that keeps VM passthrough working is to remove the host NVIDIA stack before enabling the variant (the "Clean-host workaround" section below). - -**Alternatives and scope.** The `container` variant of `cozystack.gpu-operator` is the no-purge path: it keeps the host driver and exposes GPUs to pods rather than VMs, so it does not replace passthrough for anyone who actually needs a GPU inside a VM. Talos is unaffected because the Talos image ships only the `vfio-pci` extension; this section applies to Linux distributions where you installed the host driver yourself (typically Ubuntu / Debian / RHEL with `apt install nvidia-driver-*` or equivalent). See also [`packages/system/gpu-operator/examples/README.md`](../packages/system/gpu-operator/examples/README.md) for the Talos native-pod-workload reference flow. - -### Symptom - -The first thing you see is `kubectl get pods -n cozy-gpu-operator` showing `nvidia-vfio-manager-*` stuck in `Init:Error` / `Init:CrashLoopBackOff` — the init container exits non-zero after detecting the host driver, so kubelet keeps restarting it. - -Its log shows it skipped the bind step: - -```text -Host driver detected: 580.82.07 -NVIDIA GPU driver is already pre-installed on the node, - disabling the containerized driver -Labeling node with nvidia.com/gpu.deploy.driver=pre-installed -``` - -`nvidia-sandbox-validator` then crashloops: - -```text -Error: error validating vfio-pci driver installation: - device not bound to 'vfio-pci'; device: 0000:18:00.0 driver: 'nvidia' -``` - -`lspci -nnk -d 10de:` still shows `Kernel driver in use: nvidia` on every target GPU, the node carries `nvidia.com/gpu.deploy.driver=pre-installed`, and `kubectl get node -o json | jq '.status.allocatable | with_entries(select(.key | startswith("nvidia.com/")))'` reports `{}` — no GPU resource was registered. - -### Clean-host workaround - -Purge the NVIDIA host stack and blacklist the kernel modules so the host never re-claims the GPU. Two pitfalls to avoid: `apt autoremove` is dangerous here because the `nvidia-` prefix is shared with NVIDIA DOCA / Mellanox / InfiniBand userspace, so a blanket autoremove can take RDMA out on a converged GPU + RDMA host; and a hardcoded `apt purge 'nvidia-*' 'cuda-*'` pattern list is fragile — `apt` treats `*` as a cache-wide regex and **aborts the entire transaction, purging nothing**, if any pattern matches nothing in the cache (e.g. `cuda-*` on a host without NVIDIA's CUDA repo). Build the list from what is actually installed instead: - -```bash -# dpkg-query patterns are true globs over INSTALLED packages: no -# zero-match abort (unlike apt's cache-wide regex) and no accidental -# substring over-match. List first, then review before purging. -dpkg-query -W -f '${Package}\n' 'nvidia-*' 'libnvidia-*' 'cuda-*' 2>/dev/null -``` - -Review the list before purging: - -- `nvidia-dkms-*` and `nvidia-kernel-*` are the load-bearing kernel pieces — without removing them DKMS rebuilds `nvidia.ko` on the next reboot and the blacklist below is bypassed by any explicit `modprobe`. -- On a **converged GPU + RDMA host**, drop any `libnvidia-*` that belong to NVIDIA DOCA / Mellanox OFED — purging those breaks RDMA. -- If the list is **empty**, the driver was installed with NVIDIA's `.run` installer rather than apt — run `sudo nvidia-uninstall` instead of the purge below. - -Then purge the reviewed list, blacklist the modules, and rebuild the initramfs: - -```bash -# Replace with the packages you kept from the list above. -sudo apt purge nvidia-driver-580-open nvidia-dkms-580-open <...> - -sudo tee /etc/modprobe.d/blacklist-nvidia.conf > /dev/null <<'EOF' -blacklist nouveau -blacklist nvidia -blacklist nvidia_drm -blacklist nvidia_modeset -blacklist nvidia_uvm -blacklist nvidia_peermem -EOF - -# -k all rebuilds EVERY installed kernel's initramfs (plain -u touches -# only the running kernel), so a just-upgraded kernel also boots with -# the blacklist and cannot re-claim the GPU. -sudo update-initramfs -u -k all -sudo reboot -``` - -After the reboot, confirm the host is clean. The init container exits non-zero after detecting a host driver, so both DaemonSet pods sit in `Init:CrashLoopBackOff` and **will retry on their own** — deleting them just skips the up-to-5-minute backoff window: - -```bash -# Should print nothing. -lsmod | grep -E '^(nvidia|nouveau)' - -# command -v matches what isHostDriver does (PATH lookup inside the -# chroot), so it also catches /usr/local/bin/nvidia-smi left by a .run -# or CUDA-toolkit install. Prints "ok: gone" on success. -command -v nvidia-smi >/dev/null && echo "STILL PRESENT — purge incomplete" || echo "ok: gone" - -# A leftover DKMS module rebuilds nvidia.ko on the next kernel update -# and an explicit modprobe bypasses the blacklist — should print nothing. -dkms status | grep -i nvidia - -# Skip the CrashLoopBackOff backoff window by deleting the stuck pods. -# The DaemonSet labels are operator-managed and not stable across -# gpu-operator versions, so delete by name pattern — anchored so the -# match is the two DaemonSets and nothing else. -kubectl -n cozy-gpu-operator get pods -o name \ - | grep -E '^pod/(nvidia-vfio-manager|nvidia-sandbox-validator)-' \ - | xargs -r kubectl -n cozy-gpu-operator delete -``` - -Within a couple of minutes `vfio-manager` should bind every target GPU to `vfio-pci` and the node's `allocatable` will gain the registered resource: - -```bash -lspci -nnk -d 10de: | grep 'Kernel driver in use' -# Kernel driver in use: vfio-pci - -kubectl get nodes -o jsonpath='{range .items[*]}{.metadata.name}{": "}{.status.allocatable}{"\n"}{end}' | grep nvidia.com -``` - -One label is **not** cleaned up automatically. The init container set `nvidia.com/gpu.deploy.driver=pre-installed`, and the operator's success path restores only the operand labels — it never resets this one (`rescheduleGPUOperatorComponents` in `k8s-driver-manager` v0.10.0 touches the validator / toolkit / device-plugin / etc. labels, not `deploy.driver`). So the node keeps `pre-installed` indefinitely: it is the same label the Symptom section uses as evidence, and it would disable the containerized-driver DaemonSet if the node later switches to the `container` workload. Clear it once recovery is confirmed: - -```bash -# Nothing on the success path resets this label; clear it so it does not -# mislead future debugging or block a later container-workload switch. -kubectl label node nvidia.com/gpu.deploy.driver- -``` - -### Known limitation - -The skip-on-pre-installed behavior lives in the upstream [`NVIDIA/k8s-driver-manager`](https://github.com/NVIDIA/k8s-driver-manager) Go binary at `cmd/driver-manager/main.go`: the method `(*DriverManager).isHostDriver` is called from `(*DriverManager).uninstallDriver` and has no in-band opt-out in `:v0.10.0`. `FORCE_REINSTALL` exists as an env / CLI flag in the same binary but gates the later "same-config already loaded" branch inside `uninstallDriver`, not the `isHostDriver` short-circuit. Hosts that need to keep the NVIDIA host driver installed for non-Kubernetes workloads cannot currently share the same GPU with the passthrough variant. Two mitigation paths: - -- **`container` variant** — a third variant of `cozystack.gpu-operator` that targets the apt-installed-driver host shape and exposes GPUs to pods (not VMs) without unbinding the host driver. Available now, and selectable from platform values with `bundles.iaas.gpuOperatorVariant: container`. It solves the host-driver conflict by giving up VM passthrough, so it is a mitigation only for workloads that can run in a pod. -- **Upstream override** — an env-var override of `isHostDriver` is the only structural fix that would let the passthrough variant coexist with a host driver. Not available today; requested in [NVIDIA/k8s-driver-manager#191](https://github.com/NVIDIA/k8s-driver-manager/issues/191). - -## Building the vGPU Manager image - -The proprietary vGPU Manager driver must be obtained from NVIDIA and packaged into a container image that the gpu-operator chart pulls — it is not installed from a raw `.run` at runtime. NVIDIA owns this build path; their [`gpu-driver-container`](https://github.com/NVIDIA/gpu-driver-container) repository ships per-OS Dockerfiles under `vgpu-manager//` and is the source of truth for build args, base images, and supported OS releases. Follow the README in that repository. - -The proprietary `.run` is the **Linux KVM** variant (not the Ubuntu KVM `.deb`, which ships pre-built modules for stock kernels only). It comes from the [NVIDIA Licensing Portal](https://ui.licensing.nvidia.com) under an NVIDIA AI Enterprise / vGPU subscription. - -> **EULA:** never push the resulting image to a publicly readable registry. Use a private registry (in-cluster Harbor works well as a non-proxy project). - -## Deploying with the vgpu variant - -The platform's `iaas` bundle deploys the gpu-operator Package CR when `cozystack.gpu-operator` is in `bundles.enabledPackages` and `bundles.iaas.gpuOperatorVariant: vgpu` is set. The vGPU Manager image is proprietary and not redistributable, so the bundle does not ship a default tag — the operator builds the container per the upstream [`gpu-driver-container`](https://github.com/NVIDIA/gpu-driver-container) recipe and supplies the private-registry coordinates through platform values: - -```yaml -bundles: - iaas: - enabled: true - gpuOperatorVariant: vgpu - enabledPackages: - - cozystack.gpu-operator - -gpu: - vgpuManager: - repository: registry.example.com/nvidia - image: vgpu-manager - version: "595.58.02-ubuntu24.04" - # imagePullSecrets lives per-component (vgpuManager, driver, - # validator, dcgmExporter, …). The value is a list of strings, - # not [{name: ...}]. - imagePullSecrets: - - nvidia-registry-secret -``` - -The platform forwards `gpu.vgpuManager` into the emitted gpu-operator Package CR's `components.gpu-operator.values.gpu-operator.vgpuManager`, so the bundle handles the variant + image coordinates in one place. If you need to override anything else on the gpu-operator chart (driver, validator, dcgmExporter, custom node selectors), hand-craft a `Package` CR named `cozystack.gpu-operator` with the full `components.gpu-operator.values` block and put that name in `bundles.disabledPackages`. A hand-written Package CR does not take precedence over the bundle: as long as the platform emits its own copy of that package, the next platform render replaces whatever you wrote. - -The `nvidia-registry-secret` should be a docker-registry Secret created beforehand in `cozy-gpu-operator`. - -Verify the DaemonSet is running and `nvidia.ko` loads on every GPU node: - -```bash -kubectl -n cozy-gpu-operator get pods -l app=nvidia-vgpu-manager-daemonset -kubectl -n cozy-gpu-operator exec -it -- nvidia-smi -``` - -`nvidia-smi` should enumerate the physical GPUs and report `Host VGPU Mode : SR-IOV`. - -## Profile assignment (SR-IOV path) - -> **The `vgpu` variant is experimental on Ada+ and ships without a profile-assignment loop.** NVIDIA's `vgpu-device-manager` walks `/sys/class/mdev_bus/`, which does not exist on Ada+ — the DaemonSet errors with "no parent devices found for GPU at index '0'" and is therefore disabled by default in `values-vgpu.yaml`. Until an SR-IOV-aware controller is shipped, profile assignment is an out-of-band step that must be re-applied after every node reboot (`current_vgpu_type` resets to 0 on PCIe re-enumeration). Without this step, `permittedHostDevices.pciHostDevices` will report zero allocatable resources and no VM can request the vGPU. **Do not deploy the `vgpu` variant in production until you have an automated profile-assignment mechanism in place** — typically a small DaemonSet that reads a ConfigMap (` = `) and writes the corresponding `current_vgpu_type` files at boot. - -Once `nvidia.ko` is loaded the driver enables SR-IOV (16 VFs per L40S by default). Each VF needs a vGPU profile written to its sysfs: - -```bash -# from inside the nvidia-vgpu-manager-daemonset pod (privileged, hostPID) -echo 1155 > /sys/bus/pci/devices/0000:02:00.5/nvidia/current_vgpu_type -``` - -The numeric profile ID can be discovered per-VF: - -```bash -cat /sys/bus/pci/devices/0000:02:00.5/nvidia/creatable_vgpu_types -``` - -For Pascal–Ampere GPUs (V100, T4, A100, A30) the mdev model still applies. Flip `vgpuDeviceManager.enabled: true` in your Package CR overrides — NVIDIA's device manager works correctly there. - -## KubeVirt configuration - -When `cozystack.gpu-operator` is in `bundles.enabledPackages` (and not also in `bundles.disabledPackages`), the platform mirrors the chosen GPU variant into the `KubeVirt` CR automatically. There is no manual `kubectl patch` step. This applies to the two VM variants only: `container` serves GPUs to pods and never to VMs, so selecting it emits the gpu-operator Package with no host-device wiring on the KubeVirt side. - -If you opt out of bundle management and hand-craft a `cozystack.gpu-operator` Package CR directly — typically to apply overrides the bundle does not expose (driver settings, custom node selectors, validator / dcgmExporter tweaks, etc.) — the platform does NOT auto-wire `HostDevices` or `permittedHostDevices` into the KubeVirt CR. In that flow you also hand-craft a `cozystack.kubevirt` Package CR with `components.kubevirt.values.extraFeatureGates: [HostDevices]` and the appropriate `permittedHostDevices` block. The escape-hatch values shape under `.gpu` (below) is intentionally documented in the bundle-managed flow only. Both hand-crafted Package CRs need their names in `bundles.disabledPackages`: the iaas bundle emits `cozystack.kubevirt` on every render and `cozystack.gpu-operator` on every render that has it in `bundles.enabledPackages`, and that render replaces the hand-written spec rather than merging with it. - -- `developerConfiguration.featureGates` gets `HostDevices` appended (current KubeVirt splits this from the `GPU` gate; the admission webhook rejects `spec.template.spec.domain.devices.hostDevices` without it). -- `permittedHostDevices.pciHostDevices` is filled from `packages/core/platform/files/gpu-passthrough-defaults.yaml` when `bundles.iaas.gpuOperatorVariant: default` (the package default) and `gpu.replaceDefaults` is left at `false`. The table covers Hopper (H100/H200), Ada Lovelace (L4/L40/L40S), Ampere (A100 PCIe/SXM, A40, A30, A10), Turing (T4), Volta (V100/V100S). All entries carry `externalResourceProvider: true` because the resource names come from `nvidia-sandbox-device-plugin`, not from KubeVirt's in-tree device plugin. -- `permittedHostDevices.mediatedDevices` is filled from `packages/core/platform/files/gpu-vgpu-defaults.yaml` when `bundles.iaas.gpuOperatorVariant: vgpu` **and** `gpu.vgpuDeviceManager.enabled: true` — that knob defaults to `false`, so a stock vgpu cluster ships no mdev table at all (see the Ada Lovelace / Blackwell note below for why). `gpu.replaceDefaults: true` also suppresses it. This list only EXPOSES, by profile name (`mdevNameSelector`), mdevs that the GPU Operator's vGPU Device Manager CREATES on the node; the platform does not ship a numeric `mediatedDevicesConfiguration` default (those `nvidia-NNN` type ids are per-SKU/driver sysfs indices with no portable value — set `.gpu.mediatedDevicesConfiguration` yourself, with host-verified ids, only if you want KubeVirt rather than the Device Manager to create mdevs). The starter set covers Pascal–Ampere mdev profiles (A100-40C/80C, A40-24Q/48Q, A30-24C, A10-24Q, V100D-32C, T4-16Q) — the same family range as the upstream `vgpu-device-manager` walks `/sys/class/mdev_bus/` for. Ada Lovelace / Blackwell SR-IOV vGPU is out of scope for the chart's default list; advertise those VFs via the user-override hook below. - -### Extending or replacing the default table - -The platform exposes three knobs under `.gpu`: - -```yaml -gpu: - # Extend the platform defaults with cluster-specific entries. Read by - # the two VM variants only; the container variant reads neither key. - # pciHostDevices is read in both of them — it feeds the passthrough - # (vfio-pci) path AND the post-kubevirt#16890 SR-IOV vGPU VF path on - # Ada Lovelace / Blackwell. mediatedDevices is read in vgpu alone, for - # the pre-#16890 mdev path on Pascal–Ampere; the passthrough variant - # ignores it. Both render into the same KubeVirt CR. - permittedHostDevices: - pciHostDevices: - - pciVendorSelector: "10DE:26B9" # L40S, advertised as a VF for SR-IOV vGPU - resourceName: nvidia.com/L40S-24Q - # externalResourceProvider is intentionally omitted here: after - # kubevirt/kubevirt#16890, virt-handler's in-tree device plugin - # advertises the resource directly, no sandbox plugin in the loop. - mediatedDevices: [] - # mediatedDevicesConfiguration makes KubeVirt itself create mdevs (vgpu mode). No platform default: mdev creation is normally delegated to the vGPU Device Manager (name-based), and these mediatedDeviceTypes are host/driver-specific nvidia-NNN sysfs indices (look yours up via /sys/bus/pci/devices//mdev_supported_types/*/name). Set this only to opt into KubeVirt-driven creation; mergeOverwrite REPLACES a supplied top-level key wholesale. - mediatedDevicesConfiguration: {} - # Wipe the platform defaults entirely and ship only the cluster's - # curated lists. Useful for non-NVIDIA-only clusters and strict - # allowlist requirements. - replaceDefaults: false -``` - -`replaceDefaults: false` (the default) appends user entries to the NVIDIA defaults. `replaceDefaults: true` drops the NVIDIA table entirely — if you don't then supply your own pciHostDevices / mediatedDevices list, the rendered KubeVirt CR has no `permittedHostDevices` block and the admission webhook will reject every GPU VM. - -### Notes on `nvidia-sandbox-device-plugin` resource names - -The `resourceName` strings in `gpu-passthrough-defaults.yaml` are what `nvidia-sandbox-device-plugin` (`nvcr.io/nvidia/kubevirt-gpu-device-plugin`) advertises: it derives each slug mechanically from the device's PCI-IDs database name by uppercasing it, turning `/`, `.` and whitespace into `_`, and stripping the remaining non-alphanumerics (the `[` / `]`). So `TU104GL [Tesla T4]` becomes `nvidia.com/TU104GL_TESLA_T4` and `GA100GL [A30 PCIe]` becomes `nvidia.com/GA100GL_A30_PCIE` — the slug carries every token the PCI-IDs string holds (the `GL` die suffix, the `Tesla` brand on Turing/Volta, form factor, memory), not a tidy `_`. The names track the pci.ids snapshot bundled in the plugin image, so a different plugin build can publish a different string — check with `kubectl describe node | grep nvidia.com/` and override via `.gpu.permittedHostDevices.pciHostDevices` (or wipe the table with `replaceDefaults: true` and curate it yourself). PCI vendor:device IDs themselves are stable across driver versions. - -### SR-IOV PF vs VF (Ada Lovelace and newer) - -On L40S (and other Ada-Lovelace cards) the SR-IOV VFs report the same PCI device ID as the PF — `lspci -nn -d 10de:` on the host shows both as `[10de:26b9]`. `virt-handler` distinguishes them by `is-VF + has-vGPU-profile`, so a single `pciVendorSelector` matches the right set. Verify on your specific GPU before assuming this — some other generations split PF/VF IDs. - -`externalResourceProvider: true` is **not** required when the resource is advertised by `virt-handler`'s in-tree device plugin (the SR-IOV path post kubevirt#16890). The platform passthrough defaults include the flag because that path is driven by the external sandbox plugin. - -### Verifying allocatable capacity - -```bash -kubectl get nodes -o jsonpath='{range .items[*]}{.metadata.name}{": "}{.status.allocatable.nvidia\.com/L40S-24Q}{"\n"}{end}' -``` - -## Licensing (DLS) - -vGPU 17/20 uses the NVIDIA Delegated License Service. The legacy `ServerAddress=` / `ServerPort=7070` lines in `gridd.conf` are no longer authoritative — `nvidia-gridd` (running **inside the guest**) reads the DLS endpoint from the ClientConfigToken file directly. - -The host vGPU Manager DaemonSet does not request a license — it only enables SR-IOV and loads `nvidia.ko`. Licensing is consumed entirely by the guest. The gpu-operator chart's `driver.licensingConfig.secretName` would mount the Secret into the **driver pod on the host**, where it has no effect for SR-IOV vGPU; do not wire the licensing Secret through it. - -Instead, deliver the token and `gridd.conf` to the guest via cloud-init or a containerDisk overlay: - -```yaml -# inside the VirtualMachine cloudInitNoCloud userData -write_files: -- path: /etc/nvidia/ClientConfigToken/client_configuration_token.tok - # 0744 follows NVIDIA's recommendation in the Virtual GPU Software - # Licensing User Guide ("Configuring a Licensed Client on Linux"): - # nvidia-gridd does not necessarily run as the file owner. - # https://docs.nvidia.com/vgpu/latest/grid-licensing-user-guide/ - permissions: '0744' - encoding: b64 - content: -- path: /etc/nvidia/gridd.conf - permissions: '0644' - content: | - # FeatureType selects which vGPU Software license the guest requests. - # 0 — unlicensed state (no license requested; Q profiles run in - # reduced mode after the grace period). - # 1 — NVIDIA vGPU. The driver auto-selects the correct license - # type from the configured vGPU profile (Q → vWS, B → vPC, - # A → vCS / Compute). Use this for SR-IOV vGPU profiles. - # 2 — explicitly NVIDIA RTX Virtual Workstation. - # 4 — explicitly NVIDIA Virtual Compute Server. - FeatureType=1 -``` - -Verify activation inside the guest: - -```bash -nvidia-smi -q | grep 'License Status' -# License Status : Licensed -``` - -If the guest reports `Unlicensed (Unrestricted)` for more than a couple of minutes, check `journalctl _COMM=nvidia-gridd` for handshake errors against the DLS endpoint baked into the token. - -### Migrating from chart v25.x - -Operators upgrading from the previous Cozystack release (gpu-operator chart v25.3.0) should also note that the upstream chart deprecated `driver.licensingConfig.configMapName` in favour of `driver.licensingConfig.secretName`. The old key still works but emits a deprecation warning at render time. If your existing `Package` CR set the licensing reference via `configMapName`, switch it to `secretName` on this upgrade — the Secret content (`gridd.conf` and the ClientConfigToken) does not need to change. This applies to passthrough deployments that drove host-side licensing through the gpu-operator chart; SR-IOV vGPU does not consume the host-side licensing knob at all (see "Licensing (DLS)" above). - -## Sample VirtualMachine - -Either `hostDevices` or `gpus` accepts the resource (the upstream KubeVirt API resolves both PCI and mediated-device pools), but the convention is to use `hostDevices` for VF-style PCI passthrough: - -```yaml -apiVersion: kubevirt.io/v1 -kind: VirtualMachine -metadata: - name: vgpu-smoke - namespace: tenant-example -spec: - runStrategy: Always - template: - spec: - domain: - cpu: - cores: 4 - memory: - guest: 8Gi - devices: - disks: - - name: rootdisk - disk: - bus: virtio - interfaces: - - name: default - masquerade: {} - hostDevices: - - name: gpu0 - deviceName: nvidia.com/L40S-24Q - networks: - - name: default - pod: {} - volumes: - - name: rootdisk - # A 2.4 GiB containerDisk overlay is too small to install - # the GRID guest driver in-place. Use a CDI DataVolume of - # 20 GiB+ in production. - containerDisk: - image: quay.io/containerdisks/ubuntu:24.04 -``` - -Inside the guest, install the GRID driver from the `.run` (the GUEST `.run`, distinct from the host `vgpu-kvm` package), then `nvidia-smi` should report the configured profile: - -```text -| 0 NVIDIA L40S-24Q Off | 00000000:0E:00.0 Off | 0 | -| 17 MiB / 24576 MiB P0 Default | -``` - -## Profile reference (L40S) - -L40S supports the full Q (RTX vWS), B (vPC), A (vCS / Compute) profile families. The numeric IDs come from the driver and are visible in `creatable_vgpu_types`: - -| Profile | Frame Buffer | Max instances per L40S | Use case | -| --- | --- | --- | --- | -| L40S-1Q | 1 GB | 48 | Light 3D / VDI | -| L40S-2Q | 2 GB | 24 | Medium 3D / VDI | -| L40S-4Q | 4 GB | 12 | Heavy 3D / VDI | -| L40S-6Q | 6 GB | 8 | Professional 3D | -| L40S-8Q | 8 GB | 6 | AI / ML inference | -| L40S-12Q | 12 GB | 4 | AI / ML training | -| L40S-24Q | 24 GB | 2 | Large AI workloads | -| L40S-48Q | 48 GB | 1 | Full GPU equivalent | - -Other GPU families have analogous tables in the [NVIDIA Virtual GPU Software Documentation](https://docs.nvidia.com/grid/latest/grid-vgpu-user-guide/). - -## OS support summary - -The `container` variant column assumes the host already ships the NVIDIA driver and `nvidia-container-toolkit` via the distro package manager, with the `nvidia` runtime registered in containerd (`nvidia-ctk runtime configure --runtime=containerd`). With `driver.enabled=false` the operator uses the pre-installed host driver at its standard location, so a stock apt install needs no `hostPaths.driverInstallDir` override. Talos installs the driver under a non-standard prefix, so the operator does not find it at the default location — see `packages/system/gpu-operator/examples/` for the Talos-specific path with a compat DaemonSet and an explicit `hostPaths.driverInstallDir` override. - -| Host OS | passthrough (`default`) | vGPU (`vgpu`) | container (`container`) | -| --- | --- | --- | --- | -| Ubuntu 24.04 | ⚠️ supported upstream, but the host must be clean of any apt-installed NVIDIA driver — see ["Passthrough variant: host preparation"](#passthrough-variant-host-preparation) | ✅ supported upstream (`vgpu-manager/ubuntu24.04`) | ✅ apt-installed driver + nvidia-container-toolkit | -| Ubuntu 22.04 | ⚠️ same clean-host requirement as 24.04 | ✅ | ✅ | -| Ubuntu 20.04 | ⚠️ same clean-host requirement as 24.04 | ✅ | ✅ | -| Ubuntu 26.04 | ⚠️ same clean-host requirement as 24.04, plus a `nvidia-driver` patch for usr-merge (details pending) | ⚠️ same patch + own Dockerfile fork | ✅ | -| Talos Linux | ✅ (open `vfio-pci`; the Talos image ships no host NVIDIA stack, so the clean-host check passes trivially) | ❌ NVIDIA does not grant redistribution rights for the proprietary `.run`; we tried and the path is blocked | ⚠️ host driver lands in a non-standard prefix — use `examples/values-native-talos.yaml` (compat DaemonSet + `hostPaths.driverInstallDir` override) as a starting point instead | diff --git a/docs/hubble-observability.md b/docs/hubble-observability.md deleted file mode 100644 index 33597eec3..000000000 --- a/docs/hubble-observability.md +++ /dev/null @@ -1,99 +0,0 @@ -# Enabling Hubble for Network Observability - -Hubble is a network and security observability platform built on top of Cilium. It provides deep visibility into the communication and behavior of services in your Kubernetes cluster. - -## Prerequisites - -- Cozystack platform running with Cilium as the CNI -- Monitoring hub enabled for Grafana access - -## Configuration - -Hubble is disabled by default in Cozystack. To enable it, update the Cilium configuration. - -### Enable Hubble - -Edit the Cilium values in your platform configuration to enable Hubble: - -```yaml -cilium: - hubble: - enabled: true - relay: - enabled: true - ui: - enabled: true - metrics: - enabled: - - dns - - drop - - tcp - - flow - - port-distribution - - icmp - - httpV2:exemplars=true;labelsContext=source_ip,source_namespace,source_workload,destination_ip,destination_namespace,destination_workload,traffic_direction -``` - -### Components - -When Hubble is enabled, the following components become available: - -- **Hubble Relay**: Aggregates flow data from all Cilium agents -- **Hubble UI**: Web-based interface for exploring network flows -- **Hubble Metrics**: Prometheus metrics for network observability - -## Grafana Dashboards - -Once Hubble is enabled and the monitoring hub is deployed, the following dashboards become available in Grafana under the `hubble` folder: - -| Dashboard | Description | -|-----------|-------------| -| **Overview** | General Hubble metrics including processing statistics | -| **DNS Namespace** | DNS query and response metrics by namespace | -| **L7 HTTP Metrics** | HTTP layer 7 metrics by workload | -| **Network Overview** | Network flow overview by namespace | - -### Accessing Dashboards - -1. Navigate to Grafana via the monitoring hub -2. Browse to the `hubble` folder in the dashboard browser -3. Select a dashboard to view network observability data - -## Metrics Available - -Hubble exposes various metrics that can be queried in Grafana: - -- `hubble_flows_processed_total`: Total number of flows processed -- `hubble_dns_queries_total`: DNS queries by type -- `hubble_dns_responses_total`: DNS responses by status -- `hubble_drop_total`: Dropped packets by reason -- `hubble_tcp_flags_total`: TCP connections by flag -- `hubble_http_requests_total`: HTTP requests by method and status - -## Troubleshooting - -### Verify Hubble Status - -Check if Hubble is running: - -```bash -kubectl get pods -n cozy-cilium -l k8s-app=hubble-relay -kubectl get pods -n cozy-cilium -l k8s-app=hubble-ui -``` - -### Check Metrics Endpoint - -Verify Hubble metrics are being scraped: - -```bash -kubectl port-forward -n cozy-cilium svc/hubble-metrics 9965:9965 -curl http://localhost:9965/metrics -``` - -### Verify ServiceMonitor - -Ensure the ServiceMonitor is created for Prometheus scraping: - -```bash -kubectl get servicemonitor -n cozy-cilium -``` diff --git a/docs/oidc-grafana.md b/docs/oidc-grafana.md deleted file mode 100644 index b65931dd4..000000000 --- a/docs/oidc-grafana.md +++ /dev/null @@ -1,410 +0,0 @@ -# OIDC for the Grafana instance (Phase 1) - -Cozystack ships one Grafana codebase deployed twice: as -`monitoring-system` in the platform's `cozy-monitoring` namespace and as -`monitoring` in every tenant namespace. Both instances opt in to OIDC -authentication through the same flat selector on the `Monitoring` CR. -This document covers the operator-facing surface: what the modes mean, -what the chart provisions, and how a user signs in. - -The architectural rationale lives in -[cozystack/community#24](https://github.com/cozystack/community/pull/24) -— in particular why per-tenant Keycloak realms are deliberately -deferred to Phase 2. This Grafana integration follows the same shape -as the tenant kube-apiserver's Phase 1 -([cozystack/cozystack#3044](https://github.com/cozystack/cozystack/pull/3044)), -adapted for a server-side (confidential) OAuth client instead of a -public kubectl one: authentication is wired up by the chart, but -authorization is an operator-supplied `users:` map reconciled into -the target (Grafana orgs here, ClusterRoleBindings in #3044) by a -chart-owned Job. The chart does not own any directory objects. - -## Selector - -```yaml -apiVersion: apps.cozystack.io/v1alpha1 -kind: Monitoring -metadata: - name: monitoring - namespace: tenant-acme -spec: - oidc: - mode: System # System | CustomConfig | None (default) - users: - - email: alice@acme.example - role: Admin - - email: bob@acme.example - role: Viewer -``` - -Three modes: - -- **None** — the only user-facing path is the `grafana-admin-password` - Secret, exposed to the tenant through - `packages/system/monitoring-rd`. This is the default; existing - instances render byte-identical to before. -- **System** — the Grafana instance trusts the platform `cozy` Keycloak - realm via a per-instance confidential client. Users are the ones a - platform admin already provisioned in `cozy`; the tenant does not - manage a directory of its own. -- **CustomConfig** — Grafana trusts a tenant-supplied OIDC issuer - directly. `cozy` is not in the path. Use for BYO IdPs (Okta, Auth0, - a customer's own Keycloak). - -The `grafana-admin-password` Secret stays a documented break-glass -path in every mode; `disable_login_form` is not flipped by this -selector. Hardening that further (e.g. locking the form off in -`System` mode) is a follow-up. - -## System mode - -What the chart provisions, in the release namespace of the Monitoring -CR: - -1. **KeycloakClient** named `-` in the `cozy` - realm — `public: false`, `directAccess: false`. The `secret` field - points at a chart-owned Kubernetes Secret via the EDP-Keycloak - `$:` syntax so the operator provisions the same - confidential secret to Keycloak that Grafana reads at runtime. - `redirectUris` is locked to - `https://grafana./login/generic_oauth`. -2. **KeycloakClientScope** named `--audience` - carrying an `oidc-audience-mapper` that pins `id_token.aud` to the - per-instance clientId. This is the per-instance isolation - primitive: a token minted for one Monitoring release is rejected - by another's Grafana. -3. A **Secret** `-oidc-client` carrying a random 32-char - `client-secret`. Generated on first install (`lookup` + random - fallback, same pattern as `packages/system/dashboard`), preserved - across upgrades. -4. The Grafana CR's `spec.config.auth.generic_oauth` section wired to - the platform realm issuer (`cozy` by default, `authentication.oidc.realmName`) + the per-instance audience scope. Two - independent gates ride on top of the raw OAuth wiring: - - **Tenant-membership gate — unconditional in System mode.** The chart - requests the `groups` OIDC scope (already provisioned platform-wide - by `packages/system/keycloak-configure` as a realm-default - KeycloakClientScope with an `oidc-group-membership-mapper`) and sets - - ``` - allowed_groups = -view -use -admin -super-admin - groups_attribute_path = groups - ``` - - `groups_attribute_path` is REQUIRED alongside `allowed_groups` on - Grafana v11.x+: without it Grafana leaves the extracted - `user.Groups` slice empty regardless of what the userinfo endpoint - returns, and the gate rejects every login with "user not a member - of one of the required groups" — even when the token carries the - correct claim (verified end-to-end on dev3 with Grafana v11.6.15). - The JMESPath expression `groups` reads the top-level `groups` - array from userinfo, matching the shape Keycloak's - `oidc-group-membership-mapper` emits. - - The four groups match the KeycloakRealmGroups the tenant chart - provisions in the `cozy` realm — see - `packages/apps/tenant/templates/keycloakgroups.yaml`. Grafana - rejects any login whose token does not carry at least one of these - groups. This is the isolation primitive that stops tenant-alice - from signing into tenant-bob's Grafana even though both authenticate - against the same flat `cozy` realm. The audience mapper in point 2 - protects against *replay* of a minted token across releases; this - gate protects against *issuance* of a usable token to a caller - outside the release's tenant. - - **Users-map contract — active only when `spec.oidc.users` is - non-empty.** Three additional keys are merged on top: - - `skip_org_role_sync = true` — a login never overwrites the - users-Job's role assignments; - - `oauth_allow_insecure_email_lookup = true` — the OIDC identity - binds to the pre-provisioned local account by email; - - `allow_sign_up = false` — a cozy-realm identity whose email is - NOT in `spec.oidc.users` is rejected at login (even if they are - a tenant member and pass the group gate) instead of being - admitted as `auto_assign_org_role` Viewer and waiting for the - next helm-upgrade prune pass to clean them up. - - When `spec.oidc.users` is empty (or unset) the three users-map - keys are NOT forced. The tenant-membership gate still applies, so - only tenant members can log in — they land at Grafana's - `auto_assign_org_role` default (`Viewer`). This is the intended - hands-off contract: the chart owns nothing app-side, but the - Keycloak-layer gate still isolates the release. Cross-tenant - users are rejected outright; in-tenant users get a self-service - Viewer with no org-role management by the chart. -5. A `GF_AUTH_GENERIC_OAUTH_CLIENT_SECRET` env on the Grafana - Deployment sourced from the Secret in step 3. -6. A post-install/post-upgrade **users-Job** — see the "Users and - RBAC" section — that reconciles `spec.oidc.users` into Grafana's - Main Org. - -No `KeycloakRealmGroup`s and no `role_attribute_path`. Directory -objects (users, groups, group memberships) stay owned by whoever -operates the `cozy` realm; the Monitoring release only requests -authentication wiring, it does not act as a user directory. - -Server-level `GrafanaAdmin` promotion (`allow_assign_grafana_admin`) -is out of scope for Phase 1. All Grafana instances — platform and -tenant — cap at org-level `Admin`. - -## CustomConfig mode - -The tenant supplies the entire `[auth.generic_oauth]` payload. Two -paths: - -```yaml -spec: - oidc: - mode: CustomConfig - customConfig: - config: - client_id: my-grafana - client_secret: xxxxxxxx - auth_url: https://idp.acme.example/protocol/openid-connect/auth - token_url: https://idp.acme.example/protocol/openid-connect/token - api_url: https://idp.acme.example/protocol/openid-connect/userinfo - scopes: openid email profile -``` - -…or via an existing Secret in the tenant namespace whose `auth.ini` -key holds a ready-made `[auth.generic_oauth]` fragment: - -```yaml -spec: - oidc: - mode: CustomConfig - customConfig: - secretRef: - name: acme-byo-grafana-auth -``` - -When `spec.oidc.users` is non-empty the chart merges three settings -on top of the operator's inline map so the users-Job contract holds -in `CustomConfig` mode too: - -- `skip_org_role_sync = true` — a login never overwrites the Job's - org-role assignments; -- `oauth_allow_insecure_email_lookup = true` — the OIDC identity - binds to the pre-provisioned local account by email; -- `allow_sign_up = false` — an OIDC identity whose email is not in - the users-map is rejected at login instead of being admitted with - the default `auto_assign_org_role`. - -All three keys are chart-forced (`merge` semantics, chart wins) — -setting them in the operator's map is a no-op, and -`role_attribute_path` would just be dead config since the Job -manages roles. - -When `spec.oidc.users` is empty (or unset) the chart forces none of -the three keys — a BYO-IdP operator who does not use the users-map -gets their inline `auth.generic_oauth` applied verbatim. This -matters because `oauth_allow_insecure_email_lookup` against a BYO -issuer that does not verify emails is a needless account-linking -surface, and `allow_sign_up = false` with no pre-provisioned -accounts would lock everyone out. If you want the isolation -posture without the users-map, set the keys explicitly in your -inline map. - -**`secretRef.name` mode disables the users-map.** The chart mounts the -operator's `auth.ini` fragment verbatim via `GF_PATHS_CUSTOM_INI` and -cannot inject either of the two chart-forced settings. Setting -`spec.oidc.users` alongside `customConfig.secretRef.name` fails the -render with an explicit message — the alternatives are: (a) use -`customConfig.config` (inline) and let the chart merge, or (b) leave -`spec.oidc.users` empty and include both `skip_org_role_sync = true` -and `oauth_allow_insecure_email_lookup = true` in your ini fragment -plus manage the OIDC → Grafana user mapping yourself. - -Setting both `config` and `secretRef.name` (or neither) fails the -render. In `CustomConfig` mode no Keycloak objects are provisioned in -`cozy` and no chart-owned client-secret Secret is created — the -operator manages their own credentials end-to-end. - -## Users and RBAC - -Grafana's built-in identity model exposes three org-level roles: -`Admin` / `Editor` / `Viewer`. The chart drives them from an -operator-supplied map on the CR: - -```yaml -spec: - oidc: - users: - - email: alice@acme.example - role: Admin - - email: bob@acme.example - role: Editor - - email: carol@acme.example - role: Viewer -``` - -A chart-owned Job runs on every `helm install` / `helm upgrade` and -reconciles that list into Main Org. membership via Grafana's admin -API: - -1. Each listed email gets a pre-provisioned local Grafana account - with a random password. The account is a shell; the operator - never uses that password. When they sign in with the OIDC flow - Grafana looks up the pre-provisioned account by email - (`oauth_allow_insecure_email_lookup = true`) and attaches the - OIDC identity to it. -2. Each listed email is added to Main Org. with the requested role. - Re-runs of the Job converge role changes (`Editor` → `Admin`, - demotions, etc.) via `PATCH /api/orgs/{orgId}/users/{userId}`. -3. Every Main-Org member whose email is neither in the list nor the - break-glass `grafana-admin-password` login is removed. Removing - an entry from `users:` and re-reconciling revokes access. - -The Job renders only when **both** `mode != None` and -`spec.oidc.users` is non-empty. Three empty-users states all resolve -to the same hands-off contract — the chart owns nothing in Grafana -orgs: - -- `mode: None` — OIDC is off, no chart-managed org membership at - all. This matters on upgrade: existing tenants who ran the - pre-PR Monitoring chart may have added users to Grafana manually - through the UI; if the Job ran in `mode: None` its prune pass - would silently delete those accounts on the next Flux reconcile. -- `customConfig.secretRef` — the users-map is forbidden by the - render-time assert; the operator's mounted `auth.ini` fragment is - authoritative. -- `mode: System | CustomConfig-inline` with `users:` unset — the - operator opted into OIDC but not into the chart-managed users-map; - they manage org membership themselves. - -Setting `users: [...]` on the CR means the chart owns Main-Org -membership — anything added by hand (Grafana UI, admin API, other -tooling) gets pruned on the next reconcile. The reverse edge is -worth calling out: taking `users:` back to `[]` (or unsetting it) -does NOT prune the last entry — the chart stops managing membership -and any accounts the Job provisioned are left in place. Operators -who want to clean up OIDC-provisioned accounts after switching -`System | CustomConfig → None` (or after emptying `users:`) do it -themselves through the Grafana UI or admin API. The -`activeDeadlineSeconds` and `ttlSecondsAfterFinished` notes below -only apply when the Job actually renders. - -While the users-map is active, users NOT listed in `spec.oidc.users` -who try to log in through OIDC are rejected at the door -(`allow_sign_up = false`) — no account is minted, no default -`Viewer` role is assigned. `skip_org_role_sync = true` in the -Grafana config additionally makes sure the Job's assignments -outlive the next login for users who ARE listed. - -For `System` mode, the operator provisions the corresponding -Keycloak user in `cozy` in whatever way they already do (Keycloak -UI, a `KeycloakRealmUser` CR, an identity broker) and adds them to -one of the tenant's `-{view,use,admin,super-admin}` -groups — Grafana's `allowed_groups` rejects the login otherwise. -The Monitoring release does not create Keycloak users and does not -provision `KeycloakRealmGroup`s — group directory ownership stays -with the tenant chart (`packages/apps/tenant`); group membership is -curated by whoever operates the `cozy` realm. - -## How a user logs in - -The user opens `https://grafana.` in a browser and picks the -"Sign in with Keycloak" button under the login form. Grafana runs the -Authorization Code + PKCE flow against the cozy realm, receives a -token whose `aud` claim matches this Monitoring instance's clientId, -and — if the user's email is in `spec.oidc.users` — binds the OIDC -identity to the pre-provisioned local account with the role the Job -already set. - -If the user's email is not in `spec.oidc.users` (and the users-map -is active — `mode != None` and the list is non-empty) the login is -refused by Grafana at the OAuth callback — `allow_sign_up = false` -does not mint an account for them. Add them to `spec.oidc.users` -and re-apply the CR; the Job will run on the next helm-upgrade, -pre-provision their local account, and the next login attempt will -succeed. When the users-map is inactive Grafana's default -`allow_sign_up = true` applies and any authenticated cozy-realm -identity lands with `auto_assign_org_role` (Viewer). - -The break-glass `admin_user` / `admin_password` field on the form -stays wired to the `grafana-admin-password` Secret and continues to -work — useful when Keycloak is down or misconfigured. - -## Failure modes - -- **`mode: System` without the platform-level OIDC feature** — chart - render hard-fails: - `spec.oidc.mode: System requires the platform-level OIDC feature`. - Flip `authentication.oidc.enabled: true` in the platform values, or - switch to `CustomConfig`. On the platform side that flag also - swings the `cozystack.monitoring-application` PackageSource from - variant `default` (baseline dependsOn only) to variant `oidc` - (additionally waits for `cozystack.keycloak-operator` so the - `v1.edp.epam.com` CRDs consumed by the Keycloak-side of System - mode are registered before the monitoring chart reconciles). -- **`mode: System` without the Keycloak operator CRDs registered** — - chart render hard-fails: - `spec.oidc.mode: System requires the Keycloak operator CRDs - (v1.edp.epam.com/v1)`. Symmetric across - `templates/grafana/oidc-keycloak.yaml` and - `templates/grafana/grafana.yaml` so Grafana never comes up with an - `auth.generic_oauth` block pointing at a client that never gets - provisioned. For the platform `monitoring-system` release the - `oidc` variant's `dependsOn: cozystack.keycloak-operator` prevents - the race; for tenant releases (`Monitoring` CR with - `mode: System`) verify the keycloak-operator package is deployed - before creating the CR. -- **`CustomConfig` with an unreachable issuer or wrong claim - mappings** — Grafana rejects the callback and the login screen - shows an error; the `admin_user`/`admin_password` Secret keeps - working as break-glass. -- **User successfully logs in but sees no dashboards.** Their email - is missing from `spec.oidc.users` — no org role was assigned. - Add the entry and re-apply the CR; the users-Job runs on the - next helm-upgrade and grants access. -- **users-Job fails.** The Job caps at `activeDeadlineSeconds: 900` - and `backoffLimit: 6`. Common causes: Grafana never becomes - ready (check `kubectl -n get pods -l app=grafana`), or the - `grafana-admin-password` Secret is missing its `user`/`password` - keys. `ttlSecondsAfterFinished: 3600` keeps the failed hook Job - (and its Pod's logs) around for **one hour** after the terminal - Failed condition — check its logs with - `kubectl -n logs job/-oidc-users` inside that window. - After 1h the Kubernetes TTL controller garbage-collects the Job - and the Pod together, so grab the logs quickly; if you missed - the window, re-trigger the hook with `helm upgrade` on the - release and reproduce. -- **`emailVerified` on Keycloak users is a prescriptive requirement, - not a chart-enforced one.** The chart does not emit any - `claimValidationRules` — the layered guarantees you rely on - instead are: - 1. Provision users with `emailVerified: true` (via - `KeycloakRealmUser` or the Keycloak UI's email-verify flow) so - no unverified identity ever holds a given email. - 2. The `cozy` realm keeps Keycloak's default - `duplicateEmails: false`, so a second account cannot claim an - already-registered address to impersonate an existing operator. - 3. Grafana's own login flow rejects tokens the apiserver rejects, - so on the wire the same guarantee still holds through the JWT - signature and audience checks. - Adding a CEL `claimValidationRules` entry is a reasonable - follow-up hardening; it is out of scope for Phase 1. -- **`CustomConfig` with both or neither payload set** — chart render - hard-fails: `set exactly one of 'config' (inline) or - 'secretRef.name' — they are mutually exclusive`, or `CustomConfig - requires either spec.oidc.customConfig.config … or …secretRef.name`. - -## What is NOT in Phase 1 - -- **Per-tenant Keycloak realms.** Phase 2 candidate; tracked in - cozystack/community#24. -- **Full-logout through Keycloak's end-session endpoint.** - `auth.generic_oauth` native to Grafana does the OAuth part; wiring - `--backend-logout-url` and the corresponding Keycloak client - attribute is a subsequent hardening. -- **`disable_login_form: true` under `mode: System`.** Kept off so - the `admin_user`/`admin_password` Secret remains a documented - break-glass path; hardening it is a follow-up. -- **Server-level `GrafanaAdmin` promotion.** All Grafana instances - cap at org-level `Admin`. Not exposed on the CR. -- **CEL `claimValidationRules` enforcing `email_verified`.** See the - failure-modes note above. -- **Multi-issuer / BYO alongside `cozy`.** `mode: System` and - `mode: CustomConfig` are mutually exclusive on a single Monitoring - release — no composition. Follow the tenant kube-apiserver PR's - structured-config path if you need this later. diff --git a/docs/oidc-tenant.md b/docs/oidc-tenant.md deleted file mode 100644 index 7fc7fa952..000000000 --- a/docs/oidc-tenant.md +++ /dev/null @@ -1,309 +0,0 @@ -# OIDC for tenant Kubernetes clusters (Phase 1) - -Cozystack tenant Kubernetes clusters opt in to OIDC authentication on their -kube-apiserver through a flat selector on the `Kubernetes` CR. This document -covers the operator-facing surface: what the modes mean, what the chart -provisions on either end, and how to give a user kubectl access. - -The architectural rationale lives in -[cozystack/community#24](https://github.com/cozystack/community/pull/24) — -in particular why per-tenant Keycloak realms are deliberately deferred to -Phase 2. - -## Selector - -```yaml -apiVersion: apps.cozystack.io/v1alpha1 -kind: Kubernetes -metadata: - name: prod - namespace: tenant-acme -spec: - oidc: - mode: System # System | CustomConfig | None (default) - users: - - email: alice@acme.example - role: admin # admin → cluster-admin - - email: bob@acme.example - role: view # view → view -``` - -Three modes: - -- **None** — the only user-facing path is the static - `-admin-kubeconfig` Secret (the Kamaji-minted `super-admin.svc` - kubeconfig). This is the default; existing clusters render byte-identical - to before. -- **System** — the apiserver trusts the platform Keycloak realm (`cozy` by default, set via `authentication.oidc.realmName`) via a per-cluster public client. Authenticates the users already in that realm (the one cozystack provisions). Zero-config default. -- **CustomConfig** — the apiserver trusts a tenant-supplied OIDC issuer - directly. `cozy` is not in the path. Use for BYO IdPs (Okta, Auth0, a - customer's own Keycloak). - -The `users[]` map is independent of the mode and drives per-user -`ClusterRoleBinding`s inside the tenant cluster. - -## System mode - -What the chart provisions, in the management cluster: - -1. **KeycloakClient** named `-` in the `cozy` realm — - `public: true`, PKCE required, redirect URIs locked to `localhost:8000` - and `localhost:18000` (the kubelogin / `kubectl oidc-login` defaults). -2. **KeycloakClientScope** named `--audience` carrying - an `oidc-audience-mapper` that pins `id_token.aud` to the per-cluster - clientId. This is the per-cluster isolation primitive: a token minted - for cluster A is rejected by cluster B's apiserver. -3. A **Secret** `-oidc-authn-config` carrying a structured - `apiserver.config.k8s.io/v1beta1` `AuthenticationConfiguration` with - the cozy realm issuer and the per-cluster audience. -4. A `--authentication-config=` flag, mount, and volume on the - `KamajiControlPlane` referencing the Secret above. -5. A **bootstrap Job** (Helm `post-install,post-upgrade` hook) that - applies one `ClusterRoleBinding` per `users[]` entry inside the - tenant cluster and writes a ready-to-use OIDC kubeconfig Secret on - the management side (see below). -6. A `-oidc-kubeconfig` Secret in the tenant namespace carrying - a kubeconfig with a `kubectl oidc-login` exec block, exposed to the - dashboard via `packages/system/kubernetes-rd`. - -The structured authentication-config form (rather than the legacy -`--oidc-*` flags) is intentional: it accepts multiple issuers in a list, -inline private-CA PEM, and future Phase-2 issuers extend the same Secret -instead of fighting the chart shape. - -## CustomConfig mode - -The tenant supplies the entire `AuthenticationConfiguration`. Two paths: - -```yaml -spec: - oidc: - mode: CustomConfig - customConfig: - config: | - apiVersion: apiserver.config.k8s.io/v1beta1 - kind: AuthenticationConfiguration - jwt: - - issuer: - url: https://idp.acme.example - certificateAuthority: | - -----BEGIN CERTIFICATE----- - ... - -----END CERTIFICATE----- - audiences: - - cozystack-prod - claimMappings: - username: - claim: email - prefix: "" - groups: - claim: groups - prefix: "" - users: - - email: alice@acme.example - role: admin -``` - -…or via an out-of-band Secret the operator has already created in the -tenant namespace: - -```yaml -spec: - oidc: - mode: CustomConfig - customConfig: - secretRef: - name: acme-byo-authn-config # has key config.yaml -``` - -`config` and `secretRef.name` are mutually exclusive; the chart fails the -render if both — or neither — are set. - -No Keycloak objects land in `cozy`; the chart writes only the -AuthenticationConfiguration Secret (or mounts the operator's) and the -RBAC Job. The `-oidc-kubeconfig` helper Secret is NOT written -in CustomConfig mode: the issuer and clientId are inside the -operator-supplied config and are not knowable to the chart. Distribute -the OIDC kubeconfig out-of-band. - -## Aggregated API servers - -Authenticating a user is only half of the path. A call that lands on an aggregated API server — an `APIService` backed by an extension server rather than by the core apiserver — reaches it over the aggregation layer, which forwards the caller's identity in request headers. The UID travels in `X-Remote-Uid`, which the aggregation layer sends whenever the `RemoteRequestHeaderUID` gate is on, and the extension server trusts that header only when the tenant kube-apiserver has published it under `requestheader-uid-headers` in the `extension-apiserver-authentication` ConfigMap. Without that key the extension server ignores the header, and the call is served as if the caller had no UID, even though `kubectl` against the core apiserver works fine. Anything on the far side that reads the UID, an authorizer or an audit record, sees an empty value. - -Carrying the UID across that hop is a property of the aggregation layer, not of OIDC: a caller authenticated by any means loses their UID the same way. The chart nonetheless renders the header flag only when `spec.oidc.mode` is not `None`, which keeps the blast radius to clusters opting into a new feature. A cluster that has never left `mode: None` therefore still loses the UID at the extension server. - -Be clear about who this helps. The flag forwards a UID the caller already has; it does not create one. ServiceAccount tokens carry a UID, and so do other identities that set one, and for those the aggregation hop starts working. An OIDC user gets one only from a claim mapping: in `spec.oidc.mode: System` the AuthenticationConfiguration the chart generates maps `uid` to the `sub` claim, the Keycloak account UUID, so those users reach an aggregated API server under a stable identifier. `sub` rather than the username claim, because the platform realm lets a user change the address `email` carries while the subject stays where it is. In `CustomConfig` mode the configuration is yours: map `uid` and the header carries what you mapped; leave it out and upstream resolves an empty UID (`plugin/pkg/authenticator/token/oidc/oidc.go`, `getUID`, read at v0.35.0), with nothing for the header to carry. - -On a cluster that was running before the mapping existed, those users gain a UID where they had none. Tenant RBAC does not notice — a role binding matches a username or a group, never a UID — but an audit record on the tenant apiserver now carries `user.uid`, `kubectl auth whoami` shows it, and an admission webhook or extension server inside the tenant that read the empty value now reads the subject. - -Where `spec.oidc.mode` is not `None`, and outside the cases further down that stop it, the chart renders the flag that publishes it alongside `--authentication-config`: - -| `spec.version` | rendered | -| --- | --- | -| `v1.31` | nothing — the flag does not exist upstream, and an unknown flag stops the apiserver from starting | -| `v1.32` | nothing — `RemoteRequestHeaderUID` is alpha and off, and the apiserver refuses the flag while the gate is off | -| `v1.33` and newer | `--requestheader-uid-headers=X-Remote-Uid` | - -The chart never renders `--feature-gates` itself. From `v1.33` `RemoteRequestHeaderUID` is beta and on by default, so the header flag is all the apiserver needs. On `v1.32` the chart does not switch on an alpha gate for you, so aggregated API servers do not see the caller's UID there; if you need them to on `v1.32`, write both `--feature-gates=RemoteRequestHeaderUID=true` and `--requestheader-uid-headers=X-Remote-Uid` into `controlPlane.apiServer.extraArgs` yourself, and the chart passes them through untouched. - -The version in that table is the effective one, not the image tag. `--emulated-version` in `controlPlane.apiServer.extraArgs` moves it: the gate resolves through the versioned spec at the emulated version, so `--emulated-version=1.32` puts `RemoteRequestHeaderUID` back to alpha-and-off on a `v1.35` cluster, and the chart follows by rendering nothing, as it would on a `v1.32` image. The chart reads the dot-separated numbers at the start of the value, after an optional `v`, and ignores what follows them, so it reads `v1.32`, `1.32.0` and `1.32-rc` all as `1.32`. - -Two values are still not harmless, whatever the chart does with them. An element naming another component, `--emulated-version=wardle=1.2`, says nothing about the tenant kube-apiserver, but the apiserver rejects a component it has not registered, `component not registered: wardle`, and does not start. A value whose minor is above your `spec.version` is ignored too, because emulation only moves the effective version down, and there the apiserver checks against a range rather than a ceiling: it rejects one above its own binary or below the floor it still supports, naming the range it accepts. In both cases nothing the chart renders makes any difference. - -Adding the header flag through `controlPlane.apiServer.extraArgs` by hand is no longer necessary from `v1.33`, and an existing cluster that does keeps working as long as its entries would start an apiserver: the chart skips its own copy when your entries already carry `X-Remote-Uid`, and refuses to render the shapes listed below. - -Every entry you write on one of these three flags reaches the tenant kube-apiserver. None of them is among the flags the tenant control plane sets itself and drops from `extraArgs`; the chart moves or refuses an entry naming one of those, and the description of `controlPlane.apiServer.extraArgs` lists them. Where your entry does not already satisfy the requirement the chart therefore adds its own beside it rather than failing. `--requestheader-uid-headers` is a repeatable flag whose occurrences append into one list, so a list of your own that omits `X-Remote-Uid` gets a second entry carrying it and the union is what the apiserver validates; your header keeps working alongside the standard one. - -The chart does not check how you spell kube gate terms. The apiserver collects `--feature-gates` terms per component across all your entries and refuses a configuration that names the kube component both bare and `kube:`-prefixed; the chart passes that through like any other gate value the apiserver rejects on its own terms. - -If you turned the gate off on purpose, with `RemoteRequestHeaderUID=false` or a blanket `AllBeta=false`, the chart does not render the header flag and the render is byte-identical to the one before this feature existed. You keep losing the UID at the aggregation layer, which is what the opt-out asks for. Adding the opt-out or removing it again needs no second edit on Kamaji 26.9.4-edge: the tenant control plane compares a hash of `extraArgs` against the one it stored last time and rebuilds the argument list from scratch whenever they differ, so nothing is left behind from the previous shape. A rollback of Kamaji to an earlier build loses that. The older code expects a number in the `kube-apiserver.kamaji.clastix.io/args` annotation and gives up when it finds the hash. From then on, a flag removed from `extraArgs` stays on the running control plane until someone sets the annotation back to a number by hand. - -The render fails where entries of your own describe a kube-apiserver that already refuses to start: a uid-headers list with an element that is empty once trimmed, which a trailing comma leaves behind, and a uid-headers list alongside a gate setting that turns `RemoteRequestHeaderUID` off. The chart cannot rescue either, because the value the apiserver rejects is yours. The error message names the fix, which beats a crash-looping control plane. More refusals sit outside that group and outside the conditions below: the `--oidc-*` and `--authentication-config` collisions further down, each on its own terms; an unquoted `--emulated-version=value` entry whose kube version has a non-zero patch component, such as `1.32.4`, which the apiserver refuses with `patch version not allowed`; an entry naming a flag the tenant control plane sets itself, refused in every `spec.oidc.mode` unless the chart moves it into a field, as the description of `controlPlane.apiServer.extraArgs` explains; and the list ending in one of these three flags, where the apiserver may well start — it is the silence that earns that one. - -Those first two checks run only where the chart renders something. Three things switch them off with the header flag: an effective version of `v1.32` or below, a quoted `--emulated-version`, and two `--emulated-version` entries that both name kube. Each of those leaves the chart either with nothing to render or unable to say what the apiserver will read, so it renders nothing and judges nothing, and a shape that would otherwise be refused here passes silently through to a control plane that does not start. Take the unreadable entry out if you want the checks back. `--feature-gates` or `--emulated-version` written as a flag and a value in separate entries hides a value too, but a narrower one, and the chart keeps what holds whatever that value is. The empty element is still refused. An explicit `RemoteRequestHeaderUID=false` is still refused beside a header entry behind a hidden `--emulated-version`, because it turns the gate off at every version; a blanket `AllBeta=false` is not, because at a lower emulated version the gate can be alpha, where `AllBeta` does not reach it. Neither is refused behind a hidden `--feature-gates` value, which can turn the gate back on. A uid-headers list of yours without `X-Remote-Uid` still gets the chart's element beside it, which the apiserver needs with the gate on and which changes nothing with the gate off, since your list alone is refused then. Behind a hidden value and without a list of yours, the chart renders no `X-Remote-Uid` entry at all. - -Otherwise nothing stops rendering: every other `extraArgs` shape reaching this code either renders as it did or gains the header flag. - -The gate check reads your entries the way the apiserver does. - -- An element may name a component, because `--feature-gates` is a colon-separated multimap: `kube:RemoteRequestHeaderUID=false` is the same opinion as `RemoteRequestHeaderUID=false`, while an element naming another component is not about the tenant kube-apiserver, and the chart ignores it when it works out the state of the UID gate. That is the chart's reading only. Whether the apiserver accepts the component is up to its own component registry, as it is for `--emulated-version` above. -- Past that it is one `Name=value` element at a time, spaces trimmed on both sides, and the value resolved the way `strconv.ParseBool` resolves it, so `1`, `t` and `T` mean the same as `true`, and `0`, `f` and `F` the same as `false`. -- Blanket settings count, because the apiserver applies them to every gate you have not named explicitly. `AllBeta=false` switches `RemoteRequestHeaderUID` off, so the chart reads it as your opt-out; `AllAlpha` covers alpha gates only, and from `v1.33` this gate is beta, so the chart does not read it. -- Naming the gate wins over a blanket: `AllBeta=false,RemoteRequestHeaderUID=true` leaves the gate on, because an explicit entry beats a blanket one whichever order they appear in. -- Gate names are compared exactly, as the apiserver looks them up, so `remoterequestheaderuid=false` is not an opinion about `RemoteRequestHeaderUID`; the apiserver would reject that spelling as an unrecognized gate anyway. -- Several `--feature-gates` entries settle a gate between them, last term wins, exactly as the apiserver settles them: an earlier entry naming the gate still counts when a later entry says nothing about it. -- An entry with an empty value carries no term, so it settles nothing, and it does not cancel what an earlier entry said. Drop the entry you do not want instead of emptying it. - -`--emulated-version` accumulates rather than replaces, and the apiserver refuses two elements naming the same component with `duplicate version flag`. Two entries of yours that both name kube, explicitly or by naming nothing, stop the control plane from starting; the chart does not render the header flag there, because there is no effective version left to decide against. Entries naming different registered components are fine and all of them apply, so an emulated kube version stays in force when a later entry names something else. - -Quotes stop the chart from reading the entry they are on. `--requestheader-uid-headers` and `--emulated-version` are both CSV-parsed by the apiserver, which strips a surrounding pair of double quotes before it sees the value, and the chart does not reproduce that. On `--emulated-version` that hides the version the whole decision rests on, so the chart does not render the header flag, exactly as it did before that flag existed. On `--requestheader-uid-headers` it only means the chart cannot tell whether that entry already carries `X-Remote-Uid` or an empty element: it renders its own element, which is safe whatever your value turns out to be, and does not refuse the render over an element it may be misreading. `--feature-gates` is not CSV-parsed, so quotes there are neither stripped nor understood: the apiserver rejects the term as an unrecognized gate name and the chart, reading the same text, does not take it for an opinion about `RemoteRequestHeaderUID` either. Drop the quotes if you want the chart to read the entry. - -Writing a flag and its value as two list entries has the same effect, for the same reason. The apiserver pairs them, but the value sits in an entry the chart reads separately, so it cannot be attached to the flag. On `--feature-gates` and `--emulated-version` the chart therefore renders its own `X-Remote-Uid` element only beside a uid-headers list of yours that lacks it, as described above. On `--requestheader-uid-headers` it counts the flag as present, which is what the opt-out check needs, and renders its own `X-Remote-Uid` entry beside it. Write `--flag=value` in one entry if you want the chart to read the value. - -One arrangement of that shape the chart refuses outright: one of those three flags as the last entry in the list. The apiserver pairs a valueless flag with whatever argument follows it, and what follows yours is the `--authentication-config` the chart appends, so the flag would swallow it. The AuthenticationConfiguration is then never applied, and what that costs depends on which flag took it: `--requestheader-uid-headers` accepts the path as a header name, so the control plane starts and fails every login with nothing to show for it, while `--feature-gates` and `--emulated-version` reject it and the apiserver exits instead. Give the flag its value in the same entry. Moving it earlier works too: the entry after it is then one of yours, and it reaches the apiserver right behind the flag, since the chart refuses every entry the control plane would drop or moves it out of the list it renders. - -The uid-headers list is read without trimming, because the apiserver does not trim it either: `--requestheader-uid-headers=X-Remote-Uid , Other` does not contain `X-Remote-Uid` as far as the apiserver is concerned, so the chart does not read it as one and renders its own element, which is what makes that list start. The emptiness check is the one that trims, again because the apiserver's does: in `X-Remote-Uid, ` the second element is empty once trimmed, and the apiserver refuses the whole list with `empty value in "requestheader-uid-headers"` although `X-Remote-Uid` is in it, which is why that shape fails the render instead. - -On `v1.31` and `v1.32` the chart renders no UID flag, and the UID guards above do not run, so a uid-headers or `--feature-gates` entry of yours passes through untouched. These checks still apply there as everywhere else, because none of them depends on the effective version: the `--oidc-*` and `--authentication-config` collisions, the refusal of a patch-level `--emulated-version`, the move or refusal of an entry naming a flag the tenant control plane sets itself, which the description of `controlPlane.apiServer.extraArgs` explains, and the refusal of a list ending in one of the three flags, which is about the `--authentication-config` the chart appends on every version rather than about the UID flags. Aggregated API servers cannot see the caller's UID on `v1.31`; on `v1.32` they can only through the alpha gate you enable yourself, as described above. Move the cluster to `v1.33` or newer if you need them to without it. Writing `--requestheader-uid-headers` yourself does not work around it on `v1.31` — the flag does not exist there, and an unknown flag stops the apiserver from starting. - -## Users and RBAC - -`users[]` is a flat list. Each entry produces a single -`ClusterRoleBinding` inside the tenant cluster, labelled -`app.kubernetes.io/managed-by=cozystack-oidc` and -`app.kubernetes.io/instance=`. The CRB name is a -deterministic hash of `-`, so the same email always -maps to the same binding. - -| `role:` | `ClusterRole` bound | -| --- | --- | -| `admin` | `cluster-admin` | -| `view` | `view` | - -The CRB `User:` subject is the literal `email` value; it must match the -`email` claim emitted by the issuer. The chart-generated OIDC -kubeconfig requests `--oidc-extra-scope=email` in the -`kubectl oidc-login` exec block, so the token includes `email` -regardless of whether the per-cluster client lists `email` in its -default client scopes. The `email` scope itself is a built-in OIDC -scope available in every conformant issuer (Keycloak included), so no -extra realm-side configuration is required for `System`. For -`CustomConfig`, verify your BYO issuer emits the `email` claim when -the client requests the `email` scope; every conformant OIDC provider -does. - -Toggling a user out of `users[]` revokes their access on the next chart -reconcile — the bootstrap Job prunes any CRBs labelled by the release -that are no longer in the desired list. - -The static admin kubeconfig stays as the documented break-glass path -regardless of mode. - -## How a user logs in (System mode) - -The user installs `kubectl oidc-login` once: - -```bash -kubectl krew install oidc-login -``` - -The operator hands them the OIDC kubeconfig. The Secret name follows -the Helm release pattern `kubernetes--oidc-kubeconfig` (the -cozystack-api prefixes the cluster name with `kubernetes-` when it -materialises the `HelmRelease`): - -```bash -kubectl --namespace tenant-acme get secret kubernetes-prod-oidc-kubeconfig \ - --output=jsonpath='{.data.kubeconfig}' | base64 -d > prod.kubeconfig -``` - -First `kubectl --kubeconfig prod.kubeconfig get …` call triggers the -Keycloak browser flow on localhost:8000 (then 18000 as fallback) and -caches the token locally. Subsequent calls are silent until the token -expires. - -## Failure modes - -- **`mode: System` without the platform-level OIDC feature** — chart - render hard-fails: `spec.oidc.mode: System requires the platform-level - OIDC feature (authentication.oidc.enabled) — enable it in - cozystack-values, or use mode: CustomConfig for a tenant-supplied - issuer.` -- **`CustomConfig` with an unreachable issuer or wrong claim mappings** — - the apiserver rejects tokens at request time; the admin kubeconfig - keeps working as break-glass. -- **`emailVerified` on Keycloak users is a prescriptive requirement, - not a chart-enforced one.** The chart emits a - `claimValidationRules` entry keyed on `groups` (see next bullet), - but not one keyed on `email_verified`. The layered guarantees you - rely on instead: - 1. Provision users with `emailVerified: true` (via `KeycloakRealmUser` - or the Keycloak UI's email-verify flow) so no unverified identity - ever holds the email you name in `users[].email`. - 2. The `cozy` realm keeps Keycloak's default `duplicateEmails: false`, - so a second account cannot claim an already-registered address to - impersonate an existing operator. - 3. As a k8s side-effect, if the issuer explicitly emits - `email_verified: false` on a token the apiserver rejects it with - `oidc: email not verified` — but a *missing* claim is treated as - verified. - Adding a CEL `claimValidationRules` entry - (`!has(claims.email_verified) || claims.email_verified == true`) to - the rendered System-mode config would elevate item 3 to a hard gate; - that is a reasonable follow-up hardening but is out of scope for - Phase 1. - -- **Cross-tenant isolation gate.** The rendered - `AuthenticationConfiguration` carries a CEL `claimValidationRules` - entry on the `groups` claim that rejects any token whose caller is - not a member of at least one of this tenant's four Keycloak groups: - - ``` - -view -use -admin -super-admin - ``` - - The tenant chart (`packages/apps/tenant/templates/keycloakgroups.yaml`) - provisions these groups in the shared `cozy` realm. Without this - gate, any authenticated cozy-realm user could point `kubectl - oidc-login` at another tenant's cluster, land at - `system:authenticated`, and enumerate the discovery surface - (`kubectl api-resources`, OpenAPI schemata) — RBAC would default-deny - named-resource access, but discovery still leaks. Symmetric with the - Grafana-side `allowed_groups` gate on the Monitoring chart's - `auth.generic_oauth` block (see `docs/oidc-grafana.md`). CustomConfig - mode does NOT get this gate injected — the tenant's own - AuthenticationConfiguration is authoritative and the tenant is - responsible for their own claim-side guards. -- **`kubectl` without the `oidc-login` plugin** — the exec block errors - out client-side; install the plugin. - -## What is NOT in Phase 1 - -- **Per-tenant Keycloak realms.** Phase 2 candidate; tracked in - cozystack/community#24 (Option B — retained as the strongest isolation - answer; Option A is Keycloak Organizations). -- **Federating an external IdP into `cozy`.** Out of scope. -- **Cross-cluster SSO inside one tenant.** Each cluster has its own - audience — that is the per-cluster isolation primitive. -- **Custom credential plugin / RFC 8693 token exchange.** Possible future - optimisation; not required for the per-cluster client + audience model. diff --git a/docs/operations/backup-classes.md b/docs/operations/backup-classes.md deleted file mode 100644 index 51aab243b..000000000 --- a/docs/operations/backup-classes.md +++ /dev/null @@ -1,398 +0,0 @@ -# Backup Classes - -Cozystack ships a single platform-managed `BackupClass` named `cozy-default`. It is provisioned automatically when the `backupstrategy-controller` package is installed and references the system-managed bucket provisioned through the `apps.cozystack.io/Bucket` CR `cozy-backups` in the `tenant-root` namespace (the real S3 bucket name is the COSI-assigned one from `BucketClaim.status.bucketName`). - -Tenants reference `cozy-default` from `BackupJob`, `Plan`, and `RestoreJob` resources — they do **not** supply S3 credentials, endpoints, or paths. The platform projects the system-managed credentials Secret into the tenant namespace per BackupJob (or, for long-lived references like Velero's `BackupStorageLocation`, into a fixed list of system namespaces on a periodic tick), and the default strategy templates encode `/` into every S3 path so two tenants with the same application name never collide. - -## Supported applications - -### Bound by `cozy-default` (work out-of-the-box) - -| Application Kind | Driver | Strategy CR | -|----------------------------------|--------------------------------------|----------------------------------------------------------------------------| -| `apps.cozystack.io/Postgres` | CloudNativePG (barman) | `strategy.backups.cozystack.io/CNPG` `cozy-default-cnpg` | -| `apps.cozystack.io/MariaDB` | mariadb-operator dump | `strategy.backups.cozystack.io/MariaDB` `cozy-default-mariadb` | -| `apps.cozystack.io/ClickHouse` | Altinity `clickhouse-backup` sidecar | `strategy.backups.cozystack.io/Altinity` `cozy-default-altinity` | -| `apps.cozystack.io/MongoDB` | Percona psmdb operator (pbm) dump | `strategy.backups.cozystack.io/MongoDB` `cozy-default-mongodb` | -| `apps.cozystack.io/Kafka` | Kafka Admin API (topic metadata) | `strategy.backups.cozystack.io/Kafka` `cozy-default-kafka` | -| `apps.cozystack.io/Etcd` | etcd-operator snapshot | `strategy.backups.cozystack.io/Etcd` `cozy-default-etcd` | -| `apps.cozystack.io/RabbitMQ` | RabbitMQ definitions (management API) | `strategy.backups.cozystack.io/Rabbitmq` `cozy-default-rabbitmq` | -| `apps.cozystack.io/Redis` | RDB dump Job (sentinel-discovered master) | `strategy.backups.cozystack.io/Redis` `cozy-default-redis` | -| `apps.cozystack.io/VMInstance` | Velero + kubevirt-velero-plugin | `strategy.backups.cozystack.io/Velero` `cozy-default-velero-vminstance` | -| `apps.cozystack.io/VMDisk` | Velero | `strategy.backups.cozystack.io/Velero` `cozy-default-velero-vmdisk` | - -### Shipped but NOT bound (admin opt-in required) - -| Application Kind | Driver | Strategy CR | -|----------------------------------|--------------------------------------|----------------------------------------------------------------------------| -| `apps.cozystack.io/FoundationDB` | FoundationDB operator backup_agent | `strategy.backups.cozystack.io/FoundationDB` `cozy-default-foundationdb` | - -The FoundationDB strategy CR is rendered by the chart so admins can reference it from a custom BackupClass once the operator-side plumbing (mounting `cozy-backups-creds` into the `cozy-foundationdb-operator` Deployment) is wired manually. See "FoundationDB caveat" below. - -### Endpoint format per driver - -Different operators expect different endpoint shapes; the strategy templates rendered by `backupstrategy-controller` resolve one S3 endpoint (via the `backupstrategy-controller.endpoint` helper) and adapt it to each consumer's contract. For a provisioned bucket (`provisionBucket: true`, the default) the endpoint is **derived from the COSI bucket's system-credentials Secret** (`backupStorage.systemSecretName`) and forced to `https://` — the external S3 ingress with an ACME cert, the only endpoint the backup operators can verify. SeaweedFS's in-cluster S3 serves TLS on `:8333` behind the self-signed "SeaweedFS CA", and the Etcd Strategy S3 schema has no `caCert` field, so the in-cluster endpoint cannot be targeted directly. The `backupStorage.endpoint` chart value (a full URL like `http://seaweedfs-s3.tenant-root.svc:8333`) is the **fallback**, used for external S3 (`provisionBucket: false`) and for offline `helm template`/pre-reconcile renders where the Secret lookup returns nothing. The resolved endpoint is adapted per consumer: - -| Driver | Strategy template field | Form | -|--------|-------------------------|------| -| CNPG (Postgres) | `barmanObjectStore.endpointURL` | full URL (scheme preserved) | -| Etcd | `destination.s3.endpoint` | full URL (scheme preserved) | -| MariaDB | `storage.s3.endpoint` | bare host:port (scheme stripped); `tls.enabled` derived from the scheme | -| MongoDB | n/a — storage lives on the app (`backup.endpointURL`) | full URL (scheme preserved), configured on the MongoDB application, not the strategy | -| FoundationDB | `blobStoreConfiguration.accountName` + `urlParameters.secure_connection` | bare host:port + derived secure flag | -| Velero | `BackupStorageLocation.spec.config.s3Url` | full URL (scheme preserved) | -| ClickHouse sidecar | `S3_ENDPOINT` env | bare host:port (from projected Secret) | -| Redis (dump Job) | `S3_ENDPOINT` env | bare host:port (from projected Secret); `https://` prepended when unscheme'd | -| Kafka | `S3_ENDPOINT` env on the strategy Job | full URL (scheme preserved); the Job's `curl --aws-sigv4` prepends `https://` if the endpoint carries no scheme, honours `backupStorage.forcePathStyle`, and (for the image's curl 7.76.1) signs a portless URL with `--connect-to` to the real port so a ported endpoint still verifies | - -The projected `cozy-backups-creds.endpoint` key is **stripped of scheme** so chart-emitted sidecars (ClickHouse) consume it directly. Drivers that need the full URL receive the resolved endpoint described above — derived from the COSI system Secret (forced `https://`) for a provisioned bucket, or the `backupStorage.endpoint` fallback for external S3. - -VM-driven (Velero) backups land in the same `cozy-backups` bucket under the `velero/` prefix. A `BackupStorageLocation` named `cozy-default` is shipped by the `backupstrategy-controller` chart (`packages/system/backupstrategy-controller/templates/velero-bsl.yaml`) so endpoint/bucket/region come from the same `backupStorage` values block used by Strategy CRs and the projector. - -### FoundationDB caveat - -The strategy CR `cozy-default-foundationdb` is shipped, but it is **not** bound by `cozy-default` yet. Restore runs `fdbrestore` from inside the `cozy-foundationdb-operator` Deployment, which does not yet mount `cozy-backups-creds`. Until the operator deployment is updated to mount the projected Secret, FDB platform-default restore silently fails — admins who need it today should keep using a per-app `Bucket` plus a custom `BackupClass`, or wire the credentials file into the operator deployment themselves. - -**Cleanup gotcha (zombie backup_agent).** Unlike CNPG/MariaDB/Altinity (one-shot operator-side Backup CRs), the FoundationDB driver creates an `apps.foundationdb.org/FoundationDBBackup` CR that drives a **long-lived** `backup_agent` Deployment streaming continuously to S3. Deleting a Cozystack `Backup` (e.g. via retention sweeping) does NOT stop that Deployment — the agent keeps writing until the next BackupJob's `stopOtherFoundationDBBackups` call swaps it out, until an admin invokes `examples/backups/foundationdb/cleanup.sh`, or until the operator-side CR is deleted by hand. If a tenant deletes their last Cozystack Backup and never submits another BackupJob, the agent pods will continue running indefinitely and accumulate S3 PUTs. This is intentional today (the driver has no RBAC verb to stop the operator-side CR on Cozystack-Backup deletion) but admins should be aware of it. - -## Postgres and MariaDB: a restored copy converges its application passwords shortly after recovery - -Managed Postgres no longer accepts a plaintext `users[].password`; every application-user password is chart-generated into `-credentials` and read only from there. The CNPG backup snapshot therefore carries no passwords — deliberate, since a snapshot that did was the one place a tenant password sat in cleartext. - -**Residue from before the upgrade — this is forward-looking, not retroactive.** The removal scrubs new renders and new snapshots; it does not rewrite copies made earlier, and upgrading preserves the live password (the chart reads the existing `-credentials` through `lookup`), so those older copies still expose the *current* credential. Two sinks retain it: a Postgres `Backup` object created before this release snapshotted `app.spec.users` while that spec still carried a plaintext `password`, so its `status.underlyingResources` holds that password in cleartext — a field any tenant with `get backups` in the namespace can read (see the `underlyingResources` caution below); and every pre-upgrade Helm revision of `-init-script` rendered `ALTER ROLE … WITH PASSWORD ''` into its manifest, retained for `MaxHistory` revisions. There is no in-band rotation to invalidate the exposed value (chart-based rotation was intentionally not added — a chart-rendered Secret cannot revoke a leaked credential; rotation is being reworked as a controller, cozystack/community#72). So after upgrading, treat any pre-upgrade Postgres backup as credential-bearing: delete or re-take the pre-upgrade `Backup` objects, and be aware that the old init-script Secret persists in Helm history until those revisions age out of `MaxHistory`. - -The consequence for a **restore into a copy** (a differently-named target): the recovered database keeps the source roles with their source password hashes, but the target chart generates fresh random passwords into the target's `-credentials`, and the role-reconciling init-job is skipped while `bootstrap.enabled` is set on the restored app. The restore driver clears `bootstrap.enabled` automatically once recovery is healthy, so the next HelmRelease reconcile runs the init-job, which applies `ALTER ROLE … WITH PASSWORD` for every `spec.users` entry and converges the recovered roles onto the target Secret. Convergence is therefore automatic but not instant: between the RestoreJob reaching `Succeeded` and that init-job completing, the passwords advertised in `-credentials` do not yet match the recovered roles, so a client reading that Secret cannot log in as an application user for that brief window. The chart flags the Secret `postgres.cozystack.io/credentials-pending: "true"` and the NOTES print the same caution while bootstrap is still on, so a reader does not treat the advertised password as usable mid-restore; both clear on their own once the driver clears bootstrap. The data is intact and reachable as the CNPG superuser throughout. After a to-copy restore, wait for the application login to succeed rather than assuming the advertised password works the instant the RestoreJob succeeds. The driver clears `bootstrap.enabled` by writing it onto the Postgres app's own spec, so a GitOps source (Argo CD, Flux, Terraform) that pins `bootstrap.enabled: true` for that app will revert the clear on its next apply and the copy's credentials never converge — exclude the restored app from such a source until convergence completes, or clear `bootstrap.enabled` in the source itself. If the driver cannot clear the flag at all (the app was deleted or renamed mid-restore), the RestoreJob fails with reason `BootstrapDisableFailed` once its deadline elapses rather than sitting `Running` forever with no signal. An in-place restore is unaffected: the release keeps its existing `-credentials`, whose passwords already match the roles the recovery brings back. One-time migration: an app restored to a copy under an earlier release — before this auto-clear existed — may still be sitting with `bootstrap.enabled` set and its init-job permanently skipped; the driver clears the flag only for a restore it drives to completion, never retroactively for one that already finished, so such an app keeps advertising unconverged credentials until you clear `bootstrap.enabled` on it once by hand. - -Databases and users after a Postgres restore, in place or into a copy: the driver sets the app's `spec.databases` and `spec.users` to the snapshot taken when the Backup was created, while recovery replays WAL past that point (to the end of the archive when no `recoveryTime` is set), so the recovered cluster can hold databases and users the snapshot does not list. On the first init-job run after the restore, a database the chart manages but the restored spec does not declare is released instead of dropped: its data stays, and it and its `_admin` and `_readonly` roles lose the `managed by helm` comment, so the chart no longer grants on it or drops it. Add it to `databases` to manage it again. Users are not released: a recovered user the restored spec does not declare, including a source user the target of a copy does not declare, is dropped on that run and every object it owned is reassigned to `postgres`, so a client still logging in as that user loses the login. Declare the user in `users` to keep it; the chart then generates a new password for it into `-credentials`. - -MariaDB avoids the same problem at backup time: the driver sets `ignoreGlobalPriv` on every operator `Backup` it creates, so `mysql.global_priv` — the grant table holding every user's password hash, root included — is excluded from the logical dump and a restore into a copy never overwrites the target's chart-managed users. The same exclusion is also a limitation, and it applies to every restore, not only a to-copy one: because the grant table is never in the dump, only accounts Cozystack declares through `User` CRs (the chart's `users` map) are recreated on restore — an account created out of band, directly in MySQL rather than through `users`, is in no backup, so a restore brings back its data and its `mysql.db` grants but not the account that owns them, and that login fails until the account is recreated. Cozystack treats the `User` CRs as the source of truth for accounts precisely so the grant table need not be, so keep managed accounts in `users` rather than creating them by hand. That matters most for `root`, which the operator only applies at datadir bootstrap via `rootPasswordSecretKeyRef` and could never repair afterwards; keeping the source's grants out of the dump is what lets the target's advertised `root` password stay correct through a restore. This is a **backup-side** fix, so it only protects backups captured from this release onward. A restore from a backup taken **before** this change still replays the source's `mysql.global_priv` and overwrites the target's application users and `root` with the source's hashes; after restoring such an older backup, treat the target's advertised credentials as unreliable and reset them — application users converge on the next reconcile through their `User` CRs, but `root` must be reset out of band (`ALTER USER 'root' … IDENTIFIED BY …` against the restored server) since the operator applies `rootPasswordSecretKeyRef` only at datadir bootstrap. That once-only write is also why the Secret itself now matters: `root` lives solely in `-credentials` with no plaintext escape hatch left in values, so if that Secret is lost after bootstrap — a tenant deletes it, or a partial Velero restore drops it — the advertised `root` password and the live server's diverge with no in-band way to reconcile them; back the Secret up alongside the data, and reset `root` out of band if it is ever lost. - -## ClickHouse: opt-in to the system bucket - -The `clickhouse-backup` sidecar runs inside the ClickHouse Pod itself, so the Helm chart is what wires its S3 credentials. Existing tenants on the legacy `backup.s3*` values continue to work unchanged. To switch a release onto the platform bucket, set: - -```yaml -backup: - enabled: true - useSystemBucket: true -``` - -When `useSystemBucket: true`: - -- The chart-emitted `-backup-s3` Secret is no longer rendered. -- The sidecar consumes `cozy-backups-creds` (projected by the platform). -- `S3_PATH` is set to `/` so two tenants with the same ClickHouse release name never share a prefix. - -`s3Region`, `s3Bucket`, `endpoint`, `s3AccessKey`, `s3SecretKey`, and `s3CredentialsSecret` are ignored in this mode. - -## MongoDB: the application owns the backup storage - -Unlike CNPG / MariaDB / Altinity, the MongoDB driver cannot inject its S3 target per-backup: the Percona psmdb operator only runs the percona-backup-mongodb (pbm) agents and services `PerconaServerMongoDBBackup` CRs when the `PerconaServerMongoDB` cluster has `spec.backup.enabled: true` and a storage declared, and a `PerconaServerMongoDBBackup` references that storage only by name. So the MongoDB application must **opt into backups** and point at the bucket in its own chart values: - -```yaml -apiVersion: apps.cozystack.io/v1alpha1 -kind: MongoDB -metadata: - name: orders-db -spec: - backup: - enabled: true - destinationPath: "s3:///orders-db/" - endpointURL: "https://seaweedfs-s3.tenant-root:8333" - insecureSkipTLSVerify: true # self-signed in-cluster seaweedfs; psmdb s3 storage has no CA-bundle field - s3AccessKey: "" - s3SecretKey: "" -``` - -The chart declares that storage as `s3-storage`, which the `cozy-default-mongodb` strategy names (`storageName: s3-storage`, `type: logical`). The driver then drives on-demand backups and restores through the unified `BackupJob` / `RestoreJob` / `Plan` interface on top of the operator's storage config — adding restore-to-differently-named instances (via `PerconaServerMongoDBRestore.spec.backupSource`) and point-in-time recovery that the raw scheduled-task / `mongodump` paths do not offer. When a target cluster has backups disabled, the driver surfaces a clear `Ready=False` precondition on the BackupJob/RestoreJob rather than hanging until the deadline. - -For a to-copy restore the operator reads the dump from the **source** backup's bucket/endpoint, but authenticates with the **target** cluster's own S3 credentials (the source release's Secret dies with it in a DR scenario). So the target application's credentials must be able to read the source bucket — the common case where both share the one platform `cozy-backups` bucket. A target whose credentials are scoped to a different S3 account or bucket cannot read the source archive, and the restore fails loudly with `AccessDenied` (RestoreJob `Failed`) rather than silently restoring nothing. - -A full, scripted example (write a marker document, back up, restore to a copy, assert the round-trip while the source stays untouched) is in [`examples/backups/mongodb/`](../../examples/backups/mongodb/) — driven by `run-all.sh`. - -### Point-in-time recovery (MongoDB) - -psmdb records an oplog stream between logical backups. A MongoDB `RestoreJob` recovers to a timestamp via `spec.options.recoveryTime` — the same option name and RFC3339 format the Postgres/CNPG driver uses, so the two are uniform: - -```yaml -spec: - options: - recoveryTime: "2026-08-05T12:34:56Z" # RFC3339 (UTC), same as the CNPG driver -``` - -The driver converts `recoveryTime` to the psmdb oplog target internally. Unlike CNPG (whose empty `recoveryTime` replays WAL to the latest archived point), an empty `recoveryTime` here restores the backup snapshot as taken — a psmdb logical backup is already a consistent point, so "restore this backup" is the safe default. `spec.options.restoreTimeoutSeconds` caps how long the driver waits for the operator restore before failing (default 30m), matching the CNPG option. Any unrecognised key under `spec.options` (e.g. a `recoverytime` typo) is ignored but surfaced as a `UnknownRestoreOption` Warning event on the RestoreJob rather than silently dropped. - -## Inspecting the defaults - -```bash -kubectl get backupclasses -kubectl get backupclass cozy-default -o yaml -kubectl -n tenant-root get bucket cozy-backups -kubectl -n tenant-root get secret bucket-cozy-backups-system-credentials -kubectl -n cozy-velero get backupstoragelocation cozy-default -``` - -The bucket lives in `tenant-root` and is provisioned through the `apps.cozystack.io/Bucket` CR. The system-managed credentials Secret never leaves that namespace. The backupstrategy-controller projects a copy under the name `cozy-backups-creds` into a tenant namespace right before each BackupJob or RestoreJob runs, and refreshes the same Secret in `cozy-velero` (and any other namespace listed in `backupStorage.systemNamespaces`) on a 1-minute tick. The projected Secret carries multiple key formats so each driver finds what it needs in one place: - -| Key | Consumer | -|-----------------------------------------------|-------------------------------------------| -| `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` | CNPG, MariaDB, Etcd, RabbitMQ, Redis | -| `accessKey` / `secretKey` (plus `bucketName`, `endpoint`, `region`) | ClickHouse sidecar | -| `cloud` | Velero (AWS credentials file format) | -| `blob_credentials.json` | FoundationDB backup_agent | - -The Redis dump Job additionally reads the `endpoint`, `bucketName`, and `region` keys (alongside the `AWS_*` pair) via `secretKeyRef`, the same set the ClickHouse sidecar consumes. - -The dump Job also speaks to the Redis app's own Sentinel and master, which is a separate TLS axis from the S3 endpoint above. When the `Redis` app has `tls.enabled`, the operator moves both to a TLS-only listener and publishes the CA at `redis-.ca-cert`; the Job mounts that Secret optionally and connects with `--tls --cacert` exactly when its `ca.crt` is present, so a plaintext (non-TLS) app is unaffected. This covers the default `tls.authClients: no`. Mutual TLS (`authClients: yes`) is not supported for backup — it requires a client certificate signed by the release CA, which the platform does not issue. - -### Bootstrap window - -On a fresh-cluster install, the Velero `BackupStorageLocation` `cozy-default` is rendered before the credentials projector has had a chance to copy `cozy-backups-creds` into `cozy-velero`. The BSL reports `Unavailable` until the projector's first synchronous round completes (which runs as soon as the `backupstrategy-controller` acquires leadership — in practice moments after the Pod becomes Ready, typically tens of seconds after `helm install` returns, not minutes). Velero rejects new `Backup` AND `Restore` requests against `storageLocation: cozy-default` during that window. Plan VM backup automation accordingly, or wait for the BSL to become ready before submitting backups: `kubectl -n cozy-velero wait backupstoragelocation cozy-default --for=jsonpath='{.status.phase}'=Available --timeout=5m`. - -**Note on controller restarts.** The BSL flickers `Unavailable` on every `backupstrategy-controller` pod restart while the projector replays its first synchronous round. The window is short (single-digit seconds) but operators who alert on BSL availability should suppress alerts during the controller's `kube_pod_container_status_restarts_total{container=backupstrategy-controller}` events or use a longer evaluation window than the projector tick (60s). - -### Cozy-default Bucket bootstrap - -`cozy-default` ships an `apps.cozystack.io/Bucket cozy-backups` CR in `tenant-root`, which the bucket-application chart turns into a `BucketClaim`; the COSI driver then assigns the real S3 bucket name (`bucket-`, so it cannot be computed in advance) and writes it to the BucketClaim's `.status.bucketName`. The strategy templates and the Velero BSL all read that real bucket name (Helm `lookup` against the BucketClaim). On a fresh install the BucketClaim takes a reconcile cycle to populate its status — until it does, the strategy templates render empty and only the `Bucket` CR + `BackupClass` are present in the cluster. - -**That skip does not repair itself on a reconcile.** helm-controller re-renders a release only when its chart or values change; the interval reconcile is a no-op for a healthy release, and drift detection is off on operator-generated HelmReleases. A cluster that lost the race at install time therefore keeps `BackupClass cozy-default` with **no** `Strategy` CRs and **no** Velero BSL indefinitely — which also fail-closes the pre-adoption snapshot in the v1.6.0 etcd migration. - -The same trap sits one release earlier, on the Secret everything else depends on. `bucket-cozy-backups-system-credentials` is rendered by the `bucket-cozy-backups-system` release behind a `lookup` of the COSI Secret, and is skipped just as permanently when that lookup is empty. Without it the credentials projector has no source at all, so no strategy, no Velero and no v1.6.0 etcd migration can resolve — and the gate cannot even determine the bucket name, which it reads from that Secret. - -Convergence is driven instead by the controller's default-objects gate (`backupStorage.reconcileDefaultObjects`, on by default), which repairs both, in order. While the credentials Secret is absent or carries no bucket name, the gate stamps `reconcile.fluxcd.io/forceAt` + `requestedAt` on the **bucket's** `bucket--system` HelmRelease. Once the bucket name resolves it checks that every object `cozy-default` routes to exists and stamps the same pair on the **`backupstrategy-controller`** HelmRelease, forcing the real Helm upgrade that re-runs the lookups. The two are throttled independently (one force per 5 minutes each), so the second is not delayed by the first. Expect the objects within a minute or two of the bucket becoming ready. - -The gate does not force a suspended HelmRelease — helm-controller ignores both annotations while `spec.suspend` is true, so it logs the skip and leaves the force counter alone. A release left suspended (`cozyhr suspend`) is therefore never repaired until it is resumed. - -Watch it with: - -```bash -kubectl -n cozy-backup-controller logs deploy/backupstrategy-controller | grep default-objects-gate -``` - -#### Manual recovery on an affected cluster - -Only needed on a cluster running a version without the gate (or with `reconcileDefaultObjects: false`). A plain `flux reconcile helmrelease` does **nothing** here — it does not re-render. You need a forced upgrade, and **both** annotations: `forceAt` is what makes helm-controller run a real Helm upgrade, and it is only honoured together with `requestedAt`. - -First confirm the bucket name is actually resolvable — forcing before that just re-runs the same empty lookup: - -```bash -kubectl -n tenant-root get bucketclaim bucket-cozy-backups -o jsonpath='{.status.bucketName}' -``` - -Then force the two releases, **in this order**: - -```bash -# 1. The credentials Secret. It is rendered by the -system release, not by -# bucket-cozy-backups — easy to miss, and the projector (hence every -# strategy and Velero) has no source without it. -ts=$(date -u +%Y-%m-%dT%H:%M:%SZ) -kubectl -n tenant-root annotate helmrelease bucket-cozy-backups-system \ - reconcile.fluxcd.io/forceAt="$ts" reconcile.fluxcd.io/requestedAt="$ts" --overwrite -kubectl -n tenant-root get secret bucket-cozy-backups-system-credentials - -# 2. The Strategy CRs and the Velero BSL. -ts=$(date -u +%Y-%m-%dT%H:%M:%SZ) -kubectl -n cozy-backup-controller annotate helmrelease backupstrategy-controller \ - reconcile.fluxcd.io/forceAt="$ts" reconcile.fluxcd.io/requestedAt="$ts" --overwrite -kubectl get $(kubectl get crd -o name | grep strategy.backups.cozystack.io) 2>/dev/null -kubectl -n cozy-velero get backupstoragelocation cozy-default -``` - -The race is nested: step 2's `lookup` resolves from the BucketClaim status, but the projector — and the v1.6.0 etcd migration — read the Secret from step 1, so a cluster missing both needs both. - -### Observability - -The credentials projector emits two Prometheus counters labelled by `namespace` (and `reason` for failures): - -- `cozystack_backup_credentials_projection_successes_total` -- `cozystack_backup_credentials_projection_failures_total` - -Alert on `rate(cozystack_backup_credentials_projection_failures_total[5m]) > 0` or `absent_over_time(cozystack_backup_credentials_projection_successes_total[10m])` to catch a stale BSL credential or a malformed source Secret without log scraping. - -The default-objects gate emits three more: - -- `cozystack_backup_default_objects_missing{backupclass="cozy-default"}` — how many of the objects the platform default backups depend on are absent: the credentials Secret, the Strategy CRs `cozy-default` routes to, and the Velero BSL. **This is the alert that would have caught the missing Strategy CRs**: it is non-zero whatever the HelmRelease's `Ready` condition says. Alert on `min_over_time(cozystack_backup_default_objects_missing[15m]) > 0`. -- `cozystack_backup_default_objects_check_errors_total{backupclass="cozy-default"}` — checks that could not reach a conclusion (an API error reading the source Secret, the BackupClass, or one of the routed objects). The gauge above is deliberately **not** written on those ticks, so that it does not flap on a transient API error — which means that while this counter climbs, the gauge is stale and a `0` on it proves nothing. Pair the two: `min_over_time(cozystack_backup_default_objects_missing[15m]) > 0 or rate(cozystack_backup_default_objects_check_errors_total[15m]) > 0`. -- `cozystack_backup_default_objects_force_reconciles_total{namespace,name}` — forced Helm upgrades issued, labelled by the release forced (this chart's own, or the bucket's `-system` release). A counter that keeps climbing means the forced render is not producing the objects (a missing CRD, for instance), which is a different problem from the install-time race. A suspended release is skipped before the patch and is **not** counted here, so a paused release cannot masquerade as a render that keeps failing — look for the `skipped forcing a suspended HelmRelease` log line instead. - -## Admin overrides for `cozy-default` - -`cozy-default` is rendered by the `backupstrategy-controller` chart and owned by Flux's helm-controller. **Direct `kubectl edit backupclass cozy-default` is overwritten on the next helm reconcile** — the same applies to its companion `strategy.backups.cozystack.io/*` CRs (`cozy-default-cnpg`, `cozy-default-etcd`, `cozy-default-mariadb`, `cozy-default-altinity`, `cozy-default-mongodb`, `cozy-default-foundationdb`, `cozy-default-rabbitmq`, `cozy-default-redis`, the two `cozy-default-velero-*`). The supported override path is the `backupStorage` block on the **`platform` component** of the `cozystack.cozystack-platform` Package CR: - -```yaml -apiVersion: cozystack.io/v1alpha1 -kind: Package -metadata: - name: cozystack.cozystack-platform -spec: - components: - platform: - values: - backupStorage: - provisionBucket: true # default; set false for external S3 - bucketName: cozy-backups # apps.cozystack.io/Bucket release name - endpoint: http://seaweedfs-s3.tenant-root.svc.cozy.local:8333 - region: us-east-1 - forcePathStyle: true - systemSecretName: bucket-cozy-backups-system-credentials - systemNamespaces: - - cozy-velero -``` - -The platform chart forwards this block into the child `Package cozystack.backupstrategy-controller` as `components.backupstrategy-controller.values.backupStorage` (`packages/core/platform/templates/bundles/system.yaml`), from where the cozystack operator merges it into the `backupstrategy-controller` HelmRelease over the chart defaults. Two paths that look plausible do **not** work: `spec.components.backupstrategy-controller` on the `cozystack.cozystack-platform` Package is silently ignored (the only component under that PackageSource is `platform`), and patching the child `Package cozystack.backupstrategy-controller` directly is reverted whenever the platform helm-reconcile re-renders it. - -A sibling `backupStrategyController` block on the same `platform` component is forwarded the same way, for the controller's own knobs rather than the bucket. The one an operator reaches for is `redisBackupResources`, which sizes the Redis strategy Pod — restore loads the whole dataset into a throwaway loader, so a large Redis needs more memory / ephemeral-storage than the defaults (the loader-not-ready log line points here): - -```yaml -spec: - components: - platform: - values: - backupStrategyController: - redisBackupResources: - limits: - memory: 8Gi - ephemeral-storage: 32Gi -``` - -| Knob | Effect | -|---|---| -| `provisionBucket` | Toggle creation of the in-cluster `apps.cozystack.io/Bucket` CR. Set `false` for external S3 (see [Disabling the platform-managed bucket](#disabling-the-platform-managed-bucket)). | -| `bucketName` | Two modes. With `provisionBucket: true` (default): K8s name of the Bucket CR + lookup key for the COSI BucketClaim — the actual S3 bucket name is the COSI-assigned UUID, surfaced through `BucketClaim.status.bucketName`. With `provisionBucket: false`: taken **verbatim as the real S3 bucket name** and baked into every strategy CR + the Velero BSL. | -| `namespace` | Namespace the Bucket CR (and its system-credentials Secret) lives in — `tenant-root` by default. Must be a tenant namespace (`tenant-*`): the Bucket chart's RBAC helper fails the Helm render for any other prefix. | -| `bucketNameOverride` | Escape hatch for offline `helm template` renders — bypasses the live-cluster BucketClaim lookup. Leave empty in production. | -| `endpoint` | **Fallback** S3 endpoint. For a provisioned bucket the strategy CRs + Velero BSL derive the endpoint from the COSI system Secret (external ACME ingress, forced `https://`) instead; this value is used only for external S3 (`provisionBucket: false`) and offline renders. For external S3, switching it to `https://` enables TLS in the MariaDB/FoundationDB strategies, which derive TLS from the scheme. The Redis dump Job is not scheme-driven: the projector delivers a bare host and the script prepends `https://` unconditionally, so the Job always connects over TLS — point `endpointCASecretName` (below) at the private CA rather than relying on the scheme, and ensure that CA is reachable to the relevant Pods. | -| `endpointCASecretName` | Optional Secret (key `ca.crt`) in the app namespace the Redis Job trusts for a self-signed S3 endpoint. Empty by default: the projected endpoint is always `https://` and the platform bucket's ACME cert verifies against the image's system CA store unaided. Set it only for a private CA. The Job mounts it optionally (nothing projects this Secret automatically), so a name typo does not wedge the Pod on `FailedMount`: a missing `ca.crt` falls through to the system CA store and the Job fails fast at the TLS handshake with a legible error — it does not skip verification, which still needs the explicit `insecureSkipTLSVerify` opt-in. | -| `insecureSkipTLSVerify` | Disables S3 certificate verification for the Redis Job (`curl -k`). `false` by default and an explicit opt-in, never a fallback — an untrusted-cert endpoint fails closed unless this is set. Prefer `endpointCASecretName`. | -| `region` | Re-projected into `cozy-backups-creds` on the next reconcile. Pod-restart required for chart-emitted clients consuming the region via env (ClickHouse sidecar today). | -| `forcePathStyle` | Path-style addressing; SeaweedFS S3 requires it, AWS S3 typically doesn't. | -| `systemSecretName` | Name of the human-friendly Secret produced by the Bucket app (or pre-created manually for external S3). The projector also accepts the raw COSI Secret format. | -| `systemNamespaces` | Namespaces where the controller eagerly projects `cozy-backups-creds` (Velero BSL, FDB operator). Tenants are projected lazily during BackupJob reconcile. | - -When the override needs to go beyond storage coordinates — different retention, different driver→Kind binding, multi-region split — create a **sibling BackupClass** with a unique name (anything but `cozy-default`). Sibling BackupClasses live outside the chart, are admin-owned, and Flux will not touch them. Tenants opt in by setting `backupClassName: ` on their `BackupJob`s. - -## Tuning via a custom BackupClass - -The defaults aim at a reasonable middle (30-day retention, gzip compression where applicable). To override for a specific tenant or workload, create your own `BackupClass` pointing at the same strategy CRs but with tweaked `parameters`, or a fresh strategy CR. Common knobs: - -- **CNPG strategy**: `barmanObjectStore.retentionPolicy`, `data.compression`, `wal.compression`. -- **MariaDB strategy**: `compression`, `maxRetention`, `databases[]`. -- **MongoDB strategy**: `storageName` (which `spec.backup.storages` entry on the psmdb cluster to use), `type` (`logical`), `compressionType` / `compressionLevel`. The S3 target itself is tuned via `backup.*` values on the MongoDB release (see [MongoDB: the application owns the backup storage](#mongodb-the-application-owns-the-backup-storage)). -- **Altinity strategy**: tune the `clickhouse-backup` sidecar via `backup.*` values on the ClickHouse release; the strategy Pod is a thin HTTP client. When the S3 endpoint's certificate is signed by a private CA rather than a publicly-trusted one — SeaweedFS's in-cluster `:8333` being the case in point — point `backup.endpointCA` at a Secret holding that CA bundle; the chart mounts it into the sidecar and adds it to the trust store via `SSL_CERT_DIR`, which supplements the system CA set rather than replacing it. -- **FoundationDB strategy**: `snapshotPeriodSeconds`, `agentCount`, `urlParameters[]`. -- **Rabbitmq strategy**: `artifactURITemplate` (the `///definitions.json` object-key layout) and the pod `template` (image, resources). The backup is a definitions export over the management API — vhosts, users, permissions, queues, exchanges, bindings, policies, parameters — so message payloads are out of scope and there is no point-in-time recovery; a full message-data backup is a Velero volume snapshot instead. **Restore is a merge, not a reset**: importing definitions (`POST /api/definitions`) creates or updates what the export contains and never deletes, so anything created after the backup survives the restore and the broker is not returned to its exact backup-time state. A to-copy restore imports the source's users (with password hashes) into the target, so those source credentials become valid logins there. Unlike the operator-backed strategies (whose engine owns archive retention), the Rabbitmq driver owns its object outright and deletes it from the bucket when its `Backup` is deleted — via a one-shot Job the Backup's removal waits on — so a retention-pruned `Plan` does not normally accumulate objects. The delete is **best-effort**: when it cannot run from here the Backup is released without deleting the object (with a `Warning` Event naming what was left behind), so the Backup — and any namespace being torn down — never wedges. The named give-up conditions are: the namespace is terminating (`CREATE` is forbidden there), the strategy CR or the projected credentials are unavailable, the rendered Job name is invalid, or the skip annotation below is set. Otherwise a genuinely failing delete (object storage unreachable) keeps the `Backup` in `Terminating` (a visible signal to act on) and retries. To release such a stuck `Backup`, annotate it `backups.cozystack.io/skip-artifact-cleanup: "true"` — cleanup then skips the delete and lets the `Backup` go, leaving the object in the bucket to be reclaimed manually or by a bucket lifecycle policy (`kubectl annotate backup -n backups.cozystack.io/skip-artifact-cleanup=true`). -- **Velero strategy (VMInstance / VMDisk)**: `ttl`, `includedResources[]`, `excludedResources[]`. -- **Etcd strategy**: today the strategy is path-only; combine with `Plan.spec.retentionPolicy` for trim cadence. - -The system-managed credentials Secret is the **only** way for in-cluster strategies to reach `cozy-backups`. Do not embed access keys in `BackupClass.parameters` — the security model relies on Secret references, and `parameters` end up in `Backup.status.underlyingResources`, which tenants can read. - -## Disabling the platform-managed bucket - -If a deployment runs against an external S3 (no SeaweedFS), set `backupStorage.provisionBucket: false` via the `platform` component override described above and create the source credentials Secret in `tenant-root` manually (flat-key format: `accessKey` / `secretKey` / `endpoint` / `bucketName`; or the raw COSI `BucketInfo` JSON). In the same `backupStorage` block, update `endpoint`, `region`, **and `bucketName`**: with `provisionBucket: false` the strategies and the Velero BSL take `bucketName` verbatim as the real S3 bucket name (no COSI lookup), so it must name the actual bucket on the external S3 — the `bucketName` key inside the Secret alone is not enough. The Velero `BackupStorageLocation` picks the same values up automatically (the chart renders it from the same `backupStorage` block), so no separate BSL configuration is needed. Note that disabling the cluster-default BSL itself (the chart's `velero.bslEnabled` value) is **not** carried by the `backupStorage` override path — the platform Package forwards only the `backupStorage` block. - -## Upgrade notes from chart-managed backups - -> **Postgres backups now use the CloudNativePG Barman Cloud plugin, not native `spec.backup.barmanObjectStore`.** -> -> Postgres backups were migrated off the deprecated native `barmanObjectStore` (removed in CNPG 1.29) onto the [Barman Cloud plugin](https://github.com/cloudnative-pg/plugin-barman-cloud). The `barman-cloud-*` binaries the native path needs are absent from the `standard` image variant `keycloak-db` pins; `apps/postgres` pins bare (system-flavor) tags that still ship them — its breakage was the operator/CRD skew below, not missing binaries — but the system flavor is deprecated upstream, so both move to the plugin. The chart now renders `spec.plugins` on the `cnpg.io/Cluster` plus a `barmancloud.cnpg.io/ObjectStore` CR that carries the S3 configuration, and the CNPG backup driver SSA-applies an `ObjectStore` and patches `spec.plugins` (instead of `spec.backup.barmanObjectStore`) for the platform flow; `Backup`/`ScheduledBackup` use `method: plugin`. On `helm upgrade` a legacy chart-managed Cluster's `spec.backup.barmanObjectStore` is replaced by `spec.plugins` + an `ObjectStore`. This only works once the `plugin-barman-cloud` operator is installed and co-located with the CNPG operator in `cozy-postgres-operator` (shipped by the `postgres-operator` chart) and its cert-manager dependency is present — otherwise the Cluster references a plugin that is not registered and backups / WAL archiving stall. -> -> **Mixed-version window: BackupJobs fail until the app re-renders with the new chart.** A `BackupJob` that fires while a `Cluster` still carries the pre-upgrade chart's native `spec.backup.barmanObjectStore` is rejected by the CNPG admission webhook (`Cannot enable a WAL archiver plugin when barmanObjectStore is configured`) — the driver cannot attach `spec.plugins` alongside the native config. This resolves itself once Flux re-renders the Postgres app with the new chart (which replaces `barmanObjectStore` with `spec.plugins`); re-run the BackupJob afterward. Upgrading only the operators/driver without the app charts leaves every `backup.enabled: true` Postgres in this state permanently. -> -> **Postgres `backup.enabled: true` with placeholder credentials no longer wires backups on upgrade.** -> -> The pre-v1.5 defaults for `backup.s3AccessKey` / `backup.s3SecretKey` in `packages/apps/postgres/values.yaml` were the literal `""` / `""` placeholders, so the Postgres chart still rendered a backup block on the `cnpg.io/Cluster` (with junk credentials, WAL archiving failing at runtime). Starting with v1.5 those defaults are empty strings and the chart NO LONGER renders any backup wiring when the placeholders are unmodified. Tenants on the legacy chart-managed flow who relied on those placeholders see `spec.plugins` and the `ObjectStore` disappear from the live `Cluster` on `helm upgrade`. Action — pick one: -> -> - **Move to the platform flow (recommended).** Set `backup.useSystemBucket: true`; the chart leaves `spec.plugins` unset and the CNPG backup driver SSA-applies the `ObjectStore` and patches `spec.plugins` onto the live `Cluster` at first BackupJob time. No tenant-side keys required. -> - **Stay on the legacy chart-managed flow.** Supply real `backup.s3AccessKey` / `backup.s3SecretKey` (or a pre-existing `backup.s3CredentialsSecret.name`); the chart renders `spec.plugins` + the `ObjectStore` from those coordinates. -> -> **Two platform-level changes ride along with this migration (they are required for the plugin to run):** -> -> - **CloudNativePG operator bumped to 1.28.1** (`postgres-operator` chart). A minor operator upgrade for the whole fleet; the CNPG CRDs move with it. This also fixes a latent bug where the operator image was newer than its bundled CRDs (`status.instanceID.sessionID` pruned), which made the operator believe the instance manager restarted and fail **every** backup cluster-wide with `instance manager was restarted during backup`. The vendored chart ships the CNPG CRDs as ordinary release manifests (gated by `crds.create`), so a normal `helm upgrade` updates them together with the operator — the `helm.sh/resource-policy: keep` annotation only prevents their deletion, not updates. The historical skew came from the `image.tag` pin outrunning the vendored chart's CRDs, which this PR removes; no out-of-band CRD apply is needed unless the HelmRelease itself is held back. -> - **LINSTOR scheduler admission webhook must not strip native-sidecar fields.** Older `linstor-scheduler` extender builds (≤ v0.3.5's predecessors) decoded every pod through a stale vendored Kubernetes API and re-encoded it, stripping `initContainers[].restartPolicy` cluster-wide — which breaks the plugin's restartable barman sidecar ("startupProbe forbidden without restartPolicy=Always"). The platform already ships the fixed webhook (`linstor-scheduler` re-vendored to upstream chart 0.3.1 / extender v0.3.6, which stopped stripping unknown pod fields), so no action is needed on an up-to-date platform; just do not hold the `linstor-scheduler` package back on an older version when rolling out the plugin. -> -> The same `useSystemBucket` opt-in applies to ClickHouse — see [ClickHouse: opt-in to the system bucket](#clickhouse-opt-in-to-the-system-bucket). When `useSystemBucket: true` is set on ClickHouse, the legacy `-backup` CronJob, credential Secret, and backup script are no longer rendered (they are mutually exclusive with the platform flow); migrate scheduled backups to a `backups.cozystack.io/Plan` against `cozy-default`. - -## Tenant workflow - -Tenants only ever see the BackupClass name. Typical apply: - -```yaml -apiVersion: backups.cozystack.io/v1alpha1 -kind: BackupJob -metadata: - name: ad-hoc - namespace: tenant-acme -spec: - backupClassName: cozy-default - applicationRef: - apiGroup: apps.cozystack.io - kind: Postgres - name: orders-db -``` - -## Point-in-time recovery (PostgreSQL) - -A `RestoreJob` restores a `Postgres` application from a `Backup`. Omit `spec.options.recoveryTime` to recover to the latest point in the WAL archive; set it (RFC3339) to recover the database to an exact instant — a point-in-time recovery (PITR). Under the hood the CNPG barman-cloud plugin restores the newest base backup taken at/before that instant and replays archived WAL up to it, so the restored cluster reflects the database exactly as of `recoveryTime`; later writes are absent. - -```yaml -apiVersion: backups.cozystack.io/v1alpha1 -kind: RestoreJob -metadata: - name: orders-db-pitr - namespace: tenant-acme -spec: - backupRef: - name: orders-db-adhoc # a completed Backup of the source - targetApplicationRef: # omit for a destructive in-place restore - apiGroup: apps.cozystack.io - kind: Postgres - name: orders-db-copy # a pre-deployed, empty Postgres app - options: - recoveryTime: "2026-07-21T09:30:00Z" -``` - -A full, scripted example (write a marker, capture the timestamp, restore to it, assert what survived) is in [`examples/backups/postgres/`](../../examples/backups/postgres/) — `45-restorejob-pitr.yaml`, driven by `run-all.sh`. - -### The recoverable window - -`recoveryTime` must fall inside the window the archive can reconstruct: - -- **Earliest** — the completion of the oldest base backup still in the archive. You cannot recover to an instant before the first base backup: WAL replay always starts from a base backup, and retention (`barmanObjectStore.retentionPolicy`) eventually trims the oldest ones together with the WAL that predates them. -- **Latest** — the timestamp of the most recent WAL segment shipped to object storage. While the source runs with `backup.enabled: true` it archives continuously, so the latest restorable time trails "now" only by the archive lag (seconds for a healthy cluster). Once the source is deleted, the latest restorable time is frozen at whatever WAL made it to S3 before it went away. - -A `recoveryTime` **past the latest archived WAL cannot converge**: PostgreSQL replays every available WAL, never reaches the target, exits with `FATAL: recovery ended before configured recovery target was reached`, and CNPG re-creates the recovery instance in a loop. Such a wedged restore is failed by the restore deadline (`spec.options.restoreTimeoutSeconds`, default 30m) — and the driver reads the recovery pod's log at that point, so instead of a generic timeout the RestoreJob ends `status.phase: Failed` with conditions `RecoveryConverged=False` and `Ready=False`, both reason `RecoveryTargetUnreachable`, and a message naming the target. The driver deliberately does **not** fail earlier off that FATAL: a *reachable* near-now target hits the identical FATAL transiently — often repeatedly, on a slow archiver — before it converges, so an earlier trip would reject a recoverable restore. To reject an unreachable target quickly, set a short `restoreTimeoutSeconds`; otherwise widen the window (take a fresh backup, or restore closer to now) or pick a time inside it. - -Restoring to a **very recent** instant is safe as long as WAL archiving is current: the segment covering the target may not be in object storage yet and the same FATAL fires transiently, but because the driver only fails at the deadline (not on that FATAL), the recovery has the whole window to catch up — the next attempt promotes once the WAL ships and the cluster goes healthy, which completes the restore. Only a target that never becomes reachable within the deadline is failed. If archiving is badly behind (a stalled `archive_command`, an overloaded cluster) a near-now target can exceed even the default 30m window; restore to a point you can confirm is archived (e.g. at/before the most recent completed backup, per the discovery query below). - -A `recoveryTime` **before the earliest base backup** fails differently: PostgreSQL cannot begin replay before the base backup it restored, so recovery never reaches a consistent state and never emits the "recovery ended before …" FATAL the driver classifies on. That case also surfaces at the deadline, but with the generic reason `RestoreFailed` rather than `RecoveryTargetUnreachable`. Choosing a `recoveryTime` at/after the oldest base backup's completion (below) avoids it. - -### Discovering the earliest / latest restorable time - -CNPG's `Cluster.status.firstRecoverabilityPoint` exists in the status schema but is unreliable under the barman-cloud plugin — it was observed empty on every plugin-backed cluster on the dev7 test cluster (CNPG 1.28.1) — so read the window from the backup catalog instead. Each completed base backup records its WAL range and timestamps on the underlying `cnpg.io/Backup`: - -```bash -# Completed base backups, oldest first: STOP is the earliest instant that -# backup alone can restore to; the oldest STOP is the window's lower bound. -kubectl -n get backups.postgresql.cnpg.io \ - --sort-by=.status.stoppedAt \ - -o custom-columns=NAME:.metadata.name,PHASE:.status.phase,START:.status.startedAt,STOP:.status.stoppedAt,BEGINWAL:.status.beginWal,ENDWAL:.status.endWal - -# The cozystack Backup points at its underlying cnpg.io/Backup and S3 prefix. -kubectl -n get backup.backups.cozystack.io -o jsonpath='{.spec.driverMetadata}' -``` - -The upper bound — the latest archived WAL — is whatever the source has shipped so far; with archiving healthy, any time up to a few seconds ago is safe. To confirm the archive is current, check that the source cluster's WAL is flowing to S3 (the `barman-cloud` sidecar logs an upload per segment) before restoring to a near-now target. - -### Idempotency under GitOps - -An in-progress restore is safe to reconcile. The driver purges the target `Cluster` + PVCs exactly once per RestoreJob (guarded by the `TargetPurged` condition and a freshly-recovered check), suspends the target's HelmRelease across the purge so Flux cannot race the bootstrap swap, and resumes it once the recovery cluster is rendered. A Flux reconcile (or a controller restart) mid-restore therefore re-attaches to the recovering cluster rather than deleting it and starting over. - -## Kafka: topic metadata only - -The `cozy-default-kafka` strategy backs up **topic metadata**, not message data. Its Job talks to the Kafka Admin API (`kafka-topics --describe` on backup, `kafka-topics --create` + `kafka-configs --alter` on restore) and stores one small object per run at `s3://////kafka-metadata.txt`. It captures every non-internal topic's partition count, replication factor and non-default configs; message payloads, consumer-group offsets, ACLs, quotas and `KafkaUser`s are out of scope, and there is no point-in-time recovery. The driver gates each run on the Strimzi `Kafka` cluster reporting `Ready` and never mutates it. - -This is the "reconstruct a cluster's topic topology" flow: an in-place restore recreates dropped topics into the source, and a to-copy restore applies the source's topics onto a freshly-bootstrapped empty `Kafka` (partitions and configs preserved). Restore is additive at the topic-set level — it never deletes topics that exist live but not in the backup — but it does not silently accept a divergent existing topic: it grows the partition count when the backup asks for more, and fails loudly (naming the topic and both values) when the backup asks for fewer partitions or a different replication factor, since Kafka cannot shrink partitions or change RF in place and a restore that cannot reach the recorded state must not report `Succeeded`. Restored topics are created directly through the Admin API, so on the target they are **unmanaged** (no `KafkaTopic` CR); that is the accepted tradeoff of an Admin-API-only driver. Restoring a topic whose replication factor exceeds the target cluster's broker count fails at `--create`. Topic configs are restored **additively** (`kafka-configs --add-config`): a config the backup recorded is re-applied, but a config added to a live topic after the backup is not removed, so an in-place restore does not return a topic's config set to its exact backup-time state (partition count and replication factor are the only shape the restore reconciles or fails loudly on). - -One consequence of the Admin-API approach: if a topic is declared in the Kafka app's `spec.topics`, the Strimzi Topic Operator owns it and reconciles its config from the `KafkaTopic` CR, reverting any dynamic config an in-place restore sets that the CR does not list. So this strategy is durable for **out-of-band** topics (created directly, no CR); for CR-declared topics the `KafkaTopic` CR / GitOps is the source of truth. A to-copy restore onto a fresh empty cluster is unaffected. For message-data durability, use a volume-snapshot strategy instead. See `examples/backups/kafka-metadata/` for the end-to-end flow. - -Restore is not transactional: it applies topics one at a time as it reads the object, so a failure part-way through (an RF mismatch, an unreachable broker) leaves the topics already created behind — re-running the restore is safe (existing topics are reconciled, not recreated). Like the Rabbitmq driver, this one owns its object outright and deletes it from the bucket when its `Backup` is deleted — via a one-shot Job the Backup's removal waits on — so a retention-pruned `Plan` does not accumulate objects; the delete is **best-effort** with the same give-up conditions and `backups.cozystack.io/skip-artifact-cleanup` escape hatch documented for Rabbitmq above. One caveat specific to this driver: its image ships an older `curl` (7.76.1) whose `--aws-sigv4` omits a non-default port from the SigV4 canonical host, which every S3 backend then rejects with `403 SignatureDoesNotMatch` on a ported endpoint (fixed in curl 7.86.0). The strategy script works around it with `--connect-to` — it signs and sends a portless URL and redirects the connection to the real port — so a ported endpoint (the `backupStorage.endpoint` fallback `…:8333`, `provisionBucket: false`, or SeaweedFS with `s3.ingress.enabled: false`) works too; the sibling drivers run curl 8.x and need no such workaround. Export time scales with topic count — the backup spends two Kafka CLI invocations (each a fresh JVM, ~1.5–3s) per topic — so a cluster with many hundreds of topics takes tens of minutes; the run is bounded at the Job layer by `activeDeadlineSeconds` (default 30 minutes, from the same wait the readiness precondition uses), so a wedged or unschedulable run is failed by Kubernetes as `DeadlineExceeded` — the pod is killed before the script's final upload, so no object is left orphaned — rather than requeuing forever. A cluster whose export legitimately runs longer raises the bound with the `backupTimeout` BackupClass parameter (a Go duration, e.g. `2h`), which round-trips through the `Backup` so a restore is bounded by the same value. diff --git a/docs/operations/resource-presets.md b/docs/operations/resource-presets.md deleted file mode 100644 index 95a8fb59a..000000000 --- a/docs/operations/resource-presets.md +++ /dev/null @@ -1,52 +0,0 @@ -# Resource presets - -Every cozystack app exposes a `resourcesPreset` field whose value selects a CPU and memory reservation. Presets follow a cloud-style `.` naming convention. Setting `resources:` explicitly overrides the preset. - -## Series - -| Series | CPU:Memory ratio | When to use | -| ------ | ---------------- | ------------------------------------------------- | -| `t1` | 1:0.5 | Tiny / burstable, low memory | -| `c1` | 1:1 | Compute-balanced, CPU-bound workloads | -| `s1` | 1:2 | Standard — proxies, caches, lightweight services | -| `u1` | 1:4 | Universal — databases and messaging | -| `m1` | 1:8 | Memory-heavy — search, analytics, large caches | - -## Watch out: legacy and instance-type `medium` differ - -Legacy `medium` had **1 CPU / 1Gi**. The new `*.medium` sizes have **2 CPU** (in any series). The names overlap but the resources do not. The migration table below stays correct — `medium → c1.small (1 CPU / 1Gi)` — but if you read the instance-type sizing matrix first and pick `c1.medium` "to keep things the same", you will double your CPU. When in doubt, consult the legacy-to-instance-type mapping at the bottom of this page. - -## Sizes - -| Size | CPU | t1 mem | c1 mem | s1 mem | u1 mem | m1 mem | -| ---------- | ---- | ------ | ------ | ------ | ------ | ------ | -| `nano` | 250m | 128Mi | 256Mi | 512Mi | 1Gi | 2Gi | -| `micro` | 500m | 256Mi | 512Mi | 1Gi | 2Gi | 4Gi | -| `small` | 1 | 512Mi | 1Gi | 2Gi | 4Gi | 8Gi | -| `medium` | 2 | 1Gi | 2Gi | 4Gi | 8Gi | 16Gi | -| `large` | 4 | 2Gi | 4Gi | 8Gi | 16Gi | 32Gi | -| `xlarge` | 8 | 4Gi | 8Gi | 16Gi | 32Gi | 64Gi | -| `2xlarge` | 16 | 8Gi | 16Gi | 32Gi | 64Gi | 128Gi | -| `4xlarge` | 32 | 16Gi | 32Gi | 64Gi | 128Gi | 256Gi | - -Ephemeral storage is 2Gi for every preset. - -## Legacy flat names (deprecated) - -The following short names existed before the instance-type rename and remain accepted for backward compatibility. They render exactly the CPU and memory they did before — the legacy block in `cozy-lib` returns the original values verbatim. The 1:1 mapping is: - -| Legacy | CPU | Memory | Instance-type equivalent | -| -------- | ---- | ------ | ------------------------ | -| `nano` | 250m | 128Mi | `t1.nano` | -| `micro` | 500m | 256Mi | `t1.micro` | -| `small` | 1 | 512Mi | `t1.small` | -| `medium` | 1 | 1Gi | `c1.small` | -| `large` | 2 | 2Gi | `c1.medium` | -| `xlarge` | 4 | 4Gi | `c1.large` | -| `2xlarge`| 8 | 8Gi | `c1.xlarge` | - -Legacy names are scheduled for removal in a future cozystack release. New manifests should use the instance-type form. `cozystack-api` emits a `klog` warning whenever an app CR carries a legacy value, naming the suggested replacement. - -## Automatic migration - -Platform upgrades run `migration 39` as a pre-upgrade hook. It walks every `HelmRelease` `spec.values` and every app CR under `apps.cozystack.io/v1alpha1`, rewriting legacy `resourcesPreset` values in place using the table above. The conversion is idempotent and best-effort: a failure on one object logs a warning and leaves the rest of the migration to complete. Set `MIGRATION_DRY_RUN=1` to preview the patches without applying them. diff --git a/docs/operations/system-memory-limits.md b/docs/operations/system-memory-limits.md deleted file mode 100644 index d20bf5aed..000000000 --- a/docs/operations/system-memory-limits.md +++ /dev/null @@ -1,140 +0,0 @@ -# System Component Memory Limits - -Cozystack gives every container in a system namespace a memory limit, and sets explicit requests and limits on the node DaemonSets. This page explains why that is not merely resource hygiene, how to tune it, and what it deliberately does not cover. - -## Why a memory limit, and not a PriorityClass - -Talos Linux v1.12 introduced a userspace OOM handler, enabled by default, that reacts to memory pressure before the kernel OOM killer does. Its only input from the machine is its own config document; everything else it reads straight out of cgroupfs, and it holds no Kubernetes client at all. `PriorityClass` — `system-node-critical` included — therefore has no bearing on which cgroup it picks. - -Setting a priority on a system component to stop these kills looks like a fix and changes nothing about them. Take that claim narrowly, because priority is far from inert elsewhere: it still drives scheduler preemption, kubelet eviction ordering, and the `oom_score_adj` kubelet hands the kernel OOM killer. None of those three is what kills these pods. The one ordering input this handler has is the Kubernetes **QoS class**, inferred from the cgroup path rather than from any pod object — a different axis from priority, so a `system-node-critical` pod with no memory limit is an ordinary candidate like any other. - -The handler scores each pod cgroup with a CEL expression. The default in Talos v1.13.6, the version Cozystack currently ships, is: - -``` -memory_max.hasValue() ? 0.0 : - {Besteffort: 1.0, Burstable: 0.5, Guaranteed: 0.0, Podruntime: 0.0, System: 0.0}[class] * - double(memory_current.orValue(0u)) -``` - -Any cgroup scoring zero is dropped from the candidate set entirely. A pod whose containers all carry a memory limit has `memory.max` set on its pod cgroup, scores `0.0`, and can never be selected. A pod without one stays a candidate no matter how little memory it is using. - -Three consequences follow, and all three are easy to get wrong: - -- Only a **limit** grants immunity. A memory **request** merely moves the pod from BestEffort to Burstable, which under the v1.13.6 default `strictCgroupClassOrdering: true` means "killed second" rather than "not killed" — Burstable cgroups are considered only once no BestEffort one is eligible, and the score then breaks ties within the class. That setting arrived in v1.13.4; on v1.13.0 through v1.13.3 the score alone decided, so a large Burstable pod could outrank a small BestEffort one. -- **Every** container in the pod needs a limit, init containers included. Kubelet only sets pod-level `memory.max` when all of them have one, so a single limit-free sidecar puts the whole pod back in the candidate set. -- CPU limits are irrelevant here. The ranking expression is given the cgroup's path, its QoS class, and `memory.max`, `memory.current` and `memory.peak` — no CPU information of any kind. - -Victim selection is also decoupled from the trigger. The cgroup that caused the pressure and the cgroup that gets `SIGKILL`ed are unrelated by design. In practice the pods carrying limits are overwhelmingly tenant workloads — managed applications are sized through resource presets, and a tenant namespace with `resourceQuotas` configured gets a default limit of its own — while system components carried none until the change this page describes. That inverts the intended order: a tenant workload thrashing against its own multi-gigabyte limit drives node-wide memory PSI, and `metallb-speaker` or `linstor-satellite`, using a few dozen megabytes and entirely uninvolved, is killed for it, repeatedly, until the pressure subsides. - -## What Cozystack does - -**A default LimitRange in every system namespace.** The `cozystack-operator` maintains a `LimitRange` named `cozystack-system-defaults` in each namespace it reconciles whose name does not begin with `tenant-`, defaulting container memory for anything that declares none. This is the layer that actually closes the problem, because it covers current components, components added later, and containers whose upstream chart exposes no `resources` knob. - -**Explicit requests and limits on node DaemonSets.** Charts additionally set real values on the DaemonSets that run on every node — the cilium agent and its init containers, metallb speaker, the frr-k8s controller and its sidecars, the linstor satellite along with plunger and drbd-logger, virt-handler, fluent-bit, node-exporter, multus and its init container, velero node-agent, and all three kubevirt-csi-node containers. Requests there are fitted to observed usage, which is a real signal for the scheduler; the LimitRange cannot supply that, because it applies one number to every container in the namespace and so has to keep its default request deliberately tiny. kube-ovn is absent from that list because its vendored chart already sets both. - -The operator's LimitRange stops at the `tenant-` prefix, so tenant namespaces never receive it. A tenant namespace gets a default of its own only from the tenant chart's `tenant-range-limits`, which is rendered only when `resourceQuotas` is configured on the tenant and is empty by default. A tenant workload left without a memory limit therefore stays an eviction candidate, which is the upstream design working as intended and is what restores the ordering described above. - -## Tuning - -Two installer values, both empty by default so the operator's own defaults apply: - -| Value | Operator flag | Default | -|---|---|---| -| `cozystackOperator.systemNamespaceMemoryLimit` | `--system-namespace-memory-limit` | `4Gi` | -| `cozystackOperator.systemNamespaceMemoryRequest` | `--system-namespace-memory-request` | `32Mi` | - -The limit is a ceiling, not a reservation, so it is deliberately set far above real usage — the point is that `memory.max` exists, not that it binds. Raising it is close to free; lowering it is where the risk lives. - -**The limit must stay above the largest memory request in any system namespace.** A defaulted limit below a container's own request is rejected at admission, and the pod simply will not start. List the requests before lowering it — the operator marks exactly the namespaces it treats as system with `cozystack.io/system=true`, the same condition under which it creates the LimitRange: - -```bash -for ns in $(kubectl get ns -l cozystack.io/system=true -o jsonpath='{.items[*].metadata.name}'); do - kubectl get pods -n "$ns" -o json | jq -r --arg ns "$ns" ' - .items[] - | [.spec.containers[], (.spec.initContainers // [])[]][] - | select(.resources.requests.memory != null) - | "\($ns)\t\(.name)\t\(.resources.requests.memory)"' -done | sort -u -``` - -**Keep the request small.** The operator always pairs the default limit with a default request, because a `LimitRange` that sets `default` without `defaultRequest` makes each container's request equal its limit and reserves the whole ceiling at schedule time. Note that leaving `systemNamespaceMemoryRequest` empty does not produce that state: an empty installer value omits the flag, which selects the operator's own `32Mi`. The knob is there to be raised or lowered, and clearing it is not a way to switch the request off. - -The operator also refuses to start when the request exceeds the limit. A `LimitRange` whose `defaultRequest` is above its `default` is rejected by the API server, which would wedge namespace reconciliation for every system package, so the check happens at startup rather than at apply time. - -Setting the limit to `0` disables the feature and removes the LimitRanges the operator previously created, so the knob is reversible. Leaving it empty is not the same thing — that selects the operator's `4Gi` default. - -A LimitRange only mutates at admission. Existing pods keep running without limits until they restart, so the protection lands progressively as workloads roll rather than the moment the setting is applied. - -## Verifying - -Confirm a pod cgroup actually carries `memory.max` — this is the property that matters, not the QoS class. Talos runs kubelet with the `cgroupfs` driver on a unified cgroup v2 hierarchy, so a pod cgroup is a directory named for the pod UID, dashes and all: - -```bash -POD_UID=$(kubectl get pod -n -o jsonpath='{.metadata.uid}') -NODE=$(kubectl get pod -n -o jsonpath='{.spec.nodeName}') -NODE_IP=$(kubectl get node "$NODE" -o jsonpath='{.status.addresses[?(@.type=="InternalIP")].address}') -talosctl -n "$NODE_IP" read "/sys/fs/cgroup/kubepods/burstable/pod$POD_UID/memory.max" -``` - -A byte count rather than the literal `max` means the pod is out of the victim set. Note that `talosctl -n` takes a machine address rather than a Kubernetes node name, which is why the address is looked up instead of being reused from `nodeName`. - -Mind the QoS segment of that path, and do not extrapolate it. BestEffort and Burstable pods live under `kubepods/besteffort/` and `kubepods/burstable/`, but there is no `guaranteed` directory: kubelet creates QoS-level cgroups for those two classes only, so a Guaranteed pod sits directly at `kubepods/pod`. To avoid guessing, list the pod directories two levels down instead: - -```bash -talosctl -n "$NODE_IP" ls -d 2 -t d /sys/fs/cgroup/kubepods -``` - -`talosctl read` wants an `os:admin` talosconfig and a single node per call. Reading the same file through `kubectl debug node/$NODE --profile=sysadmin` under `/host/sys/fs/cgroup` also works, but it depends on the kubelet, on scheduling, and on a namespace that admits a privileged pod — all shakier than the Talos API in precisely the situation that makes you run this check. - -Inspect what the handler has actually killed: - -```bash -talosctl -n get oomactions -o yaml -``` - -Each entry carries the score the victim was selected on, the command lines of the processes in it, and a dump of the trigger context it fired under. Ask for `-o yaml`: the default table shows only a score, and its `Time` column reads a field the spec never sets, so it renders empty. This is a ring buffer of the last 50 actions held in memory, so it does not survive a `machined` restart and is no substitute for an alert — but it is still the better of the two signals here, being structured and complete where the logs are neither. - -Once every eligible pod in a namespace carries a limit, the healthy signature is the controller still triggering under pressure and finding nothing it is allowed to kill: - -```bash -talosctl -n logs controller-runtime | grep OOMController -``` - -Both halves of that signature — `OOM controller triggered`, then `no eligible cgroup to kill` — are emitted at the default log level, so neither needs a debug flag. Note that the structured fields are encoded as JSON rather than logfmt, so the second line reads `no eligible cgroup to kill {"component": "controller-runtime", "controller": "runtime.OOMController", "ranked": 0}`. Grep for `"ranked"` or for the message text; `ranked=` matches nothing and reads as though the handler were not running. The trigger firing is not itself a fault. - -`talosctl dmesg` carries the same lines and is the more common reflex, but it is the weaker source: that path strips log levels and timestamps, truncates at 976 bytes, and suppresses the first four occurrences of each ranking error — precisely the lines worth having if scoring ever misbehaves. - -## What this does not cover - -**Kubernetes static pods.** `kube-apiserver`, `kube-controller-manager` and `kube-scheduler` are managed by Talos rather than by any chart. A `cozystack-system-defaults` LimitRange does reach `kube-system`, since `cozystack-scheduler` installs there, but it cannot touch them: a LimitRange defaults resources at API-server admission, and kubelet builds static pods straight from files on disk without ever passing through it. Sizing those is a Talos machine-config matter. - -**A handful of vendored containers with no upstream `resources` knob** — the four frr-k8s `cp-*` init containers, the kube-ovn `hostpath-init` and `install-cni` init containers, and `cozy-proxy`, whose chart exposes no resources value at all. These are covered by the namespace LimitRange and nothing else. That is enough for OOM immunity, since the defaulted limit is what puts `memory.max` on the cgroup, but their request is then the generic default rather than a figure fitted to measured usage, so the scheduler gets a weaker signal for them than for the DaemonSets above. Lifting that needs changes upstream. - -**Optional components** `hami` and `kilo` carry no chart-level values, on the grounds that inventing numbers for components with no usage measurements behind them is worse than the blanket default. - -## When the trigger itself is the problem - -Giving system components limits stops them being *victims*. It does not stop the handler *triggering*, and a node under genuine sustained pressure will keep firing. The v1.13.6 default trigger is: - -``` -(multiply_qos_vectors(d_qos_memory_full_total, {System: 8.0, Podruntime: 4.0}) > 3000.0 && - multiply_qos_vectors(qos_memory_full_avg10, {System: 1.0, Podruntime: 1.0}) > 5.0 && - time_since_trigger > duration("5s")) || -(memory_full_avg10 > 75.0 && time_since_trigger > duration("10s")) -``` - -The first clause is QoS-aware, which is what keeps unrelated pressure from firing it, and it reached that shape over three changes rather than one: [siderolabs/talos#12602](https://github.com/siderolabs/talos/pull/12602) replaced the original global-PSI trigger with the per-QoS form in v1.13.0, [#12632](https://github.com/siderolabs/talos/pull/12632) added the `qos_memory_full_avg10 > 5.0` conjunct to make it less sensitive, and [#13725](https://github.com/siderolabs/talos/pull/13725) added the `5s` cooldown in v1.13.6. The second clause is a global-PSI backstop that is still cause-blind, and a single workload thrashing inside its own cgroup limit can drive root `memory_full` above 75 while the node has free RAM. The `10s` term makes that clause fire at most once per 10 seconds, which is a useful fingerprint when reading the controller log. - -If a cluster trips the backstop persistently, it can be relaxed through an `OOMConfig` machine-config document — at the cost of raising the last-resort guard before the kernel OOM killer takes over. The document also accepts `cgroupRankingExpression`, `strictCgroupClassOrdering` and `sampleInterval`; anything left out keeps its default, so overriding the trigger alone is enough here: - -```yaml -apiVersion: v1alpha1 -kind: OOMConfig -triggerExpression: |- - (multiply_qos_vectors(d_qos_memory_full_total, {System: 8.0, Podruntime: 4.0}) > 3000.0 && - multiply_qos_vectors(qos_memory_full_avg10, {System: 1.0, Podruntime: 1.0}) > 5.0 && - time_since_trigger > duration("5s")) || - (memory_full_avg60 > 90.0 && time_since_trigger > duration("60s")) -``` - -Prefer fixing the workload that is generating the pressure. Persistent triggering means a pod is sitting at its memory ceiling and reclaiming constantly, and raising that pod's limit addresses the cause rather than the symptom. diff --git a/docs/release.md b/docs/release.md index c53b7490d..175bd37fc 100644 --- a/docs/release.md +++ b/docs/release.md @@ -1,6 +1,6 @@ # Release Workflow -This document is both the process design (what the release model looks like) and the operational playbook (what to actually do, what breaks, what to verify). Companion to [`agents/changelog.md`](./agents/changelog.md), which is the canonical changelog process. +The release documentation is both the process design (what the release model looks like) and the operational playbook (what to actually do, what breaks, what to verify), split into one page per topic under [`release/`](./release/). Companion to [`agents/changelog.md`](./agents/changelog.md), which is the canonical changelog process. ## When to use this guide @@ -15,643 +15,31 @@ You are about to: If you are about to generate a changelog only, jump straight to [`agents/changelog.md`](./agents/changelog.md). -## Introduction - -Cozystack uses a staged release process to ensure stability and flexibility during development. - -There are three types of releases: - -- **Release Candidates (RC)** – Preview versions (e.g., `v1.2.0-rc.1`) used for final testing and validation. -- **Regular Releases** – Final versions (e.g., `v1.2.0`) that are feature-complete and thoroughly tested. -- **Patch Releases** – Bugfix-only updates (e.g., `v1.2.1`) made after a stable release, based on a dedicated release branch. - -All three are matched by `tags.yaml`'s regex `^v\d+\.\d+\.\d+(-(alpha|beta|rc)\.\d+)?$`. The tag push is the trigger for the whole pipeline. **Pre-release tags (`-alpha` / `-beta` / `-rc`) are cut with the [`Cut Pre-release Tag`](../.github/workflows/cut-prerelease.yaml) workflow** (manual dispatch from `main` or `release-X.Y`) — it pushes the tag as the CI app at the dispatch branch's tip, so GitHub fills `base_ref` (`tags.yaml`'s `Get base branch` step refuses tags pushed without a base) and the push triggers `tags.yaml` (a tag pushed with the default `GITHUB_TOKEN` would not). Stable `vX.Y.Z` tags are never pushed by hand at all — they are cut write-once by the promote flow at a PR merge commit. Only `-rc.N` pre-releases feed the promotion flow ([`promote-rc.yaml`](../.github/workflows/promote-rc.yaml) accepts `vX.Y.Z-rc.N` alone); `-alpha.N` / `-beta.N` tags are built and published for download and validated on demand with the [`e2e-tag.yaml`](../.github/workflows/e2e-tag.yaml) button, but are never promoted to a stable release. - -## Release Candidates - -Release candidates are Cozystack versions that introduce new features and are published before a stable release. Their purpose is to help validate stability before finalizing a new feature release. - -Release candidates are given numbers `vX.Y.0-rc.N`, for example, `v1.2.0-rc.1`. The first one is cut from `main`, once all major features for the upcoming release have merged and the release enters its testing phase. - -**Cutting the first rc freezes the line.** [`cut-prerelease.yaml`](../.github/workflows/cut-prerelease.yaml) creates `release-X.Y` at the tagged commit, and from that point the release's content is closed: - -- Every later cut for that line — `rc.2`, `rc.3`, an `alpha`/`beta`, or a patch-line rc — must be dispatched from `release-X.Y`. A dispatch from `main` is refused. -- Fixes reach the release only by cherry-pick or backport onto `release-X.Y` (see [Backports](#backports)). -- `main` reopens immediately for the next minor, so feature work never has to wait for the release to ship. - -This is what makes an rc mean something. Previously `release-X.Y` was created only when the stable release merged, so `rc.2` was cut from `main`'s tip and silently absorbed everything that had landed since `rc.1` — the shipped release could contain code that no rc had ever validated. - -**Un-freezing is manual and deliberate.** If an `rc.1` turns out to be unusable and the line has to be re-cut from `main`, delete `release-X.Y` by hand first; the refuse step blocks every other route back to a `main` dispatch, which is the point of it. Nothing automates the deletion, and nothing should — throwing away a frozen line is a decision worth making explicitly. - -Each RC contributes to a cumulative set of release notes that will be finalized when `vX.Y.0` is released. After testing, if no critical issues remain, the last good rc is **promoted** to the regular release `vX.Y.0` — the exact rc images retagged by digest, never rebuilt and never tagged from a later commit (see [Regular Releases](#regular-releases)). Promotion cuts the write-once `vX.Y.0` tag at the promote PR's merge commit, fast-forwards the `release-X.Y` maintenance branch the freeze already created, and opens the way for patch releases. - -## Regular Releases - -A regular release `vX.Y.0` is **promoted from a release-candidate that already passed e2e** — never tagged by hand and never rebuilt. The bytes shipped as `vX.Y.0` are the exact `vX.Y.0-rc.N` images, retagged by digest. We'll use `v1.2.0` as an example. - -```mermaid -gitGraph - commit id: "feature" - commit id: "feature 2" - commit id: "feature 3" tag: "v1.2.0-rc.1" -``` - -A regular release sequence runs as follows: - -1. Cut the first release candidate (`v1.2.0-rc.1`) from the last good commit on `main`: run the [`Cut Pre-release Tag`](../.github/workflows/cut-prerelease.yaml) workflow (manual dispatch **from `main`**) with the tag. It tags `main`'s HEAD as the CI app, then **creates `release-1.2` at that commit, freezing the line**; `tags.yaml` then builds the rc images, publishes the rc prerelease, pushes the digest-vendored `release-1.2.0-rc.N` staging branch, and runs its mandatory `rc-e2e` job by calling [`e2e-tag.yaml`](../.github/workflows/e2e-tag.yaml) against that published tag. -2. Watch the rc's mandatory full E2E and wait for it to pass, then complete the other checks in [Pre-release verification checklist](#pre-release-verification-checklist). If the latest `tags.yaml` run cannot provide a green `rc-e2e`, a successful manual dispatch of [`e2e-tag.yaml`](../.github/workflows/e2e-tag.yaml) for the same tag is equivalent gate evidence. `main` is already open for the next minor, so anything landing there is **not** in this release: fixes for `1.2` are cherry-picked onto `release-1.2`, and a later rc is cut by dispatching the workflow **from `release-1.2`**. **Optional:** once the notes are worth reviewing, press the `Generate RC Changelog` button ([`changelog-rc.yaml`](../.github/workflows/changelog-rc.yaml)) to generate `docs/changelogs/v1.2.0.md` now and bank it on the `release-1.2.0-rc.N` staging branch — so there is time to review and hand-edit it before promotion. Skipping the button changes nothing; promotion generates the changelog itself. - - ```mermaid - gitGraph - commit id: "feature" - commit id: "feature 2" - commit id: "feature 3" tag: "v1.2.0-rc.1" - branch release-1.2 - checkout main - commit id: "feature 4 (next minor)" - checkout release-1.2 - commit id: "cherry-picked fix" tag: "v1.2.0-rc.2" - ``` - -3. Once the checks are green, run the [`promote-rc.yaml`](../.github/workflows/promote-rc.yaml) workflow (manual dispatch) with that rc tag. Its `parse` job verifies E2E before any staging: it accepts a successful `rc-e2e` job in the latest `tags.yaml` push run for the tag, or any retained successful manual `e2e-tag.yaml` run whose expanded E2E job name targets the tag. The emergency `skip_e2e_gate` input bypasses this check, logs a loud warning, and marks the promote PR with ⚠️. Before its first registry write, promotion also proves that the selected `main` or `release-X.Y` target already contains the candidate-aware PR gate, finalizer and trusted verifier; backport this pipeline to an existing maintenance branch before promoting its next patch. Promotion **creates no stable name before merge**: dispatch does write to the registry — it publishes one `promotion-*` packages candidate, and that tag is real and publicly listable — but it creates no `vX.Y.Z` tag, moves no `latest`, and publishes no stable installer, so nothing a consumer resolves changes until the PR merges. It: - 1. Rewrites the rc version substring to `1.2.0` and commits that exact tree, serializes its `packages/` directory under a run-specific temporary OCI tag, then adds a second commit pinning the candidate's immutable digest in the installer before pushing `release-1.2.0`. Container digests remain exactly the rc's; the two commits give the OCI revision an honest source SHA without pretending the artifact can contain its own digest. - 2. Drafts the `v1.2.0` release and uploads the (restamped) assets. - 3. Generates `docs/changelogs/v1.2.0.md` (in a parallel job, detached at the rc tag) — or, if you pressed the rc-time `Generate RC Changelog` button, copies the file already banked on the `release-1.2.0-rc.N` staging branch instead of regenerating — and commits it onto the `release-1.2.0` branch, so the changelog is reviewed as part of the promotion and finalize can publish the release with it already in place. Non-blocking: if generation fails the PR still opens, carrying a ⚠️ line that says the changelog is missing. - 4. Opens the `cozystack/website` "update managed apps reference" PR (`update-docs-v1.2.0` branch), generating the docs from the `release-1.2.0` staging branch via `FETCH_REF`. Non-blocking, and **do not merge that PR until `v1.2.0` is published** — merging early breaks the live site's version routing (see [Phase 3](#phase-3--update-website-docs-now-the-backstop)). - 5. Opens the `chore(release): promote v1.2.0-rc.N -> v1.2.0` PR into `release-1.2`, labelled `release` only. The PR body records whether E2E was verified or bypassed, plus ✅/⚠️ changelog and website-docs lines. E2E does not run on this promote PR by default because the immutable rc already passed the mandatory full suite; a maintainer may add `full-e2e` to run it again. The stable retag itself is deferred to the merge (step 5), so an abandoned promotion leaves no stable-named images and cannot wedge a re-promotion; retention protects the temporary candidate for as long as this release PR remains open, then may remove it after 30 days. - - The PR targets the maintenance branch, not `main`: `promote-rc.yaml` prefers `release-X.Y` whenever it exists, and since the rc freeze it always does. The digest-vendored `Prepare release` commit therefore stays on the release line instead of landing on `main`. - - ```mermaid - gitGraph - commit id: "feature 3" tag: "v1.2.0-rc.1" - branch release-1.2 - checkout release-1.2 - commit id: "cherry-picked fix" tag: "v1.2.0-rc.2" - branch release-1.2.0 - checkout release-1.2.0 - commit id: "Prepare release v1.2.0" - commit id: "Pin promoted packages artifact" - checkout release-1.2 - merge release-1.2.0 id: "Pull Request" - ``` - -4. Maintainer reviews the PR and the draft release against the [Phase 4 checklist](#phase-4--review-and-merge-the-promote-pr): confirm the E2E-verification line is ✅ (or explicitly accept its ⚠️ bypass), the changelog line is ✅, and note the website-docs line — the `cozystack/website` docs PR that promotion parked, which stays unmerged for now. E2E does not run on this promote PR by default. Then merge — **do not squash-merge**, the stable tag must attach to a real merge commit. GitHub removes the merged branch `release-1.2.0` (the repo has auto-delete-on-merge enabled). -5. CI workflow triggers on merge (this is where every consumer-visible or write-once side effect happens, after the rc E2E gate and PR review): - 1. Pulls the pinned packages candidate by digest and verifies that it matches the merged `packages/` tree apart from the artifact's impossible self-reference, carries no rc image tags, and preserves the original rc artifact's container `repo@digest` set. - 2. Creates the tag `v1.2.0` at the newly created merge commit — write-once. The tag is published here for the first time, never moved. - 3. Cuts the write-once `api/apps/v1alpha1/v1.2.0` Go-module tag at the same commit. - 4. Ensures the `release-1.2` maintenance branch exists at the tag commit. Since the rc freeze created it, this is normally a no-op fast-forward: the merge commit is already its tip. - 5. Publishes the release page (`draft` → `latest`), using `docs/changelogs/v1.2.0.md` from the merge commit as the release body. - 6. Retags the verified packages candidate and rc container images by digest to `v1.2.0` (and `:latest` only when `v1.2.0` is the newest published stable), and publishes the stable `cozy-installer` chart — no container rebuild. -6. Once the release is published, merge the parked `cozystack/website` docs PR (opened back at promote time, step 3.iv) so the live site's version routing flips to `v1.2.0` — its versioned docs and `openapi.json` are on GitHub now. The maintainer can then announce the release to the community. - -```mermaid -gitGraph - commit id: "feature 2" - commit id: "feature 3" tag: "v1.2.0-rc.1" - branch release-1.2 - checkout main - commit id: "feature 4 (next minor)" - checkout release-1.2 - commit id: "cherry-picked fix" tag: "v1.2.0-rc.2" - branch release-1.2.0 - checkout release-1.2.0 - commit id: "Prepare release v1.2.0" - checkout release-1.2 - merge release-1.2.0 id: "Release v1.2.0" tag: "v1.2.0" -``` - -Note that `main` never receives the release commit. It forked away at the freeze and carries the next minor's work. - -## Patch Releases - -A patch release now follows exactly the same shape as the regular release above — by the time `vX.Y.0` ships, everything is already happening on `release-X.Y`. The only difference is where the line starts: - -* `release-X.Y` already exists, created by the freeze at `vX.Y.0-rc.1`, so there is no branch to create. -* Patch commits are cherry-picked onto it, and the rc is cut by dispatching **from `release-X.Y`** — the same dispatch used for `rc.2` of the original release. - - -Let's assume that we've released `v1.2.0` and that development is ongoing. -We have introduced a couple of new features and some fixes to features that we have released -in `v1.2.0`. - -Once problems were found and fixed, a patch release is due. - -```mermaid -gitGraph - commit id: "feature 3" tag: "v1.2.0-rc.1" - branch release-1.2 - checkout release-1.2 - commit id: "Release v1.2.0" tag: "v1.2.0" - checkout main - commit id: "feature 4" - commit id: "patch 1" - commit id: "feature 5" - commit id: "patch 2" -``` - - -1. The maintainer cherry-picks patch commits from `main` onto the existing `release-1.2` branch. These must be only patches to features that were present in version `v1.2.0`. - - Cherry-picking can be done as soon as each patch is merged into `main`, or directly before the release. - - The `backport` label automates this: [`backport.yaml`](../.github/workflows/backport.yaml) targets the newest existing `release-X.Y` branch, which during a freeze window is the line being stabilised rather than the last published one. - - ```mermaid - gitGraph - commit id: "feature 3" tag: "v1.2.0-rc.1" - branch release-1.2 - checkout release-1.2 - commit id: "Release v1.2.0" tag: "v1.2.0" - checkout main - commit id: "feature 4" - commit id: "patch 1" - commit id: "feature 5" - commit id: "patch 2" - checkout release-1.2 - cherry-pick id: "patch 1" - cherry-pick id: "patch 2" - ``` - - When all relevant patch commits are cherry-picked, the branch is ready for release. - -2. The maintainer cuts a release candidate (`v1.2.1-rc.N`) via the [`Cut Pre-release Tag`](../.github/workflows/cut-prerelease.yaml) workflow (manual dispatch **from `release-1.2`**), which tags that branch's `HEAD`. CI builds and publishes the rc, pushes the `release-1.2.1-rc.N` staging branch, and runs the mandatory full `rc-e2e` job against the published tag. -3. Watch `rc-e2e` and wait for it to pass, then complete the other release checks. A successful manual `e2e-tag.yaml` run for `v1.2.1-rc.N` is also valid evidence if the latest `tags.yaml` run does not carry a green `rc-e2e`. **Optional:** press the `Generate RC Changelog` button ([`changelog-rc.yaml`](../.github/workflows/changelog-rc.yaml)) to generate `docs/changelogs/v1.2.1.md` at rc time and bank it on the rc staging branch; promotion then reuses it instead of regenerating. -4. Once the checks are green, run [`promote-rc.yaml`](../.github/workflows/promote-rc.yaml) (manual dispatch) with that rc tag. It runs the same five jobs as a regular promotion: the dispatch first gates on the latest tag-push `rc-e2e` or a successful tag-correlated manual E2E run (`skip_e2e_gate` overrides it), verifies that `release-1.2` already carries the candidate-aware pipeline, then commits and publishes the rewritten packages tree under a run-specific temporary `promotion-*` tag, adds a second commit pinning the candidate on the `release-1.2.1` branch, drafts the `v1.2.1` release with the restamped assets, generates or picks up `docs/changelogs/v1.2.1.md` and commits it onto that branch, opens the parked `cozystack/website` docs PR (updating the existing `v1.2/` directory in place, since a patch does not promote `next/`), and opens the promote PR into `release-1.2` with only the `release` label. The promote PR body carries the same ✅/⚠️ E2E, changelog, and website-docs lines and runs no E2E by default; add `full-e2e` manually to force a repeat. As with a regular release every stable name is deferred to merge; retention protects the temporary candidate while this PR is open and, after it merges, while `release-1.2` still pins it — until finalize retags it stable. - - ```mermaid - gitGraph - commit id: "feature 3" tag: "v1.2.0-rc.1" - branch release-1.2 - checkout release-1.2 - commit id: "Release v1.2.0" tag: "v1.2.0" - checkout main - commit id: "feature 4" - commit id: "patch 1" - commit id: "feature 5" - commit id: "patch 2" - checkout release-1.2 - cherry-pick id: "patch 1" - cherry-pick id: "patch 2" tag: "v1.2.1-rc.1" - branch release-1.2.1 - commit id: "Prepare release v1.2.1" - checkout release-1.2 - merge release-1.2.1 id: "Pull request" - ``` - - Finally, when release is confirmed, the release sequence goes on. - -5. Maintainer reviews the PR against the [Phase 4 checklist](#phase-4--review-and-merge-the-promote-pr), confirms the E2E-verification and changelog lines and notes the parked website-docs line, and merges it — **do not squash-merge**. GitHub removes the merged branch `release-1.2.1` (auto-delete-on-merge is enabled). -6. CI workflow triggers on merge (all consumer-visible or write-once side effects, after the rc E2E gate and PR review): - 1. Verifies the pinned packages candidate against the merged tree and the original rc artifact's container digests. - 2. Creates the tag `v1.2.1` at the newly created merge commit — write-once. The tag is published here for the first time, never moved. - 3. Cuts the write-once `api/apps/v1alpha1/v1.2.1` Go-module tag at the same commit. - 4. Publishes the release page (`draft` → `latest`; `latest` moves only if `v1.2.1` is the newest published stable). - 5. Retags the verified packages candidate and rc container images by digest to `v1.2.1` and publishes the stable `cozy-installer` chart — no container rebuild. -7. Once the release is published, merge the parked `cozystack/website` docs PR, then announce the release to the community. - -## What CI does during the release process - -The numbered process above is implemented by seven workflows, including the reusable/manual [`e2e-tag.yaml`](../.github/workflows/e2e-tag.yaml), plus the reusable [`changelog-generate.yaml`](../.github/workflows/changelog-generate.yaml) that two of them share to produce the changelog. Knowing which job does what makes the failure modes much easier to diagnose. - -1. [`cut-prerelease.yaml`](../.github/workflows/cut-prerelease.yaml) — manual dispatch (from `main` or `release-X.Y`): the sole entry point for creating a pre-release tag. Validates the `-alpha`/`-beta`/`-rc` tag, then pushes it (write-once, at the branch tip) as the CI app so `tags.yaml` fires. Cutting the first `vX.Y.0-rc.N` also creates `release-X.Y`, freezing the line; afterwards a `vX.Y.*` dispatch from `main` is refused. Stable tags are never created here. -2. [`tags.yaml`](../.github/workflows/tags.yaml) — fires on any pre-release tag push: `prepare-release` builds and publishes the pre-release and pushes its digest-pinned staging branch, then — **only for `-rc.N` tags** — the mandatory `rc-e2e` job calls `e2e-tag.yaml` in the same run (`-alpha.N` / `-beta.N` skip it and are validated on demand with `e2e-tag.yaml`'s manual button). `generate-changelog` and `update-website-docs` also live here but are **backstops only** — both are normally produced at promotion time (see 4); on a stable tag push each self-skips or no-ops when the promote flow already did the work. These stable-tag backstops only fire because finalize pushes the stable tag with the CI app token (a `GITHUB_TOKEN` push triggers no run — see 5). -3. [`e2e-tag.yaml`](../.github/workflows/e2e-tag.yaml) — reusable from `tags.yaml::rc-e2e` and manually dispatchable for a published tag. It resolves the tag's published disk plus digest-pinned tree and runs the full install, OpenAPI, and Chainsaw suite. Its dispatch run title is the constant workflow name, so the promote gate correlates a manual run through the successful tag-bearing E2E job name rather than the title. -4. [`promote-rc.yaml`](../.github/workflows/promote-rc.yaml) — manual dispatch. Five jobs: `parse` validates the rc tag and requires green full-E2E evidence before any staging; `promote` rewrites and commits the rc tags, publishes that packages tree as a run-specific temporary reproducible candidate, commits its digest pin in the `release-X.Y.Z` tree, and drafts the stable release; `changelog` calls the reusable `changelog-generate.yaml` **in parallel** to produce `docs/changelogs/vX.Y.Z.md` (regenerating it, or copying an rc-time changelog already committed to the `release-X.Y.Z-rc.N` staging branch by `changelog-rc.yaml` — see 7); `website-docs` (needs `parse`, `promote`) opens the `cozystack/website` docs PR from the staging branch via `FETCH_REF` (see [Phase 3](#phase-3--update-website-docs-now-the-backstop)); `open-pr` joins them, commits the changelog onto the staging branch, and opens the `release-X.Y.Z` promote PR with the `release` label but no automatic `full-e2e`. So the changelog and website docs are reviewed as part of the promotion, the already-checked rc suite is not repeated by default, and the PR body carries ✅ verified or ⚠️ bypassed plus ✅/⚠️ changelog and website-docs lines. Both `changelog` and `website-docs` are non-blocking. No stable registry name is created at dispatch. -5. [`.github/workflows/pull-requests.yaml`](../.github/workflows/pull-requests.yaml) verifies a promotion candidate against the prospective merge tree and original rc artifact before the required `E2E Tests` status can turn green. [`pull-requests-release.yaml`](../.github/workflows/pull-requests-release.yaml) fires after merge and repeats that verification before any stable tag, then cuts the write-once stable + Go-module tags, publishes the release **with the merged changelog as its body**, retags the candidate and rc images to stable by digest (`:latest` gated on newest-stable), and publishes the stable chart. -6. [`update-releasenotes.yaml`](../.github/workflows/update-releasenotes.yaml) — fires on pushes to `main` that touch `docs/changelogs/v*.md`; syncs that content into the corresponding GitHub Release body. No longer the primary path (finalize sets the body directly, which is race-free and works for maintenance lines too) — this now covers later edits to a published changelog and manual re-syncs via `workflow_dispatch`. -7. [`changelog-rc.yaml`](../.github/workflows/changelog-rc.yaml) — manual dispatch, **optional**: generate the changelog at rc time instead of waiting for promotion, while there is still time to review it. It calls the same reusable [`changelog-generate.yaml`](../.github/workflows/changelog-generate.yaml) and commits the result to the `release-X.Y.Z-rc.N` staging branch as `docs/changelogs/vX.Y.Z.md`; the promote-time `changelog` job then copies that file instead of running the AI again. Skipping this workflow changes nothing — promote generates the changelog itself, exactly as before. - -### Phase 1 — `prepare-release` (hard gate) - -On an rc tag push: builds images, commits digest pins, creates the draft release, and pushes the `release-X.Y.Z-rc.N` staging branch. (The stable promote PR is opened later by `promote-rc.yaml`, not here. When the stable tag itself is pushed by finalize, a draft already exists, so this job is a no-op — see [Phase 5](#phase-5--pull-requests-releaseyaml-finalize).) - -The commit (`Prepare release vX.Y.Z`, authored by `cozystack-ci[bot]`) is **digest pins and image tags only**: - -- `packages/core/{installer,platform,testing}/values.yaml` -- `packages/system/*/values.yaml` (cozystack-api, dashboard, kamaji, linstor, kubevirt-csi-node, etc.) -- `packages/apps/kubernetes/images/{kubevirt-csi-driver,ubuntu-container-disk-*}.tag` -- `packages/system/dashboard/templates/configmap.yaml` (the `$tenantText` value) - -Things that look surprising in the diff but are normal: - -- **Zero-diff packages**: when buildx fully caches and upstream base images haven't moved, the digest is byte-identical to the previous release and won't appear. Verify the build step actually ran — don't assume "no diff = nothing built." -- **Sudden churn on `ubuntu-container-disk-*` tags**: `cloud-images.ubuntu.com/noble/current/` is a moving target; these often rebuild even without code changes. -- **Switched registry**: if a self-built image moved from `docker.io` to `ghcr.io`, the registry portion of the digest changes — that's a deliberate move, not a regression. -- **`targetVersion` is NOT touched by the release PR.** Platform migration `targetVersion` is bumped earlier in a feature commit (e.g. `[platform] Bump migration targetVersion to 39 for migration 38`). The release PR only re-pins the `platform-migrations` image digest. - -### RC E2E — mandatory check before promotion - -For an rc, `prepare-release` must finish before `tags.yaml::rc-e2e` calls the published-tag lane, so the full suite tests the published disk and digest-pinned staging tree that promotion will reuse. `promote-rc.yaml::parse` then checks the latest `tags.yaml` push run whose `head_branch` is the rc tag and accepts it only when the reusable E2E job succeeded. GitHub exposes called-workflow job names as `E2E Release Candidate / E2E vX.Y.Z-rc.N (full suite)`, which the gate matches by the exact tag-bearing suffix. - -The alternate evidence path scans retained successful `workflow_dispatch` runs of `e2e-tag.yaml` and accepts one whose direct E2E job is named `E2E vX.Y.Z-rc.N (full suite)`. The workflow's run title is always `E2E Release Tag` and therefore cannot correlate the input tag; artifact names also carry the tag but expire independently, so the job name is the strongest available correlator. If Actions retention or manual deletion removes the run/job metadata, or that job is renamed without updating the matcher, the gate fails closed and tells the maintainer to run the E2E Release Tag button again. `skip_e2e_gate=true` is an emergency override, not alternate evidence: it writes a loud warning and a ⚠️ PR-body line. - -### Phase 2 — the changelog (generated at rc time or promotion, not here) - -The changelog for `vX.Y.Z` is produced by [`promote-rc.yaml`](../.github/workflows/promote-rc.yaml)'s `changelog` job (a thin call to the reusable [`changelog-generate.yaml`](../.github/workflows/changelog-generate.yaml)) and committed onto the `release-X.Y.Z` staging branch by `open-pr`, so it rides the promote PR and is on the base branch the moment the release publishes. Finalize then uses that file verbatim as the GitHub Release body. Generating it here — on the stable tag push — would be too late by construction: that tag is created by finalize, which has already published the release. It can also be produced earlier, at rc time, via the optional [`changelog-rc.yaml`](../.github/workflows/changelog-rc.yaml) button — which runs the same reusable core and commits the file to the `release-X.Y.Z-rc.N` staging branch, from which the promote-time `changelog` job copies it (validated) instead of regenerating. - -The `changelog` job runs **in parallel** with `promote`, detached at the rc tag (the "promotion" configuration in §2 of [`agents/changelog.md`](./agents/changelog.md)), using a separate **read-only** GitHub App token for the AI step so the model cannot mutate the repo even with `--allow-all-tools`. Every write — the commit onto the staging branch and the PR — happens in `open-pr` under a write-scoped token. - -Generation is deliberately **non-blocking**: a Copilot outage or exhausted token quota must never block a release. Only the AI step carries `continue-on-error`, and `open-pr` is gated on `promote` alone (`if: !cancelled() && needs.promote.result == 'success'`) so the promote PR opens regardless. When the changelog is missing the PR body says so explicitly — that ⚠️ line is the signal to act on. - -Recovery, in order of preference: - -1. Commit `docs/changelogs/vX.Y.Z.md` to the `release-X.Y.Z` branch by hand (follow [`agents/changelog.md`](./agents/changelog.md)). `promote` preserves it across a re-dispatch, and `open-pr` will not overwrite it with generated output. -2. Re-dispatch `promote-rc.yaml` — generation runs again; anything already on the branch wins. -3. Merge without one and let `tags.yaml::generate-changelog` (the backstop) open a changelog PR against `main` after the fact. The release is published with the draft's body until that merges. - -Known failure modes: - -- Copilot quota exhausted (`COPILOT_GITHUB_TOKEN` 402). Refill or rotate, then re-dispatch. -- AI step timeout (hard 30-min cap). -- Output truncated or whitespace-only — caught by the `Verify changelog` step (`hack/validate-changelog.sh`), which accepts either header convention (`# Cozystack vX.Y.Z` for a minor or `# vX.Y.Z ()` for a patch), and requires the leading release-link comment pointing at `releases/tag/vX.Y.Z`, a `compare/...vX.Y.Z` link ending in this version, and at least one `## ` section — deliberately with no line-count floor, since a complete short patch changelog (v1.5.1 ships in 19 lines) must not be rejected as a fragment. It downgrades to the missing-changelog path rather than shipping a fragment as release notes. - -**`tags.yaml::generate-changelog` is the backstop.** It self-skips when the changelog is already on `main`. It earns its keep in two cases: generation failed during promotion, or the promote PR targeted `release-X.Y` so the file never reached `main`. Since the rc freeze the second case is **every** release, minor and patch alike — the promote PR always targets the release line (see [Regular Releases](#regular-releases)), which makes this backstop the only route by which a published changelog reaches `main`. In that case it **ports the reviewed file from the tag commit verbatim** rather than regenerating — a second AI pass there would spend quota and then overwrite already-published, already-reviewed release notes. - -### Phase 3 — `update-website-docs` (now the backstop) - -The `cozystack/website` "update managed apps reference" PR is normally opened **earlier, at promote time**, by [`promote-rc.yaml`](../.github/workflows/promote-rc.yaml)'s `website-docs` job — not here. That job fetches the README content from the `release-X.Y.Z` staging branch `promote` just pushed (via the website Makefile's `FETCH_REF` variable), so the docs are ready to review alongside the promote PR while the stable tag is still unborn. It refreshes the trunk version pins from the staging ref before promoting `next/` → `vX.Y/`, so a new minor's docs inherit fresh Talos/cozystack pins instead of a stale `next.yaml`. It is **non-blocking**: if it fails (or trips its `FETCH_REF`-support guard against a website checkout that predates that Makefile variable), the promote PR opens with a ⚠️ website-docs line and this tag-time job backfills the same branch. - -**Merge-timing contract:** the website PR must NOT be merged before the release is published (finalize). Merging it early flips the site's latest-version pointer to a version whose versioned docs and `openapi.json` are not on GitHub yet, so every version-pin and API link for the new version 404s. Both the website PR body and the promote PR body say so; park the website PR until the GitHub release for `vX.Y.Z` is live, then merge. - -This tag-time `update-website-docs` job stays as the **backstop**. It runs with `if: !cancelled() && needs.prepare-release.result == 'success'` (surviving a failed/skipped changelog phase, stopping on cancel), decides whether to promote `next/` → `vX.Y/`, runs `make update-all`, stages `content hugo.yaml data/versions`, and force-pushes the same `update-docs-vX.Y.Z` branch. On the normal path — where `promote-rc.yaml::website-docs` already did the work — it no-ops into "No changes to commit". At tag time the stable tag exists, so its `BRANCH=RELEASE_TAG` fetch resolves without needing `FETCH_REF`. For it to fire at all, finalize must push the stable tag with the **CI app token** (see [Phase 5](#phase-5--pull-requests-releaseyaml-finalize)) — a tag pushed with the default `GITHUB_TOKEN` triggers no workflow run. - -If anyone changes the website Makefile to write somewhere else (e.g. `static/`, `i18n/`), the `git add` list must grow in **both** jobs or the PR silently drops files. - -### Phase 4 — review and merge the promote PR - -Reviewer checklist for the `chore(release): promote vX.Y.Z-rc.N -> vX.Y.Z` PR: - -- [ ] The PR body says `✅ RC full e2e was verified`; if it says the gate was bypassed, obtain explicit maintainer acceptance or add `full-e2e` and wait for that opt-in run. -- [ ] `Verify release packages candidate` is green. It pulls the candidate and original rc artifact by digest, compares the candidate to GitHub's prospective merge tree, and feeds the required `E2E Tests` status even when full E2E is not repeated. Do not edit `packages/` on this PR after generation; if the guard reports drift, re-dispatch promotion to create and pin a new run-specific candidate. Note what a green here does *not* cover: GitHub fires no `pull_request` event when the base branch advances, so a `packages/` change merged to the base afterwards is never re-verified on the PR. Finalize repeats the check against the real merge commit and catches that case before any stable name exists — but it catches it after the promote PR has already merged, so a `packages/` change landing on the base while a promote PR is open is worth holding back. -- [ ] The PR body's **website-docs line** is present: if ✅, the `cozystack/website` docs PR is open and **parked** — do NOT merge it until `vX.Y.Z` is published (see [Phase 3](#phase-3--update-website-docs-now-the-backstop)); if ⚠️, the tag-time backstop will backfill it after finalize. -- [ ] Diff is digest pins + image tags only — nothing else. -- [ ] No accidental config drift (a value file you don't recognize). -- [ ] If any chart bumped, check the new digest pulls — `crane manifest ghcr.io/cozystack/cozystack/@` should return. -- [ ] Build artifacts on the draft release page exist and match the expected count. -- [ ] The PR includes `docs/changelogs/vX.Y.Z.md`, it has content, and the entries match the commit range (see [Changelog pre-publish verification](#changelog-pre-publish-verification)). If the PR body carries the ⚠️ "No changelog in this PR" line, resolve that before merging — finalize publishes this file as the release body. - -### Phase 5 — `pull-requests-release.yaml` (finalize) - -Fires on merge of a PR that is merged, carries the `release` label, and is authored by `cozystack-ci[bot]` (the last guard closes the "name a branch `release-X.Y.Z`, get it labelled, merge it" hole). Head branch must match `release-X.Y.Z[-suffix]`. This is where **every consumer-visible or write-once side effect of a promotion happens** — after the rc's mandatory E2E was checked at dispatch and the PR merged, making promotion transactional at stable names. Steps: - -1. **Verify the packages candidate before creating any stable tag.** [`hack/verify-promoted-packages.sh`](../hack/verify-promoted-packages.sh) pulls the candidate by the digest committed in installer values, proves it matches the merged `packages/` tree after normalizing only the impossible self-reference, rejects surviving rc image tags, then follows the candidate's embedded pre-push `platformSourceRef` back to the original rc artifact and compares normalized container `repo@digest` sets. Any package edit after candidate publication or any changed container digest aborts finalize while all stable names are still absent. -2. **Create the tag at the merge commit** (write-once). The merge commit of `Prepare release vX.Y.Z` did not exist before the PR opened, so there is nothing to move — the tag is created here for the first time. A pre-existing tag at a different commit fails the step loudly rather than being force-moved (see [Tag immutability](#tag-immutability)). The checkout uses `persist-credentials: false` so this push authenticates as the **CI app** (via `git remote set-url`), not the default `GITHUB_TOKEN` — a `GITHUB_TOKEN` push creates no workflow run, so a persisted-credential push would silently skip `tags.yaml` entirely and its stable-tag backstops (`generate-changelog`, `update-website-docs`) would never fire. -3. **Cut the `api/apps/v1alpha1/vX.Y.Z` Go-module tag** (write-once, stable only) at the same commit, so Go consumers of `api/apps/v1alpha1` get the release. Moved here from `tags.yaml`, whose `prepare-release` body is skipped for a promoted stable (the draft already exists). -4. **Ensure the maintenance branch `release-X.Y` exists** at the tag commit. Since the rc freeze creates it, this is normally a no-op fast-forward — the merge commit is already the branch tip. Still created if missing; updated fast-forward-only — a non-fast-forward update warns and is left for a maintainer rather than being force-updated. -5. **Publish the draft release**, with `docs/changelogs/vX.Y.Z.md` from the merge commit as its body (an absent or whitespace-only file warns and leaves the draft's body in place, rather than publishing blank notes). `make_latest` is computed against published-non-prerelease tags: prereleases stay `false`; tags older than the current max stay `false` (and the current max is force-restored to `latest` if necessary, so an older patch tag cut after a newer minor won't downgrade `latest`). -6. **Retag the verified packages candidate and rc container images to stable** by digest (`hack/promote-retag.sh`, no container rebuild) and **publish the stable `cozy-installer` chart**. `:latest` (on both the images and the chart) moves only when this release's `make_latest` was `true` — the same decision as step 5, so the release's `latest` and the images' `:latest` never disagree. The chart is packaged with `platformVersion` stamped into its default values so the documented `helm --install --version X.Y.Z` path reports the stable version. - -### Phase 6 — `update-releasenotes.yaml` (sync GitHub Release body) - -Fires on pushes to `main` that touch `docs/changelogs/v*.md`. Reads each `docs/changelogs/vX.Y.Z.md` and PATCHes the matching GitHub Release's `body` if it differs. Since Phase 5 now sets the body directly from the merge commit, this is no longer on the critical path — it covers later **edits** to a published changelog, the backstop PR landing a changelog that reached `main` after the fact, and manual re-syncs via `workflow_dispatch`. It only watches `main`, which is why finalize (not this job) is what populates a release promoted onto `release-X.Y` — since the freeze, that is every release rather than only a patch. - -## Stable tags come from rc promotion - -A stable `vX.Y.Z` is created only by **promoting an existing release-candidate** that already passed e2e — never by rebuilding and never by a cron. - -- [`promote-rc.yaml`](../.github/workflows/promote-rc.yaml) is triggered manually once an rc has gone green. It rewrites the rc version substring in the vendored image tags (the container digests stay the rc's), commits and publishes the resulting declarative packages tree under a unique run-specific `promotion-*` tag, commits that digest pin, and opens the `release-X.Y.Z` staging PR. The PR gate verifies the candidate against the prospective merge and original rc artifact; finalize repeats that check before creating the write-once stable tag at the merge commit, then retags the verified packages artifact and rc's already-built, e2e-passed container digests to the stable tag **by digest** (no container rebuild — see [`hack/promote-retag.sh`](../hack/promote-retag.sh)) and publishes the release. An abandoned promotion leaves no stable-named bytes; its temporary candidate is retention-managed. - -So a commit on a supported `release-X.Y` line ships when a maintainer promotes the next rc for that line — not automatically within 24h. Pushing a stable `vX.Y.Z` tag by hand is **not** a supported path: `tags.yaml` fails fast on a stable tag that has no pre-existing draft ("stable tags come from promote-rc.yaml"), and even so the finalize step would refuse to move a pre-existing tag. Pre-releases (`vX.Y.Z-rc.N`, `-alpha.N`, `-beta.N`) are cut with the [`Cut Pre-release Tag`](../.github/workflows/cut-prerelease.yaml) workflow, which pushes the tag as the CI app; [`tags.yaml`](../.github/workflows/tags.yaml) then fires on that push, builds it, and publishes the pre-release. Cutting via the workflow (rather than a manual `git push`) is what lets repo admins lock `v*` tag creation to the CI app — see the tag-protection note below. - -## Nightly builds - -A nightly is an **installable copy of `main` on GHCR — not a rebuild and not a release**. [`build-main.yaml`](../.github/workflows/build-main.yaml) already builds every push to `main` into the CI registry (OCIR); the nightly promotes that build to the public release registry (GHCR) and proves it installs. - -[`nightly.yaml`](../.github/workflows/nightly.yaml) runs daily (gated by the `NIGHTLY_ENABLED` repo variable) in three stages: - -1. **mirror** — resolve the exact commit `cozystack-packages:main` was built from, then [`hack/nightly-mirror.sh`](../hack/nightly-mirror.sh) copies every cozystack-owned component image OCIR→GHCR **by digest** (bit-for-bit, no rebuild) and re-publishes the rewritten `cozystack-packages` artifact and the `cozy-installer` chart to GHCR, tagged `0.0.0-nightly...` plus a floating `nightly`. -2. **build-disk** — assemble the Talos `nocloud` disk from the upstream siderolabs imager (the profile references only `ghcr.io/siderolabs/*`, so this needs no cozystack image and no rebuild) and publish it as a GHCR OCI artifact (`cozystack-nocloud`) so a nightly is installable on real hardware, not just in e2e. -3. **e2e** — stage the published GHCR closure (rewritten tree + the `cozy-installer` chart pinned to the GHCR packages artifact + the disk) and run the **full** app suite. A nightly has no diff, so Test Impact Analysis does not apply. - -No GitHub release and no `api/apps/v1alpha1/*` Go-module tag are created for a nightly. [`retention.yaml`](../.github/workflows/retention.yaml) prunes old GHCR nightly versions (keeps the newest 14 per package; the floating `nightly`, release tags and untagged versions are never touched) and abandoned packages candidates. A candidate version is eligible only when all of these hold: it carries at least one tag and **every** tag on that manifest matches the strict `promotion-vX.Y.Z-from-vX.Y.Z-rc.N-run--` form, so a manifest that has been retagged stable is excluded; it was last updated more than 30 days ago; its digest is not pinned by `packages/core/installer/values.yaml` at the head of an **open** pull request that is same-repository, authored by `cozystack-ci[bot]`, on a `release-X.Y.Z` branch and carrying the `release` label; and its digest is not pinned by that same file at the tip of `main` or of any `release-X.Y` branch — which is what keeps a candidate safe between the promote PR merging and finalize retagging it. Any such PR head whose pin is not exactly one `digest=sha256:<64 hex>` stops the candidate sweep for that run and fails the job, without affecting the nightly sweep. - -Install a nightly: - -```bash -helm upgrade --install cozystack \ - oci://ghcr.io/cozystack/cozystack/cozy-installer --version 0.0.0-nightly.20260626.15992304129.1 -# ...or --version nightly for the latest -``` - -The matching Talos node image is `ghcr.io/cozystack/cozystack/cozystack-nocloud:0.0.0-nightly.20260626.15992304129.1` (pull with `oras`). - -## Backports - -### The backport bot - -[`backport.yaml`](../.github/workflows/backport.yaml) wraps [`korthout/backport-action`](https://github.com/korthout/backport-action) and fires on a merged `main`-targeted PR carrying one of: - -| Label | Target branch | -|-------|---------------| -| `kind/backport` | the newest existing `release-X.Y` branch | -| `kind/backport-previous` | the second-newest existing `release-X.Y` branch | - -Resolution is dynamic at run time, and it reads the branches themselves: the job lists the repository's branches, keeps the ones matching `release-.`, and sorts them numerically descending — so `release-1.10` ranks above `release-1.9`, which a lexicographic sort gets backwards. `backport` takes the first, `backport-previous` the second, so both name a branch that exists by construction; asking for `backport-previous` when only one line exists fails the job rather than inventing a target. Nothing is derived arithmetically — an earlier version computed the previous line as `Y-1`, which named a non-existent branch whenever a minor was skipped. - -**During a freeze window the newest line is the one being stabilised, not the last published one.** `release-X.Y` is created when the first `vX.Y.0-rc.1` is cut, before `vX.Y.0` is published, so from the freeze until the release `backport` targets the release being stabilised and `backport-previous` targets the last published stable. That is the intent: the frozen branch is the only way into the upcoming release, which is when backports matter most. The trade-off is that for the length of the window the line one step further back has no label pointing at it, so a fix that has to reach it before the new release publishes must be cherry-picked by hand. - -The bot creates a backport PR with title `[Backport release-X.Y] `. When this PR merges, the title prefix used to re-trigger the bot through `pr-labeler.yaml`, which auto-applied `backport` to any `[Backport release-X.Y]`-titled PR. Combined with the org-level `dosubot` re-applying the label, this caused recursive backports. - -The fix (PR #2584): both job `if:` blocks gate on `github.event.pull_request.base.ref == 'main'`. Backport PRs target `release-X.Y`, so they cannot satisfy this — architectural protection, regardless of which bot relabels them. - -### When the bot fails - -If the run triggered by the merge dies without opening a backport PR, look for a run of this workflow that has not finished before retrying — `gh run list --workflow backport.yaml --branch ` — and clear it, because the retry queues behind it rather than replacing it. Do not filter by status: a run whose jobs are waiting for a runner, or which is held behind the concurrency group, is not `in_progress`, and filtering it out is how you conclude nothing is running. `--branch` narrows the list but does not identify the PR, since head branch names are not unique across forks and `gh run list` has no PR filter, so confirm which PR a run belongs to before cancelling it or you cancel someone else's backport. If cancelling does not clear the run it holds the group until GitHub retires it and the retry keeps queueing; that case has not been exercised here. A run whose jobs have all finished can still sit `in_progress`, which looks the same from the PR as a run that died. Then remove whichever backport label the PR already carries and add it back: a label event is the only other trigger, and it qualifies on the label it carries, so re-applying it is what starts a fresh attempt. - -Conflicting cherry-picks produce a draft PR via `conflict_resolution: draft_commit_conflicts`. Look for the bot's comment with the merge-conflict diff. You either: - -- Resolve in the draft branch and undraft, or -- Drop the bot's branch and cherry-pick manually: - -```bash -git checkout release-X.Y -git cherry-pick -x -s -# resolve conflicts -git commit -s -git push origin release-X.Y # or push to a new branch and open a PR -``` - -To find the bot's failed comments across a batch of PRs: - -```bash -for n in $(gh pr list --search "label:kind/backport label:kind/backport-previous merged:>=2026-01-01" --json number --jq '.[].number'); do - echo "=== #$n ===" - gh pr view $n --json comments --jq '.comments[] | select(.author.login == "github-actions" or (.author.login | contains("backport"))) | .body' | head -20 -done -``` - -### Cherry-pick triage before a patch - -A patch release includes bugfixes for code that shipped in the corresponding minor `vX.Y.0`. Use: - -```bash -# 1. Inventory PRs already labeled for backport (merged but not yet on release-X.Y) -gh pr list --search "is:merged label:kind/backport" --limit 100 -gh pr list --search "is:merged label:kind/backport-previous" --limit 100 - -# 2. List commits on main since the release branch diverged that are NOT yet on release-X.Y -git merge-base origin/main origin/release-X.Y -git log ..origin/main --grep="(#" --oneline - -# 3. Open PRs that may need labeling before the cut -gh pr list --state open --base main --label kind/bug -``` - -**Include rule:** - -- `kind/bug` — especially destructive (data loss, crash-loop, OOM, eviction). -- `area/security` / CVE. -- Narrow chart fixes whose blast radius is contained (e.g. one operator's resources). -- Patch-line-policy-matching dependency bumps (e.g. cilium 1.X.Y → 1.X.(Y+1) on a `release-A.B` shipping cilium 1.X — never a minor bump, only a patch within the line the branch already ships). - -**Skip rule:** - -- `kind/feature` — even with `lgtm`. A patch release is not a delivery vehicle for features. -- CI-only changes (`area/ci`, test infrastructure). -- Docs-only changes (those land via `update-website-docs` automatically). -- Large multi-package dependency churn (Dependabot Go-deps bumps). -- PRs whose conventional-commit type is `!` (breaking) or that mix `feat` with `fix`. - -**Borderline cases:** - -- Large refactors with `lgtm` AND an obvious bug payload — prefer extracting the bug fix into a narrower commit and backporting only that. -- PRs labeled both `kind/bug` and `kind/feature` — split them. - -### Backporting code that touches monotonic counters - -Migrations are the canonical case. `packages/core/platform/images/migrations/run-migrations.sh` is a linear counter — it runs `seq $CURRENT_VERSION $((TARGET_VERSION - 1))` and stops if `CURRENT >= TARGET`. This creates a forward-upgrade trap. Walking through it with `release-1.2` as the maintenance branch: - -- `main` has `targetVersion=10` and migrations 1–9 on disk. -- The `release-1.2` branch was cut when `targetVersion=5` (migrations 1–4 on disk). -- You backport a new migration to `release-1.2` at slot 5, and naively bump `targetVersion` 5 → 6 to enable it. -- Customer running 1.2.x runs the new migration, stamps `cozystack-version=6` in-cluster. -- On upgrade to 1.3 (main's `targetVersion=10`), the runner walks `seq 6 9` and runs main's migrations 6–9 — **main's own migration at slot 5 never runs.** The backport claimed that slot on `release-1.2`; main's slot 5 holds an unrelated migration that gets silently skipped. - -Mitigations, in order of preference: - -1. **Don't bump `targetVersion` in the backport.** Just ship the migration file. Prior precedent in the repo: an earlier maintenance branch's ACME backport did exactly this — the migration shipped but ran on no clusters until a later commit raised the counter. Pair this with relaxing the chart-side `{{ fail }}` guard on the maintenance branch (chart-side coalesce) so the new value works without the migration having executed. -2. **If you must bump,** add an idempotent duplicate of the now-skipped main migration at a higher slot. Bounded cost (one extra file per affected migration) and survives the skip window. -3. **Audit cross-branch counter state before deciding.** Compare migration numbering across `main`, `release-X.Y`, and `release-X.(Y-1)`. If a backport would create a skip window on any forward-upgrade path, choose option 1. - -This rule generalizes to any monotonic-counter state: schema versions, feature-flag generations, anything that gates "have I run X yet?" with a single integer. - -## Changelogs - -### Where the canonical process lives - -[`agents/changelog.md`](./agents/changelog.md) is the source of truth. Read it end-to-end before generating; do not infer the process from past commits or memory. The CI runs it under Copilot via the reusable `changelog-generate.yaml` — called by `promote-rc.yaml::changelog` at promote time and by the optional `changelog-rc.yaml` at rc time — and, as a backstop, `tags.yaml::generate-changelog`; locally the same prompt is replayable by following the doc directly. - -### Common changelog failure modes - -These are mistakes that have shipped in real changelogs. Verify against each before merging the changelog PR. - -**1. Commits from outside the release range.** Caused by running `git log ..HEAD` from `main` while generating a patch changelog — `HEAD` on `main` contains everything that landed since the tag plus backports merged to `release-X.Y` after the tag was cut. Use `git log ..` explicitly. The doc was updated to require this after v1.3.1's changelog shipped with 14 entries for what was actually a 1-commit release. - -**2. Original + backport listed as two separate entries.** Each backport must coalesce with its original into a single entry of the form `(in #orig, backport #bp)`. To verify after generation: - -```bash -# Every entry that mentions "backport" should also reference the original PR number -grep -E 'backport #[0-9]+' docs/changelogs/v.md | grep -v '#[0-9]*, backport' -``` - -Output should be empty. - -**3. Wrong PR author.** The squash-merge commit's author is whoever clicked "Merge" — not the person who wrote the code. **Always** resolve via `gh pr view --json author --jq .author.login`, never `git log --format=%an`. This bites hardest for website-repo entries where the same merger handles most PRs. - -**4. Superseding patch, stale changelog.** Tags are write-once, so a critical fix after `vX.Y.Z` ships as the next patch `vX.Y.(Z+1)` rather than moving the tag. If a changelog PR already exists for a tag you are superseding, the changelog work transfers to the new patch. Compare `git log ..` against what the existing `changelog-vX.Y.Z` branch already documents; only add/remove the deltas. If the only new commits are CI-internal or a revert of a feature that never reached a stable tag, no changelog edit is needed. - -**5. PR numbers swapped inside prose.** The entry-format validator checks bullet entries but ignores Feature Highlights paragraphs and Upgrade Notes. Both have caused wrong PR references in shipped changelogs. Verify every `#NNNN` in prose with `gh pr view `. - -**6. Hallucinated entries.** Every entry must correspond to a commit in `git log ..`. Verify by extracting PR numbers from the file and grep-searching the commit range: - -```bash -grep -oE '#[0-9]+' docs/changelogs/v.md | sort -u | while read pr; do - n=${pr#\#} - if ! git log .. --grep="#${n}" --oneline | grep -q .; then - echo "PR $pr in changelog but not in commit range" - fi -done -``` - -**7. Bot accounts as human contributors.** `cozystack-ci[bot]`, `github-actions`, `dependabot`, `renovate`, and any `app/*` login must NOT appear in the `## Contributors` list. They legitimately appear in **per-entry attribution** (e.g. a Renovate-authored PR) — but not in the human roll-call. - -**8. Title duplicated as description.** `* **fix(foo): X**: fix(foo): X (...)` means you wrote the conventional-commit subject twice and never wrote a user-facing description. The brief and the detail must say different things — the detail explains what the change means for users. - -### Changelog pre-publish verification - -Run these checks before merging the changelog PR. Catches problems in roughly the order they occur: - -```bash -PREV=v1.2.0; NEW=v1.2.1 - -# A. Every chart bump is mentioned somewhere in the changelog -git diff --name-only $PREV..$NEW -- 'packages/*/charts/*/Chart.yaml' 'packages/*/*/charts/*/Chart.yaml' | while read f; do - old=$(git show "$PREV:$f" 2>/dev/null | yq '.version // ""') - new=$(git show "$NEW:$f" 2>/dev/null | yq '.version // ""') - if [ "$old" != "$new" ]; then - component=$(basename "$(dirname "$f")") - if ! grep -qi "$component" docs/changelogs/$NEW.md; then - echo "MISSING: $component $old -> $new ($f)" - fi - fi -done - -# B. Out-of-Chart.yaml pins (Talos, tenant K8s, vendored images) -for path in packages/core/talos/values.yaml packages/core/installer/values.yaml packages/apps/kubernetes/values.yaml; do - git diff $PREV..$NEW -- "$path" | head -40 -done -git diff --name-only $PREV..$NEW -- 'images/*/Dockerfile' - -# C. Every cited #NNNN exists and is a merged PR (not an issue) -grep -oE '#[0-9]+' docs/changelogs/$NEW.md | sort -u | sed 's/#//' | xargs -P 20 -I{} sh -c ' - state=$(gh api /repos/cozystack/cozystack/issues/{} --jq ".pull_request.merged_at // \"ISSUE\"" 2>/dev/null) - echo "#{} $state" -' | grep -E 'ISSUE|null|^#[0-9]+ $' - -# D. URL liveness -grep -oE 'https://[^)" ]+' docs/changelogs/$NEW.md | sort -u | xargs -P 10 -I{} sh -c ' - code=$(curl -s -o /dev/null -w "%{http_code}" {}) - if [ "$code" != "200" ]; then echo "$code {}"; fi -' - -# E. Website PR authors are PR authors, not commit authors -grep -oE 'cozystack/website#[0-9]+' docs/changelogs/$NEW.md | sort -u | sed 's|cozystack/website#||' | while read n; do - pr_author=$(gh pr view $n --repo cozystack/website --json author --jq .author.login) - echo "website#$n -> @$pr_author" -done - -# F. Working tree clean except for the changelog -git status --porcelain | grep -v "docs/changelogs/$NEW.md" -# Should output nothing. -``` - -Ship criterion: every chart bump surfaced, no issue-cited-as-PR, no 404 URLs, every website entry attributed via `gh pr view` (not commit author), `git status` shows only the changelog. - -### Cozystack-specific URL quirks - -`cozystack.io` paths are versioned: `/docs/operations/foo/` and `/docs/next/foo/` both 404. Only `/docs/vX.Y/foo/` and the unversioned canonical `/docs/foo/` serve content. AI-generated changelogs invent the unversioned form. Verify URLs with the `curl` loop above. - -### Platform-component coverage - -For a minor release (`vX.Y.0`), changelog entries should surface what an upstream chart bump actually brought in — features, breaking changes, security fixes. PR commit messages usually don't capture this; the upstream `CHANGELOG.md` or GitHub Release notes do. For each bumped `Chart.yaml`: - -1. Read the `sources:` field — typically a GitHub URL. -2. Fetch release notes strictly inside `old < x <= new` via `gh release view --repo / --json body,name`. -3. Summarize in 2–5 user-impact bullets per component (new features, breaking changes, CVEs, important deprecations). Don't reproduce upstream notes verbatim; link to them. -4. If a PR-level entry already mentions the bump, enrich that entry with bullets — don't duplicate the entry. -5. If 3+ bumps have no PR-level mention, introduce a `## Platform Components` section. - -If you can't find upstream notes for a bumped component, list it with version-only info and no bullets. Hallucinated bullets are worse than missing detail. - -## Release-time fires — what's gone wrong recently - -These are real regressions that escaped to users. The pattern in each: code passed CI, shipped in a stable release, broke customers. Read them as a working list of pre-release verification gaps. - -### v1.3.0 — cert-manager ingressClassName regression (fix #2562) - -**Bug:** A commit migrated ACME HTTP-01 to use the modern `acme.cert-manager.io/http01-ingress-ingressclassname` annotation. The matching ingress-shim code that reads that annotation was added by cert-manager upstream PR #8244 and was **never backported** to the `release-1.19` branch — but cozystack 1.3.0 shipped cert-manager v1.19.3. The annotation was silently dropped at runtime and every solver Ingress fell back to the ClusterIssuer's default class `tenant-root`. Let's Encrypt validation broke for every tenant whose `publishing.ingressName != tenant-root`. - -**Blast radius:** v1.3.0, v1.3.1, and v1.1.7 (the migration was cherry-picked to `release-1.1`). - -**Why CI missed it:** the migration commit was self-contained and `helm template` rendered cleanly. There was no E2E that creates a tenant with a non-default ingress class and watches a real Let's Encrypt cert issue. Verification had been done from the docs side ("the API has been available since cert-manager 1.12"), not against the shipped cert-manager source. - -**Would have caught it:** non-root-tenant E2E with LE-staging cert issuance, asserting the solver Ingress lands on the tenant's class. - -### v1.4.0 — kubevirt-instancetypes upgrade failure (fix #2612) - -**Bug:** `packages/system/kubevirt-instancetypes/Makefile` contained `sed -i '/persistent: true/d' templates/preferences.yaml`, which stripped the only child of `preferredTPM`, leaving `preferredTPM:` (null) in six Windows preferences. KubeVirt v1.6.x silently accepted it. The v1.6.3 → v1.8.2 operator bump (2026-04-27) hardened the CRD's OpenAPI schema and started rejecting null for an object-typed field. `helm upgrade` then failed on every cluster with `kubevirt-instancetypes` enabled. - -**Why CI missed it:** the kubevirt-operator bump and the inert `preferences.yaml` were two weeks apart in commit history. CI only tests fresh installs against the new CRDs; it doesn't run `helm upgrade` from prior versions. Schema regression on a vendored asset that hadn't been touched in 18 months. - -**Would have caught it:** `helm template | kubectl apply --dry-run=server -f -` against the freshly-installed CRDs of every bumped operator. Or an upgrade-from-N-1 E2E lane. - -### v1.4.0 — Flux 2.7 → 2.8 readiness deadlock (#2602) - -**Bug:** helm-controller v1.5.0 (shipped in Flux 2.8) changes the default wait strategy to kstatus polling, which polls **every applied resource including child HelmReleases**. The `packages/apps/kubernetes` umbrella has 19 child HRs that each `dependsOn: parent` (with a `lookup` guard so the dependency only activates after the parent exists). Pre-2.8: parent went Ready as soon as Helm returned. Post-2.8: parent waits for children, children wait for parent. Deadlock. - -**Why CI missed it:** the cycle only manifests on the second reconcile (parent exists, so the `lookup` activates the child's `dependsOn`). Fresh-install E2E dodges this — the parent-already-exists branch isn't taken on the first apply. - -**Would have caught it:** apply-mutate-reapply E2E (any chart bump in the kubernetes umbrella triggers a second reconcile). Plus an explicit PR-template requirement: for any flux/helm-controller bump, paste the upstream breaking-changes section into the PR body. - -### Patterns these share - -1. **Fresh-install CI is insufficient.** All three regressions passed fresh-install lanes. -2. **Upstream breaking-defaults bumps are the common shape.** kubevirt CRD hardening, helm-controller default wait strategy, cert-manager API surface drift. Pre-merge reading of upstream changelogs would have caught two of three. -3. **One-engineer-bitten-once is the only safety net for live verification.** The cert-manager bump PR included an explicit live-cluster verification step — because the same engineer had been bitten the prior week. There is no checklist requiring it. - -## Pre-release verification checklist - -For RCs and final releases, run this before merging the release PR. Each item is here because something has shipped without it and broken users. - -- [ ] **The published rc passed mandatory full E2E.** Confirm the promote PR says `✅ RC full e2e was verified`; the normal promote PR itself runs no E2E. Add `full-e2e` manually only when a repeat is required, and treat a ⚠️ bypass line as an explicit release-risk decision. -- [ ] **Upgrade from previous patch** (`vX.Y.(Z-1)`) on a real cluster. `helm upgrade` succeeds, all HelmReleases reach Ready, no CRD schema rejections. -- [ ] **Upgrade from previous minor** (`v(X-1).Y.0`) for RC and minor releases. Same assertions. -- [ ] **At least one tenant with `publishing.ingressName != tenant-root`** and a real Let's Encrypt-staging cert issuance. -- [ ] **Apply-mutate-reapply** on the kubernetes umbrella HelmRelease (catches second-reconcile bugs). -- [ ] **For every CRD-source bump** (kubevirt, cert-manager, flux, cilium, kamaji): `helm template | kubectl apply --dry-run=server` against the freshly-installed CRDs. -- [ ] **For every flux / helm-controller / kubevirt-operator / cert-manager bump:** paste the upstream breaking-changes section of the bump's CHANGELOG into the PR body before merge. -- [ ] **After cutting the tag,** watch `pull-requests-release.yaml::Finalize Release`. If it fails on `Draft release for v... not found`, undraft the release manually and file the workflow regression — this has been a known recurring failure since the `Publish draft release` step lost its explicit `github-token` in refactor `66a756b6`. -- [ ] **The promote PR carries `docs/changelogs/vX.Y.Z.md` and it was verified** per [Changelog pre-publish verification](#changelog-pre-publish-verification). Finalize publishes this file as the release body, so verifying it before merge is verifying the release notes. -- [ ] **The `cozystack/website` docs PR stays parked until publish.** Promotion opens it early; merging it before the GitHub release for `vX.Y.Z` is live 404s the new version's docs and API links. Merge it right after finalize publishes the release (regular-release step 6, patch step 7). - -## CI failures release engineers commonly hit - -| Symptom | Class | Diagnosis | Block release? | -|---------|-------|-----------|----------------| -| `Draft release for vX.Y.Z not found` on every release-* merge | Workflow regression — `Publish draft release` lost its `github-token` in a past refactor; default `GITHUB_TOKEN` cannot list drafts | At `pull-requests-release.yaml:163`. Undraft manually, file the fix | No | -| Changelog Copilot job returns 402 | Token quota — `COPILOT_GITHUB_TOKEN` premium-request quota empty | Both changelog entry points hit it: the optional rc-time `changelog-rc` dispatch and the promote-time `changelog` job (both call the reusable `changelog-generate.yaml`), plus the `tags.yaml` backstop | No — `continue-on-error: true` on the AI step, generate changelog by hand following [`agents/changelog.md`](./agents/changelog.md) | -| E2E `kubernetes-test` fails with `CSINode does not contain driver csi.kubevirt.io` | Test ordering bug | Tenant's `kubernetes-${test_name}-csi` HelmRelease still installing when NFS PVC is created. Fix: wait for `csinode/` to advertise the driver before creating the PVC | Yes — flaky and masks real CSI bugs | -| `tenant-root` HR in perpetual upgrade-rollback loop after OIDC patch | Real bug at the intersection of #2602's readiness change and the cozystack reconcile cadence | Look for `rate: Wait(n=1) would exceed context deadline` in operator logs; multiple tenant child HRs stuck `InProgress` | Yes | -| `cozy-dashboard` ImagePullBackOff from `cozystack-ui:latest` | Registry flake | Known noisy on some OCI mirrors; not currently in the prepull set | No — retry | -| PR CI: `docker push` 409 on `:latest` for the same image across two PRs | Concurrent manifest race on a shared floating tag | The `:latest` tag was previously written by every `make image` regardless of PR. Resolved by the image-tag refactor (`IMAGE_TAG=pr--` in PR builds, `IMAGE_TAG=` only at release time) | No — `gh run rerun --failed` | - -**Heuristic:** workflow-token and Copilot-quota issues are out-of-band — release the tag, fix the workflow in a follow-up PR. Test ordering bugs and tenant-root reconcile storms are real and should block. - -If you find yourself doing the same manual fixup on two consecutive releases (e.g. "undraft the release"), open a workflow-regression issue. Workflow bugs with known manual workarounds rot silently for months. - -## Tag immutability - -Published tags are **write-once** — once a `vX.Y.Z` or rc tag is pushed it is never moved or deleted. (Nightlies are not git tags at all — they are GHCR OCI tags, see [Nightly builds](#nightly-builds).) Moving a tag silently poisons the Go module proxy / pkg.go.dev cache for `api/apps/v1alpha1/vX.Y.Z` and drifts SBOM/provenance toolchains, so the release flow is built so a move is impossible by construction: - -| File | Tag / branch handling | -|------|------------------------| -| [`pull-requests-release.yaml`](../.github/workflows/pull-requests-release.yaml) | Verifies the pinned packages candidate before creating a stable name. Creates `vX.Y.Z` at the PR merge commit **write-once** (create if absent, no-op if unchanged, fail loudly if it would move — the merge commit is new, so there is nothing to move). Cuts the `api/apps/v1alpha1/` Go-submodule tag write-once at the same commit, **stable only** (never rc/beta/alpha). The `release-X.Y` maintenance branch is fast-forward-only. Retags the verified packages artifact and rc container digests to the stable image tag (also write-once at the image level). | -| [`tags.yaml`](../.github/workflows/tags.yaml) | The `release-X.Y.Z-rc.N` staging branch is a mutable staging ref (compare-before-force: skipped when unchanged, force+log only when it genuinely moves). Fails fast on a stable `vX.Y.Z` tag with no pre-existing draft — stable tags come from `promote-rc.yaml`, never a hand push. | -| [`promote-rc.yaml`](../.github/workflows/promote-rc.yaml) | Mutates no stable tags. Before staging, verifies green full E2E from the latest rc tag-push run or a tag-correlated manual published-tag run (unless loudly bypassed). Commits and publishes the rewritten packages tree under a run-specific temporary `promotion-*` tag, adds a second commit pinning its digest on the `release-X.Y.Z` branch, generates the changelog there, and opens the promote PR with `release` but no automatic `full-e2e`; the PR gate verifies the candidate and finalize repeats that verification before the stable tag and image retag. The staging branch is force-pushed on re-dispatch, but an existing `docs/changelogs/vX.Y.Z.md` is preserved across the rebuild. | - -This is the immutable-tag + rc-promotion model from [#2677](https://github.com/cozystack/cozystack/issues/2677): stable `vX.Y.Z` is created only by promoting an existing rc, rc tags are write-once, and `api/apps/v1alpha1/vX.Y.Z` is created only on a stable release. The old nightly `auto-release.yaml` (which delete-recreated auto-bumped patch tags) has been removed. rc and stable tags accrete permanently; the only churning artifacts are GHCR nightlies and abandoned temporary promotion candidates, which [`retention.yaml`](../.github/workflows/retention.yaml) prunes (see [Nightly builds](#nightly-builds)) — GHCR storage is the cost vector to watch. - -### Repo-side enforcement (tag-protection rulesets) - -The guarantees above are enforced in the workflows. Repo admins back them with two GitHub **tag rulesets** targeting `v*`: - -- **Immutability** — *Restrict updates* + *Restrict deletions*, **no bypass**. No actor (not even the CI app) can move or delete a shipped `v*` tag. Safe to enable at any time: nothing in the release flow ever moves or deletes a `v*` tag, it only creates new ones. -- **Creation control** — *Restrict creations* with the **CI app as the sole bypass actor**, plus *Limit branches/tags updated in a single push* = 1. This turns "don't hand-push tags" from convention into hard enforcement: every `v*` tag — pre-release **and** stable — can then be created only by CI. Enable this **only after** [`cut-prerelease.yaml`](../.github/workflows/cut-prerelease.yaml) is in use, since that workflow is what makes CI the sole creator of pre-release tags; enabling it earlier would lock maintainers out of cutting rc/alpha/beta. (The Go-module tag `api/apps/v1alpha1/*` gets an equivalent pair of rulesets.) - -## Splitting a release-blocking bundle PR - -Sometimes the work that has to land before a release is a 40-commit grab bag (CI stabilization, dependency bumps, chart fixes). Splitting it makes it reviewable and survivable. The strategy that has worked: - -1. **Verify what's already on `main`.** Use `git merge-base --is-ancestor` and subject grep to drop commits that have already landed. -2. **Find existing open PRs that cover the same commits.** Force-push to the existing branch instead of opening a duplicate — preserves review threads. -3. **Identify the "bottleneck" PR.** The one whose changes make previously-silent misconfigurations into hard errors (typically an operator-version bump). Everything else can fan out in parallel. -4. **Squash iterative same-author bug-on-bug fixes** inside each split. Preserve authorship via `--author` on the squashed commit. -5. **Mark the keystone PR as draft** and link in the body to the dependency PRs. Reviewers know it intentionally fails CI until the chain lands. -6. **Beware of concurrent registry pushes.** When fanning out 5+ PR CI runs simultaneously, multiple `make image` jobs can collide on shared floating tags. The `IMAGE_TAG=pr--` refactor solved this; if you see `Conflicted with another upload of the same manifest`, `gh run rerun --failed`. - -## Cleanup after release - -- The `release-X.Y.Z` branch is deleted by GitHub when its PR merges. The `release-X.Y` maintenance branch is created by `cut-prerelease.yaml` at the rc freeze (create-only, never force-moved) and fast-forwarded afterwards by `pull-requests-release.yaml::Ensure maintenance branch`. -- The draft release is published by the same workflow. -- The release body is set by finalize from `docs/changelogs/vX.Y.Z.md` at publication. Afterwards, `update-releasenotes.yaml` re-syncs that file into the GitHub Release body on any push to `main` that touches it — so edits to a published changelog land on the release page the next time `main` moves. -- Local cleanup: remove your worktree (`git worktree remove`) and prune merged release branches. +## Pages + +- [Introduction](./release/introduction.md): the three release types and the tag push that drives the pipeline. +- [Release Candidates](./release/release-candidates.md): what an rc is, and how cutting the first one freezes `release-X.Y`. +- [Regular Releases](./release/regular-releases.md): promoting an rc to `vX.Y.0`, step by step. +- [Patch Releases](./release/patch-releases.md): the same flow for `vX.Y.Z` on an existing `release-X.Y` line. +- [What CI does during the release process](./release/ci-pipeline.md): which workflow does what, phase by phase, including multi-arch builds and the rc E2E gate. +- [Stable tags come from rc promotion](./release/stable-tags.md): why a stable tag only ever comes from promoting an rc. +- [Release signatures and SBOM](./release/signatures-and-sbom.md): the source SBOM, checksums and cosign signature on each release, the SBOM each release image carries, and how to verify and read them. +- [Nightly builds](./release/nightly-builds.md): how a nightly mirrors `main` to GHCR, and how to install one. +- [Backports](./release/backports.md): the policy that decides what goes into a patch release, and how a contributor gets a fix there. +- [Backport mechanics](./release/backport-mechanics.md): cherry-pick triage before a patch, and the monotonic-counter trap. +- [Backport tasks](./release/backport-tasks/README.md): resolving a batch conflict, deferring the original a failed batch CI comes from, and checking a pull request title, with the check each has to pass. +- [Changelogs](./release/changelogs.md): changelog failure modes and the pre-publish checks. +- [Release-time fires](./release/release-time-fires.md): regressions that escaped to users, and the verification gaps they expose. +- [Pre-release verification checklist](./release/pre-release-checklist.md): what to verify before merging a release PR. +- [CI failures release engineers commonly hit](./release/ci-failures.md): known failures and whether each one blocks a release. +- [Tag immutability](./release/tag-immutability.md): write-once tags and the rulesets that enforce them. +- [Splitting a release-blocking bundle PR](./release/splitting-bundle-prs.md): how to break up a grab-bag PR that blocks a release. +- [Cleanup after release](./release/cleanup.md): what is left to clean up once a release is out. ## See also - [`agents/changelog.md`](./agents/changelog.md) — canonical changelog generation process. -- [`agents/contributing.md`](./agents/contributing.md) — commit/PR conventions, backport label semantics. +- [`agents/contributing.md`](./agents/contributing.md) — commit/PR conventions. - [`agents/releasing.md`](./agents/releasing.md) — pointer file for AI agents handling release tasks. - [`.github/workflows/cut-prerelease.yaml`](../.github/workflows/cut-prerelease.yaml) — the sole entry point for cutting a pre-release tag as the CI app. - [`.github/workflows/tags.yaml`](../.github/workflows/tags.yaml) — tag-push pipeline (rc build + mandatory `rc-e2e`; stable-tag changelog/website backstops). @@ -665,5 +53,6 @@ Sometimes the work that has to land before a release is a 40-commit grab bag (CI - [`agents/image-refs.md`](./agents/image-refs.md) — where image references live, what their tags mean, and the invariants promotion and mirroring rely on. - [`hack/lib/image-refs.sh`](../hack/lib/image-refs.sh) — the single enumeration of ref-bearing files, shared by the promote, retag and mirror tooling. - [`.github/workflows/retention.yaml`](../.github/workflows/retention.yaml) — GHCR nightly and abandoned promotion-candidate pruning. -- [`.github/workflows/backport.yaml`](../.github/workflows/backport.yaml) — automatic cherry-pick bot. +- [`cmd/backport-batch`](../cmd/backport-batch/README.md) — the backport batch that applies the [backport policy](./release/backports.md). +- [`.github/workflows/backport-batch.yaml`](../.github/workflows/backport-batch.yaml) — runs the backport batch on Monday and Thursday for each line it runs for: the newest released lines, and a line in its rc window. - [`.github/workflows/update-releasenotes.yaml`](../.github/workflows/update-releasenotes.yaml) — sync changelog → GitHub Release body. diff --git a/docs/release/backport-mechanics.md b/docs/release/backport-mechanics.md new file mode 100644 index 000000000..3474bffea --- /dev/null +++ b/docs/release/backport-mechanics.md @@ -0,0 +1,37 @@ +## Backport mechanics + +Under the [backport policy](./backports.md) fixes reach a release line through the batch, and nobody labels pull requests for backport. This page covers the mechanics around it: cherry-pick triage before a patch, and the trap that keeps migrations out of patch releases. + +### Cherry-pick triage before a patch + +A patch release includes bugfixes for code that shipped in the corresponding minor `vX.Y.0`. What goes in is decided by the rules in [Backports](./backports.md), not per pull request, and each batch pull request says what it picked, what it deferred and what it skipped under which rule. What is left to check before a cut: + +```bash +# Exits 1 and prints the URLs while a pull request the rules take is not on +# the line, including one only on the open batch PR, which the cut would not +# carry; see cmd/backport-batch/README.md. +go build ./cmd/backport-batch +./backport-batch check --line release-X.Y --cut +``` + +[`backport-batch check`](../../cmd/backport-batch/README.md) applies the rules to every pull request merged into `main` since the line branched, and looks for each one they take on the line and then on the open batch pull request: by picks whose `-x` lines name its merge commit or every commit of its own, by a pick that would change nothing, and, on commits from before the policy's batch-only day, by what their text says, such as `Backport of #N`. With `--cut` a change found only on the open batch pull request fails the check too, since a cut tags the line and would not carry it: merge the batch pull request first. A conflict the batch deferred, or an original deferred to the next batch, prints as a warning without failing the check, also once that batch merged or closed. An original that waits on the open batch for a maintainer fails the cut, and so does a unit on the open batch that carries only part of its original. An original parked because it builds on a change the line never gets, or would land only in part, prints as a note; one that waits on another original fails, warns or notes by what it waits on. A change that reached the line by hand counts like any other, by what reached the line. + +### Backporting code that touches monotonic counters + +The batch never takes a change like this: rule 4 in [Backports](./backports.md) holds migrations, `targetVersion`, sizeable API changes and CRDs for the next minor. What follows is why, and what a maintainer has to do when a migration must reach a release line anyway. + +Migrations are the canonical case. `packages/core/platform/images/migrations/run-migrations.sh` is a linear counter — it runs `seq $CURRENT_VERSION $((TARGET_VERSION - 1))` and stops if `CURRENT >= TARGET`. This creates a forward-upgrade trap. Walking through it with `release-1.2` as the maintenance branch: + +- `main` has `targetVersion=10` and migrations 1–9 on disk. +- The `release-1.2` branch was cut when `targetVersion=5` (migrations 1–4 on disk). +- You backport a new migration to `release-1.2` at slot 5, and naively bump `targetVersion` 5 → 6 to enable it. +- Customer running 1.2.x runs the new migration, stamps `cozystack-version=6` in-cluster. +- On upgrade to 1.3 (main's `targetVersion=10`), the runner walks `seq 6 9` and runs main's migrations 6–9 — **main's own migration at slot 5 never runs.** The backport claimed that slot on `release-1.2`; main's slot 5 holds an unrelated migration that gets silently skipped. + +Mitigations, in order of preference: + +1. **Don't bump `targetVersion` in the backport.** Just ship the migration file. Prior precedent in the repo: an earlier maintenance branch's ACME backport did exactly this — the migration shipped but ran on no clusters until a later commit raised the counter. Pair this with relaxing the chart-side `{{ fail }}` guard on the maintenance branch (chart-side coalesce) so the new value works without the migration having executed. +2. **If you must bump,** add an idempotent duplicate of the now-skipped main migration at a higher slot. Bounded cost (one extra file per affected migration) and survives the skip window. +3. **Audit cross-branch counter state before deciding.** Compare migration numbering across `main`, `release-X.Y`, and `release-X.(Y-1)`. If a backport would create a skip window on any forward-upgrade path, choose option 1. + +This rule generalizes to any monotonic-counter state: schema versions, feature-flag generations, anything that gates "have I run X yet?" with a single integer. diff --git a/docs/release/backport-tasks/README.md b/docs/release/backport-tasks/README.md new file mode 100644 index 000000000..dbbb536ad --- /dev/null +++ b/docs/release/backport-tasks/README.md @@ -0,0 +1,29 @@ +## Backport tasks + +The [backport batch](../backports.md) is built by [`backport-batch`](../../../cmd/backport-batch/README.md), and two steps around it need a maintainer's judgement. Each is a task with fixed inputs, one allowed output and a check in code that the result passes before anything is pushed. Both wait on the batch pull request: the batch's comment lists the deferred conflicts, and a failed batch CI shows on its checks. + +| Task | Input | Output | Check | +|---|---|---|---| +| [Resolve a conflict](./resolve-conflict.md) | a deferred conflict on the batch pull request | the original's commits picked under one merge on the batch branch, or one pick for a squash | `backport-batch fold`, and `backport-batch verify` in CI | +| [Attribute a failed batch CI](./failed-ci.md) | the failing jobs of the batch pull request | the culprit deferred to the next batch | `backport-batch run --defer` | + +### Rules for every task + +- Push nothing but the branch of the open batch pull request, `backport-batch/-` in this repository, and only what the task's check accepted. Never push to `main` or a `release-*` branch, and never open a second batch pull request: the scheduled run continues the open one. +- Change no file the original pull request does not change, or the path a rename on `main` or on the line gave it. A conflict that cannot be resolved inside those files is not resolved: the original stays deferred. +- Never rewrite the batch branch by hand. A plain push to it is a fast-forward; only `backport-batch run --defer --push` replaces it, leased on the head it rebuilt. +- Leave the batch pull request's title and body to the tool: it rewrites both on every run, and a hand edit is lost or, inside the `backport-batch` block, makes `run`, `check`, `fold` and `notify` refuse the body, and inside the `backport-batch-report` block makes `run --push` and `backport-batch report` refuse it. Leave the tool's report comments as they are too: each keeps one classification of the line, and an edited one makes `backport-batch report` refuse it. +- When the task cannot be done within these rules, push nothing and leave a comment on the batch pull request saying why, so the next maintainer to look finds it. Nothing is lost by waiting: a red batch does not merge, and a deferred original goes to the next batch. + +### Getting the tool + +Build it from `main`, in a clean worktree of this repository whose `origin` is this repository and with `gh` authenticated as someone who can push to the batch branch: + +```bash +git fetch origin +git worktree add --detach ../backport-task origin/main +cd ../backport-task +go build -o /tmp/backport-batch ./cmd/backport-batch +``` + +Run it from that worktree. Every command but `notify` and `report` fetches `origin` first, and `run`, `check`, `fold` and `lines` read the policy from `origin/main`. diff --git a/docs/release/backport-tasks/failed-ci.md b/docs/release/backport-tasks/failed-ci.md new file mode 100644 index 000000000..18b26f4dc --- /dev/null +++ b/docs/release/backport-tasks/failed-ci.md @@ -0,0 +1,41 @@ +## Attribute a failed batch CI + +CI on the batch pull request runs the line's build and tests against every original the batch carries at once. When a check fails, this task finds the original the failure comes from and takes it out of the batch, so the rest can merge; the original goes to the next batch with the reason recorded. Read the [rules for every task](./README.md#rules-for-every-task) first. + +### Inputs + +- The open batch pull request for the line and its failing checks: `gh pr checks `, and the log of each failing job, `gh run view --log-failed`. +- The originals the batch carries, one unit each on its first-parent line: `git log --first-parent --reverse --format='%h %s' origin/..origin/backport-batch/-`. A merged pull request's unit is a merge whose message is the original's merge message, naming its number, and whose `Backported-from:` trailer names its merge commit on `main`; its commits are `git log --reverse --format='%h %an %s' ^1..^2`. A squash-merged one is one commit whose subject ends in its number. The files a unit changes are `git diff --name-only ^1 `. +- The line's own CI on its head, `gh run list --branch `, to tell a failure the batch brought from one the line already had. + +### Output + +The batch rebuilt without the culprits, by one `backport-batch run --defer` with `--push`, which records each culprit and the reason in the batch pull request. Nothing else: no commit by hand, no revert, no edit to the batch branch. + +### Steps + +1. Read the failing jobs and name what fails: the job, the package or test, and the first error. +2. When the same job fails the same way on the line's head, or the failure is the runner's (a timeout pulling an image, a lost runner, a registry error), the batch did not cause it: defer nothing, and comment on the batch pull request with the job and the line's run that shows the same failure. +3. Otherwise pin it on originals by their files: the originals that change the failing package, chart or test, or what it builds from. Take the fewest that explain the failure; when no original's files reach the failure, or every original's do, the culprit cannot be pinned from files alone: read the failure further before deferring anything. +4. Write the reason as one line naming the job and the failure, for example `e2e-apps: postgres never becomes Ready`. + +### Check before pushing + +```bash +/tmp/backport-batch run --line --defer N[,N] --reason ": " +``` + +It rebuilds the branch locally without those originals and prints the new body, exiting 0. It exits 2 and names the original when dropping one leaves a later commit that no longer applies; add that one to `--defer` only when its files reach the failure too, otherwise comment on the batch pull request naming it and stop. Then publish the same command with `--push`: + +```bash +/tmp/backport-batch run --line --defer N[,N] --reason ": " --push +``` + +It replaces the batch branch only if nobody pushed onto it since the rebuild read it, and updates the pull request body. CI runs again on the new head; if it fails again on another original, repeat from step 1. + +When the culprits are everything the batch carries, there is no branch left to push: the body printed without `--push` says the batch is closing, and `--push` records the deferrals in the batch pull request, closes it and deletes its branch, still only if nobody pushed onto it since. The next batch tries them again. If it stops part way, the next `run --push` on the line finishes the close, and says so. + +### Never + +- Defer an original the failure does not reach, to make the batch green by taking out more than the culprit. +- Push the rebuilt branch any other way, or push to it by hand. diff --git a/docs/release/backport-tasks/resolve-conflict.md b/docs/release/backport-tasks/resolve-conflict.md new file mode 100644 index 000000000..885e568d4 --- /dev/null +++ b/docs/release/backport-tasks/resolve-conflict.md @@ -0,0 +1,66 @@ +## Resolve a conflict + +The batch carries a pull request merged into `main` as its own commits, each picked with `git cherry-pick -x`, under a merge commit that names the original; a squash-merged one as one pick. When any of an original's commits conflicts, nothing of it stays on the batch, and the batch pull request lists it under **Deferred conflicts** with the commit that failed and its files, and in its `backport-batch` block. This task ports one such original onto the batch by hand, in the same shape. Read the [rules for every task](./README.md#rules-for-every-task) first. + +### Inputs + +- The open batch pull request for the line, its branch `backport-batch/-` and its head commit, as GitHub shows them: `gh pr view --json headRefName,headRefOid`. The resolution lands on that batch, so without an open batch pull request there is nothing to resolve onto: wait for the next batch, which lists the conflict again, or port the change as a pull request of its own against the line, as [fixes that exist only on a release line](../backports.md#fixes-that-exist-only-on-a-release-line) describes, and drop the original from the line. +- The original's number `N` from the **Deferred conflicts** list, and its merge commit on `main`: `gh pr view N --json mergeCommit --jq .mergeCommit.oid`. It has two parents when the pull request was merged, one when it was squashed. +- For a merged pull request, its own commits, oldest first, without the merges that brought `main` into its branch: `git rev-list --reverse --topo-order --no-merges ^1..^2`. +- The files the original changes, `git diff --name-only ^1 `, which are the only files the resolution may touch. + +### Output + +For a merged pull request, one merge commit on the batch head: its first parent is the head of the batch pull request, and its second parent ends a straight line of picks of the pull request's own commits, in their order, each made with `git cherry-pick -x` so it keeps its author, message and sign-offs and ends in the `(cherry picked from commit …)` line git appends. Its message is the original's merge message with a `Backported-from: ` trailer of its own. For a squash-merged pull request, one pick of its commit. Either way only files the original changes, and nothing else: no extra commit, no fix-up of an earlier pick. + +### Steps + +```bash +git fetch origin +git switch --detach +base=$(git rev-parse HEAD) +``` + +Pick the original's commits, oldest first; for a squash-merged pull request the one commit to pick is its merge commit on `main`: + +```bash +git -c core.hooksPath=/dev/null cherry-pick -x --signoff +``` + +When a pick conflicts, resolve each conflicted file so that it does on the line what that commit does on `main`, keeping the line's own code wherever the commit does not change it, and go on with the next commit: + +```bash +git add +git -c core.hooksPath=/dev/null cherry-pick --continue --no-edit +``` + +When the original builds on something the line does not have, a helper, a value or another pull request, the resolution would have to bring that along, which this task does not allow: abort with `git cherry-pick --abort`, go back with `git switch --detach "$base"`, and comment on the batch pull request which change the original depends on; it stays deferred until that change is on the line. An original the batch parked because it builds on such a change is the same task, and lands only as a complete adaptation: every file it changes changed, unless the line already has that file as the original makes it. When that change will never reach the line, drop the original there instead, with `backport-batch run --line --drop N --reason "" --push`, so later batches stop trying it. A commit whose change the line already has stops the pick as empty; skip it with `git cherry-pick --skip`. A resolution that ports only what the line has and leaves a file of the original as it was, one the line does not have for instance, is refused by `fold`: such a port goes to the line as a pull request of its own, as [fixes that exist only on a release line](../backports.md#fixes-that-exist-only-on-a-release-line) describes, and the original is dropped there. + +For a merged pull request, join the picks to the batch head with the merge commit: + +```bash +tip=$(git rev-parse HEAD) +git switch --detach "$base" +{ git log -1 --format=%B ; printf '\nBackported-from: %s\n' ; } > /tmp/batch-merge-message +git -c core.hooksPath=/dev/null merge --no-ff -F /tmp/batch-merge-message "$tip" +``` + +### Check before pushing + +```bash +/tmp/backport-batch fold --line --original N --commit "$(git rev-parse HEAD)" +``` + +It prints `ok` and exits 0, or prints why not and exits 1. Push only on `ok`, as a fast-forward of the batch branch: + +```bash +git push origin HEAD:refs/heads/backport-batch/- +``` + +Resolve one original at a time and push each before starting the next: the next fold has to sit on the new head. CI on the batch pull request runs again on the push, `backport-batch verify` among it, and the next run of the batch lists the original as on the branch, with the picks the resolution changed marked as such. + +### Never + +- Push a commit `fold` did not print `ok` for, or push anywhere but the batch branch. +- Squash the original's commits into one pick, reorder them, or pick a commit of another pull request into the merge. +- Edit a file outside the original's files to make the pick build; that is the dependency case above. diff --git a/docs/release/backports.md b/docs/release/backports.md new file mode 100644 index 000000000..ad7424c40 --- /dev/null +++ b/docs/release/backports.md @@ -0,0 +1,128 @@ +## Backports + +Backports are automatic. Everything that can go into a patch release goes in, and nobody decides it pull request by pull request: nobody requests a backport, and contributors never open backport pull requests. The one exception is a maintainer override, below. A batch job takes the fixes merged into `main` and cherry-picks them onto each `release-X.Y` line it runs for, following the rules on this page. + +### Getting a fix into a patch release + +Merge it into `main` with a `fix` title, for example `fix(postgres): keep the replica count on resize`. Nothing else is needed: if the change meets the rules below, the next batch picks it up for every [line the batch runs for](#which-lines-the-batch-runs-for). + +The batch takes a pull request's type from its title alone, so a fix that ships inside a `feat` or `refactor` pull request does not reach a patch release. Put the fix in a pull request of its own. + +### What the batch takes + +The batch takes a pull request from `main` into release line X.Y when all of these hold: + +1. It merged into `main` after `release-X.Y` branched, or after the line started under this policy if that is later (see [Where each line starts](#where-each-line-starts)), and the line does not carry it yet. +2. Its title type is `fix` or `security`, the type of a fix that comes through a security advisory. CI and e2e fixes count, because they keep the line's own CI working. The title is read once any leading `[Backport …]` prefixes are dropped, and a title that does not read as a Conventional Commits title is kept out. +3. It is not breaking: no `!` after the type or scope, and no `BREAKING CHANGE:` or `BREAKING-CHANGE:` footer at the start of any line of the description its merge into `main` recorded. A footer inside an HTML comment, where the pull request template quotes it, does not count. +4. It touches no platform migrations, anything under `packages/core/platform/images/migrations/migrations/`, and no `targetVersion` line of `packages/core/platform/values.yaml`, adds, removes or edits no CustomResourceDefinition document (a CRD in a test fixture under `tests/` or `testdata/` does not count, and neither does an edit to another document in the same file), and makes no change to the API that the [API review gate](../../.github/workflows/api-review-gate.yaml) calls sizeable: a new or removed API group or resource, or a schema change that can reject what the old schema accepted. Those wait for the next minor; a reworded description or a new optional field under `api/` does not. [Backporting code that touches monotonic counters](./backport-mechanics.md#backporting-code-that-touches-monotonic-counters) shows what a migration on a release line breaks. +5. Each of its commits picks cleanly with `git cherry-pick -x`, or its conflict is resolved during the batch, and the batch's build and tests pass. A pick that fails moves to the next batch, and the batch pull request lists it with the files that conflicted. +6. On an older line, it is already on the next newer line the batch runs for. Lines are processed newest first, so an older line takes only what the newer one already carries. + +The batch reads the pull requests off `main`'s first-parent history, one per merge commit or squash commit that names its pull request. A commit there that names none, a direct push for instance, and a merge of more than two parents are never taken; the batch pull request counts them. + +### What the batch leaves out on one line + +A pull request the rules take for every line can still be wrong for one of them, for instance because it builds on code that line does not have. A maintainer drops it from that line with `./backport-batch run --line --drop --reason --push`: the batch takes it off, if it carries it, and no later batch for that line picks it again. The drop is kept in the [line's record](#the-lines-record-and-reports), so it needs an open batch pull request to record it on; before a line's first batch pull request exists there is nothing to record it on, and the command refuses. `--undrop ` withdraws it, and the next batch tries the pull request again. A pull request the line already carries cannot be dropped. To land a hand-made port instead, open it as a pull request of its own, as [fixes that exist only on a release line](#fixes-that-exist-only-on-a-release-line) describes, and drop the original. + +The batch also leaves a pull request out of a line on its own when it cannot land there whole. A pick that would leave part of what the pull request does on `main` without effect on the line, a change to a file the line does not have, or the deletion of a file the line never had or already removed, is not made: the pull request is parked, the batch pull request lists it under "Parked" with those files, and `check` prints it as a note without failing. A file the line already has as the pull request makes it counts as there, and so does a file `main` or the line renamed, under its other name. A unit already on the open batch that does only part of its original fails `check --cut` and `backport-batch verify`, whatever its label says, until `backport-batch run --defer` takes it out. What applies of a parked pull request goes to the line as a pull request of its own, as [fixes that exist only on a release line](#fixes-that-exist-only-on-a-release-line) describes. + +A pull request is parked too when it builds on a change the line never gets: it changes a file a `feat` added on `main`, say, or a line such a change wrote, and the line has neither. `backport-batch` reads that from git, as [its README](../../cmd/backport-batch/README.md#what-an-original-builds-on) describes, and names the change in the batch pull request. One that builds on a change that is still to come, a deferred conflict, one waiting for a maintainer, one rule 6 holds or one not tried yet, waits for it instead, listed under "Waiting on another original", and the batch tries it again once that change is on the line; one picked earlier in the same batch counts as there. A complete hand adaptation of a parked pull request, every file it changes changed, still lands on the batch through [resolving a conflict](./backport-tasks/resolve-conflict.md). + +### What waits for the next minor + +`feat`, `chore` and `docs` pull requests, and dependency bumps (scope `deps`), ship with the next minor, not in a patch release; only a maintainer's `backport/include`, below, takes one. If a class of fixes should also wait for a minor, it gets a new rule on this page; a single pull request that the rules get wrong is what the overrides below are for. + +### Maintainer overrides + +A maintainer overrides the rules for one pull request with a label on the merged pull request on `main`: + +- `backport/include` takes it although rules 2 to 4 keep it out, a `feat` for instance, or although it merged before its line started under this policy. It still has to pick cleanly or have its conflict resolved, pass CI on the batch, and, on an older line, already be on the newer one, and a line that already carries it does not take it again. It lifts no park, as [what the batch leaves out on one line](#what-the-batch-leaves-out-on-one-line) describes. +- `backport/skip` keeps it out although the rules take it, and `backport-batch check` stops asking for it. An open batch that picked it before the label came keeps it until `backport-batch run --defer` takes it out; the batch pull request says so meanwhile. + +A label decides for every line. To keep a pull request out of one line only, drop it there with `backport-batch run --drop`, as [what the batch leaves out on one line](#what-the-batch-leaves-out-on-one-line) describes; `backport/include` does not lift a drop. + +`backport/skip` wins when a pull request carries both. Each run reads the labels afresh, and the batch pull request lists every override and what became of it. + +### Which lines the batch runs for + +The batch runs for the two newest lines that have shipped a stable release, and for every line branched after the newest of them that has not shipped one yet. A line has shipped once its first stable `vX.Y.Z` tag exists, which only the merge of its promotion creates ([stable tags come from rc promotion](./stable-tags.md)); an rc, alpha or beta tag does not count. How many released lines it keeps is `released-lines` in the block below. + +With 1.6 and 1.7 released, cutting `v1.8.0-rc.1` creates `release-1.8` ([release candidates](./release-candidates.md)), and from the next run the batch runs for 1.6, 1.7 and 1.8. Once `v1.8.0` ships it runs for 1.7 and 1.8, and 1.6 takes no more batches. Rule 6 holds across all of them, newest first: while 1.8 is in its rc window, a fix reaches 1.7 only after the 1.8 batch that carries it has merged, and 1.6 only after 1.7's. + +During its rc window a line is frozen: every later rc is cut from `release-X.Y` itself, and `main` is open for the next minor. The freeze closes the line to `main`, not to the batch, which is how fixes reach it: a batch pull request against a frozen line is built, checked and merged like any other, and the next rc carries what it merged once `check --cut` passes (see [Running the batch](#running-the-batch)). A line that drops out keeps its open batch pull request as it is, and `backport-batch` no longer runs or checks that line; a maintainer merges the pull request or closes it. + +### Where each line starts + +The policy applies in full from `release-1.7` on: a line released before it took effect keeps the patch content its users chose it with, so it takes only fixes merged after the policy started, and an older one only with `backport/include`. The batch reads the block below from this page, on `main`: a line it lists starts on that day, and any other line starts where it branched from `main`. The block also gives the `batch-only` day and `released-lines`. + +From the `batch-only` day in the block, a change from `main` reaches a line only through the batch, and only the batch's picks show that a line carries it: a pick whose `(cherry picked from commit …)` line, the one git appends, names the original's merge commit or every commit of its own. A picked commit keeps its message and a batch merge carries the original's, so text in them, a `Backport of #N`, a `Backported-from:` trailer or an `-x` line the commit's author wrote, counts only on commits from before that day, where it records the hand backports and earlier batches. + +```backport-policy +# release-X.Y: YYYY-MM-DD, the day the line started under this policy +release-1.6: 2026-10-26 +# batch-only: YYYY-MM-DD, the day from which only the batch's picks show what a line carries +batch-only: 2026-10-26 +# released-lines: N, how many of the newest lines with a stable release the batch runs for +released-lines: 2 +``` + +### Fixes that exist only on a release line + +Some fixes go to a release line as a pull request of their own. Such pull requests are occasional, and maintainers open them: for a fix with no counterpart on `main`, for one that on `main` came as part of another pull request, or for one written for `main` rather than for the line. When the counterpart on `main` is a pull request of its own that the batch would take, the batch skips it as already on the line once picking it would change nothing there; otherwise a maintainer labels it `backport/skip`. A port of only what a line has of a pull request from `main`, one that leaves out what the line lacks, is such a pull request as well: the batch carries no unit that does part of its original, and `backport-batch fold` refuses one. + +A pull request opened against a `release-*` branch is closed automatically, with a comment that links to this page, when its author is a user account, not a bot, that GitHub names neither the repository's owner nor a member nor a collaborator, and whose access to the repository GitHub reports as read or none. Anyone with triage access or more keeps their pull request open. When GitHub's answer on the author's access cannot be read, the check closes nothing and fails, naming the read that failed. The check runs only when a pull request is opened, so a maintainer keeps a contributor's release-only fix by reopening it. [`hack/close-manual-backport.sh`](../../hack/close-manual-backport.sh) does this from [`pr-labeler.yaml`](../../.github/workflows/pr-labeler.yaml); run it with `--pr --dry-run` to see what it would decide for a given pull request when it is opened. + +### Cadence + +The batch runs for each of its lines twice a week, on Monday and Thursday: often enough that a fix reaches its line within days, rarely enough that nobody spends time on it every day, and early enough in the week that each run leaves working days to cut an rc, run its e2e and promote it before the weekend. Patch releases ship weekly. + +### Running the batch + +[`backport-batch`](../../cmd/backport-batch/README.md) builds the batch in a clean worktree, newest line first. The scheduled run below does this; by hand it is: + +```bash +go build ./cmd/backport-batch +./backport-batch run --line release-1.7 --continue --push +./backport-batch run --line release-1.6 --continue --push +``` + +A run by hand trusts the open batch pull request the scheduled run opened as `cozystack-ci[bot]` and continues it; `BACKPORT_BATCH_BOT` names another bot, and set empty trusts none. + +`./backport-batch lines` prints the lines, newest first. `run`, `check`, `fold` and `lines` read the policy block from this page on `main`, so until the page with its block is on `main` they need `--policy ` naming a ref that has it, and the scheduled run, which passes none, fails. + +`run` picks what the rules take onto `backport-batch/-` and opens a draft pull request against the line. A pull request merged into `main` with a merge commit goes onto the batch as its own commits, oldest first, each picked with `git cherry-pick -x --signoff` so it keeps its author, its message and its sign-offs and gains the sign-off of whoever runs the batch; commits that merged `main` into the pull request's branch are left out. A merge commit joins them to the batch: it carries the original's merge message from `main` and ends in a `Backported-from: ` trailer. A pull request squash-merged into `main` goes on as one pick. When any commit of an original conflicts, nothing of that original stays on the batch. The batch pull request is merged into the line with a merge commit, so all of this reaches the line as it is. Its body lists the originals with how many commits each brought and which of them differ from the commit they came from, whose release notes wait under "Check these notes" with what to compare, since a note may not hold for a pick that differs, the conflicts it deferred with the commit that failed and its files, what it parked and why, and what it skipped under which rule, and ends with the [line's record and the run's report](#the-lines-record-and-reports); `--push` prints the pull request's URL. While that pull request is open, the next run continues it, `--continue` reading its head, rather than opening another. CI on the batch pull request runs the line's build and tests, and a maintainer merges it. Since rule 6 reads the newer line itself, an older line takes a fix in the batch after the newer line's batch with that fix has merged. + +A deferred conflict waits for the next batch. To land it sooner, pick the original's commits onto the batch head with `git cherry-pick -x`, resolving each conflict, and join them to the batch head with a merge commit that names the original; an original squash-merged into `main` is one pick of its commit there, with no merge. Check that merge or that pick with `./backport-batch fold --line --original --commit `, and push it onto the batch branch, as [resolving a conflict](./backport-tasks/resolve-conflict.md) describes. CI runs `backport-batch verify` on every push to a batch pull request, which holds every original on it to the same shape. When CI on the batch pull request fails, the original it comes from is taken out with `./backport-batch run --line --defer --reason --push` and goes to the next batch, as [attributing a failed batch CI](./backport-tasks/failed-ci.md) describes; the rest of the batch merges without it. When it is all the batch carries, `--push` records why in the batch pull request, closes it and deletes its branch, and the next batch tries it again. `--drop` and `--undrop` change the record of the open batch pull request in the same way, and need one. + +Before a patch release or an rc is cut from a line, `./backport-batch check --line --cut` has to exit 0. A cut tags the line, so the check fails while a pull request the rules take is not on the line, including one that is only on the open batch pull request: merge the batch pull request first. It prints the URLs, and prints what the batch deferred as warnings, since deferring is a maintainer's call; so is a pull request labelled `backport/skip` that the open batch still carries. An original that waits on the batch for a maintainer fails the cut, also when it is all the batch has left, and so does a unit on the batch that carries only part of its original, whatever its label. A cut that passes says so. Without `--cut`, as the scheduled run uses it, a change on the open batch pull request counts as carried. + +### The line's record and reports + +What the batch decided about a line, the conflicts it deferred, the originals taken out with `--defer` and those waiting for a maintainer, is kept in a `backport-batch` block in the body of the line's newest batch pull request, its record. `backport-batch` reads the record whether that pull request is open, merged or closed, and writes it only while the pull request is open: a merged or closed batch pull request is never edited or commented on again. So a conflict the batch deferred is still a warning in `check` after the batch merged, until a later batch tries it again. A run that picks nothing while no batch is open writes nothing, and says so. A record `backport-batch` cannot read, or one written by someone it does not trust, stops it rather than let it fall back to an older one; how it decides is in [its README](../../cmd/backport-batch/README.md#the-lines-record-and-reports). + +Each run also reports where every pull request merged into `main` since the line branched stands, and what it read to decide. The body carries the latest report under the record, and a comment the tool posts on the open batch pull request keeps each one, so an earlier classification is still there after a later run replaced the body, and after the batch merged. Each drop in a report keeps its reason and the merge commit it is bound to. `./backport-batch report --pr ` prints the report the body carries, and `--id ` an earlier one; it writes nothing and never fetches, and reads GitHub and, for a report that keeps drops, the clone's history at the heads the report was made from. A run that picks nothing while no batch is open has nowhere to keep its report: the next batch's report has the line's state. + +### Changes to workflows + +The scheduled run's token may not push a commit that changes `.github/workflows/`, so the scheduled run leaves such an original out (`run --no-workflow-files`). That holds also for one whose only missing dependency that never comes is a test or documentation, which a maintainer's run, with the token that may push the workflow, parks instead: what lands of it then is a pull request of its own; `check` reads which of the two the open batch was assembled as from its record, and with no batch open takes the scheduled run's. The batch pull request lists it under "Waiting for a maintainer", with the workflow files it changes, and so does the batch's comment. It is no conflict. The policy still takes it: `check` warns about it while it waits, and `check --cut` fails on it. When nothing else is picked there is no batch pull request to list it on, and `check` reports it as missing. + +A maintainer brings it over with their own token, one that may push workflow changes (the Workflows permission, or the classic `workflow` scope), by continuing the open batch without the flag: + +```bash +./backport-batch run --line --continue --push +``` + +That picks it onto the batch in the batch's shape, after what the batch carries, and the body stops listing it; later scheduled runs continue the batch on top. To cut without it instead, take it out with `./backport-batch run --line --defer --reason --push`. + +### The scheduled run + +[`backport-batch.yaml`](../../.github/workflows/backport-batch.yaml) runs [`hack/backport-batch-scheduled.sh`](../../hack/backport-batch-scheduled.sh) on Monday and Thursday. For each line the batch runs for, newest first, it continues the open batch pull request or opens one, runs `check`, and then `backport-batch notify`, which reports what waits on the batch. A batch open for three days or more, so one the previous run already saw, gets a comment on its pull request saying so and a line in the run's summary. The comment is one per pull request, updated in place on every run. It also lists the deferred conflicts, which a maintainer resolves as [resolving a conflict](./backport-tasks/resolve-conflict.md) describes, and the originals that wait because they change workflows, and names each parked original once: a park named on one batch is not named again on the next while it stays the same park, and with no batch open nothing is named until the next batch opens. A failed batch CI waits for a maintainer too, as [attributing a failed batch CI](./backport-tasks/failed-ci.md) describes; the comment does not list it, and it shows on the batch pull request's checks. `hack/backport-batch-scheduled.sh --dry-run` does the same in the current worktree and changes nothing on GitHub. Its `check` sees the line without the batch the dry run just built, so it can exit 1 where the real run's check passes. + +The batch runs as the cozystack-ci GitHub App, which the release workflows already use, and needs no secret of its own. The job mints a token from `COZYSTACK_CI_APP_ID` and `COZYSTACK_CI_PRIVATE_KEY` for this repository alone, with Contents and Pull requests write and nothing more, and fails when either secret is missing. Its pushes start CI on the batch pull request, which a push with the job's own `GITHUB_TOKEN` would not. Its commits carry the App's bot, `cozystack-ci[bot]`, whose batch pull request and comment `backport-batch` trusts: `BACKPORT_BATCH_BOT`, which the job sets from the token, names it, and a run without the variable trusts `cozystack-ci[bot]` too. The App's installation has to grant this repository Contents and Pull requests read and write, which an organization admin sees among the organization's installed GitHub Apps. It has no Workflows permission, so a change to `.github/workflows/` waits for a maintainer, as [changes to workflows](#changes-to-workflows) describes. + +It also reads one repository setting, which a repository admin sets up: `BACKPORT_ALERT_TEAM`, a variable, the team or person the comment mentions, as `org/team` or a login. Unset, the comment mentions nobody: the batch pull request is a draft the App opened, so no one is notified of what waits unless they watch the repository. + +Optionally, once the `Backport batch shape` check runs from `main`, a ruleset makes it required on the release lines. It targets `release-*` and excludes `release-*.*.*`: `release-*` alone also matches the `release-X.Y.Z-rc.N` and `release-X.Y.Z` staging branches that [`tags.yaml`](../../.github/workflows/tags.yaml) and [`promote-rc.yaml`](../../.github/workflows/promote-rc.yaml) push, which have no batch on them, and a required check would refuse those pushes. "Do not require status checks on creation" stays on, since [`cut-prerelease.yaml`](../../.github/workflows/cut-prerelease.yaml) creates `release-X.Y` with a push at its first rc. + +To run the scheduled script for real by hand, export your own token as `BACKPORT_BATCH_TOKEN`: without `--dry-run` it uses that variable and no other credential. With a token that may push workflow changes, leave `--no-workflow-files` out and the run brings over what waits. diff --git a/docs/release/changelogs.md b/docs/release/changelogs.md new file mode 100644 index 000000000..e5d7db401 --- /dev/null +++ b/docs/release/changelogs.md @@ -0,0 +1,107 @@ +## Changelogs + +### Where the canonical process lives + +[`agents/changelog.md`](../agents/changelog.md) is the source of truth. Read it end-to-end before generating; do not infer the process from past commits or memory. The CI runs it under Copilot via the reusable `changelog-generate.yaml` — called by `promote-rc.yaml::changelog` at promote time and by the optional `changelog-rc.yaml` at rc time — and, as a backstop, `tags.yaml::generate-changelog`; locally the same prompt is replayable by following the doc directly. + +### Common changelog failure modes + +These are mistakes that have shipped in real changelogs. Verify against each before merging the changelog PR. + +**1. Commits from outside the release range.** Caused by running `git log ..HEAD` from `main` while generating a patch changelog — `HEAD` on `main` contains everything that landed since the tag plus backports merged to `release-X.Y` after the tag was cut. Use `git log ..` explicitly. The doc was updated to require this after v1.3.1's changelog shipped with 14 entries for what was actually a 1-commit release. + +**2. Original + backport listed as two separate entries.** Each backport must coalesce with its original into a single entry of the form `(in #orig, backport #bp)`. To verify after generation: + +```bash +# Every entry that mentions "backport" should also reference the original PR number +grep -E 'backport #[0-9]+' docs/changelogs/v.md | grep -v '#[0-9]*, backport' +``` + +Output should be empty. + +**3. Wrong PR author.** The squash-merge commit's author is whoever clicked "Merge" — not the person who wrote the code. **Always** resolve via `gh pr view --json author --jq .author.login`, never `git log --format=%an`. This bites hardest for website-repo entries where the same merger handles most PRs. + +**4. Superseding patch, stale changelog.** Tags are write-once, so a critical fix after `vX.Y.Z` ships as the next patch `vX.Y.(Z+1)` rather than moving the tag. If a changelog PR already exists for a tag you are superseding, the changelog work transfers to the new patch. Compare `git log ..` against what the existing `changelog-vX.Y.Z` branch already documents; only add/remove the deltas. If the only new commits are CI-internal or a revert of a feature that never reached a stable tag, no changelog edit is needed. + +**5. PR numbers swapped inside prose.** The entry-format validator checks bullet entries but ignores Feature Highlights paragraphs and Upgrade Notes. Both have caused wrong PR references in shipped changelogs. Verify every `#NNNN` in prose with `gh pr view `. + +**6. Hallucinated entries.** Every entry must correspond to a commit in `git log ..`. Verify by extracting PR numbers from the file and grep-searching the commit range: + +```bash +grep -oE '#[0-9]+' docs/changelogs/v.md | sort -u | while read pr; do + n=${pr#\#} + if ! git log .. --grep="#${n}" --oneline | grep -q .; then + echo "PR $pr in changelog but not in commit range" + fi +done +``` + +**7. Bot accounts as human contributors.** `cozystack-ci[bot]`, `github-actions`, `dependabot`, `renovate`, and any `app/*` login must NOT appear in the `## Contributors` list. They legitimately appear in **per-entry attribution** (e.g. a Renovate-authored PR) — but not in the human roll-call. + +**8. Title duplicated as description.** `* **fix(foo): X**: fix(foo): X (...)` means you wrote the conventional-commit subject twice and never wrote a user-facing description. The brief and the detail must say different things — the detail explains what the change means for users. + +### Changelog pre-publish verification + +Run these checks before merging the changelog PR. Catches problems in roughly the order they occur: + +```bash +PREV=v1.2.0; NEW=v1.2.1 + +# A. Every chart bump is mentioned somewhere in the changelog +git diff --name-only $PREV..$NEW -- 'packages/*/charts/*/Chart.yaml' 'packages/*/*/charts/*/Chart.yaml' | while read f; do + old=$(git show "$PREV:$f" 2>/dev/null | yq '.version // ""') + new=$(git show "$NEW:$f" 2>/dev/null | yq '.version // ""') + if [ "$old" != "$new" ]; then + component=$(basename "$(dirname "$f")") + if ! grep -qi "$component" docs/changelogs/$NEW.md; then + echo "MISSING: $component $old -> $new ($f)" + fi + fi +done + +# B. Out-of-Chart.yaml pins (Talos, tenant K8s, vendored images) +for path in packages/core/talos/images/talos/profiles/installer.yaml packages/core/installer/values.yaml packages/apps/kubernetes/values.yaml packages/apps/kubernetes-nodes/values.yaml; do + git diff $PREV..$NEW -- "$path" | head -40 +done +git diff --name-only $PREV..$NEW -- 'images/*/Dockerfile' + +# C. Every cited #NNNN exists and is a merged PR (not an issue) +grep -oE '#[0-9]+' docs/changelogs/$NEW.md | sort -u | sed 's/#//' | xargs -P 20 -I{} sh -c ' + state=$(gh api /repos/cozystack/cozystack/issues/{} --jq ".pull_request.merged_at // \"ISSUE\"" 2>/dev/null) + echo "#{} $state" +' | grep -E 'ISSUE|null|^#[0-9]+ $' + +# D. URL liveness +grep -oE 'https://[^)" ]+' docs/changelogs/$NEW.md | sort -u | xargs -P 10 -I{} sh -c ' + code=$(curl -s -o /dev/null -w "%{http_code}" {}) + if [ "$code" != "200" ]; then echo "$code {}"; fi +' + +# E. Website PR authors are PR authors, not commit authors +grep -oE 'cozystack/website#[0-9]+' docs/changelogs/$NEW.md | sort -u | sed 's|cozystack/website#||' | while read n; do + pr_author=$(gh pr view $n --repo cozystack/website --json author --jq .author.login) + echo "website#$n -> @$pr_author" +done + +# F. Working tree clean except for the changelog +git status --porcelain | grep -v "docs/changelogs/$NEW.md" +# Should output nothing. +``` + +Ship criterion: every chart bump surfaced, no issue-cited-as-PR, no 404 URLs, every website entry attributed via `gh pr view` (not commit author), `git status` shows only the changelog. + +### Cozystack-specific URL quirks + +`cozystack.io` paths are versioned: `/docs/operations/foo/` and `/docs/next/foo/` both 404. Only `/docs/vX.Y/foo/` and the unversioned canonical `/docs/foo/` serve content. AI-generated changelogs invent the unversioned form. Verify URLs with the `curl` loop above. + +### Platform-component coverage + +For a minor release (`vX.Y.0`), changelog entries should surface what an upstream chart bump actually brought in — features, breaking changes, security fixes. PR commit messages usually don't capture this; the upstream `CHANGELOG.md` or GitHub Release notes do. For each bumped `Chart.yaml`: + +1. Read the `sources:` field — typically a GitHub URL. +2. Fetch release notes strictly inside `old < x <= new` via `gh release view --repo / --json body,name`. +3. Summarize in 2–5 user-impact bullets per component (new features, breaking changes, CVEs, important deprecations). Don't reproduce upstream notes verbatim; link to them. +4. If a PR-level entry already mentions the bump, enrich that entry with bullets — don't duplicate the entry. +5. If 3+ bumps have no PR-level mention, introduce a `## Platform Components` section. + +If you can't find upstream notes for a bumped component, list it with version-only info and no bullets. Hallucinated bullets are worse than missing detail. diff --git a/docs/release/ci-failures.md b/docs/release/ci-failures.md new file mode 100644 index 000000000..9beabe02c --- /dev/null +++ b/docs/release/ci-failures.md @@ -0,0 +1,16 @@ +## CI failures release engineers commonly hit + +| Symptom | Class | Diagnosis | Block release? | +|---------|-------|-----------|----------------| +| `Draft release for vX.Y.Z not found` on every release-* merge | Workflow regression — `Publish draft release` lost its `github-token` in a past refactor; default `GITHUB_TOKEN` cannot list drafts | At `pull-requests-release.yaml:163`. Undraft manually, file the fix | No | +| Changelog Copilot job returns 402 | Token quota — `COPILOT_GITHUB_TOKEN` premium-request quota empty | Both changelog entry points hit it: the optional rc-time `changelog-rc` dispatch and the promote-time `changelog` job (both call the reusable `changelog-generate.yaml`), plus the `tags.yaml` backstop | No — `continue-on-error: true` on the AI step, generate changelog by hand following [`agents/changelog.md`](../agents/changelog.md) | +| `Prepare Release` skipped and the run red, `Build arm64 images` failed | The rc's arm64 build failed | Read the `build-arm64` log; `build-arm64-nightly.yaml` usually failed the same way first. Fix on the line, cut the next rc | Yes — an rc is not published amd64 only | +| `Stitch multi-arch indexes and republish` fails listing refs | `verify-multiarch.sh` found refs that are not amd64+arm64 indexes, or that it could not check | Each listed ref names its reason. Single-platform manifest or index without one architecture: make the image multi-arch, or allowlist its repository with a reason if it cannot be. Manifest unreadable: correct the ref or digest; the allowlist does not excuse it. Rate-limited or unavailable after 3 tries: re-run once the throttle clears | Yes | +| E2E `kubernetes-test` fails with `CSINode does not contain driver csi.kubevirt.io` | Test ordering bug | Tenant's `kubernetes-${test_name}-csi` HelmRelease still installing when NFS PVC is created. Fix: wait for `csinode/` to advertise the driver before creating the PVC | Yes — flaky and masks real CSI bugs | +| `tenant-root` HR in perpetual upgrade-rollback loop after OIDC patch | Real bug at the intersection of #2602's readiness change and the cozystack reconcile cadence | Look for `rate: Wait(n=1) would exceed context deadline` in operator logs; multiple tenant child HRs stuck `InProgress` | Yes | +| `cozy-dashboard` ImagePullBackOff from `cozystack-ui:latest` | Registry flake | Known noisy on some OCI mirrors; not currently in the prepull set | No — retry | +| PR CI: `docker push` 409 on `:latest` for the same image across two PRs | Concurrent manifest race on a shared floating tag | The `:latest` tag was previously written by every `make image` regardless of PR. Resolved by the image-tag refactor (`IMAGE_TAG=pr--` in PR builds, `IMAGE_TAG=` only at release time) | No — `gh run rerun --failed` | + +**Heuristic:** workflow-token and Copilot-quota issues are out-of-band — release the tag, fix the workflow in a follow-up PR. Test ordering bugs and tenant-root reconcile storms are real and should block. + +If you find yourself doing the same manual fixup on two consecutive releases (e.g. "undraft the release"), open a workflow-regression issue. Workflow bugs with known manual workarounds rot silently for months. diff --git a/docs/release/ci-pipeline.md b/docs/release/ci-pipeline.md new file mode 100644 index 000000000..73f105bb7 --- /dev/null +++ b/docs/release/ci-pipeline.md @@ -0,0 +1,107 @@ +## What CI does during the release process + +The numbered process of a [regular release](./regular-releases.md#regular-releases) is implemented by seven workflows, including the reusable/manual [`e2e-tag.yaml`](../../.github/workflows/e2e-tag.yaml), plus the reusable [`changelog-generate.yaml`](../../.github/workflows/changelog-generate.yaml) that two of them share to produce the changelog. Knowing which job does what makes the failure modes much easier to diagnose. + +1. [`cut-prerelease.yaml`](../../.github/workflows/cut-prerelease.yaml) — manual dispatch (from `main` or `release-X.Y`): the sole entry point for creating a pre-release tag. Validates the `-alpha`/`-beta`/`-rc` tag, then pushes it (write-once, at the branch tip) as the CI app so `tags.yaml` fires. Cutting the first `vX.Y.0-rc.N` also creates `release-X.Y`, freezing the line; afterwards a `vX.Y.*` dispatch from `main` is refused. Stable tags are never created here. +2. [`tags.yaml`](../../.github/workflows/tags.yaml) — fires on any pre-release tag push: `build-amd64` and `build-arm64` build the pre-release side by side, then `prepare-release` publishes it and pushes its digest-pinned staging branch, then — **only for `-rc.N` tags** — the mandatory `rc-e2e` job calls `e2e-tag.yaml` in the same run (`-alpha.N` / `-beta.N` skip it and are validated on demand with `e2e-tag.yaml`'s manual button). `generate-changelog` and `update-website-docs` also live here but are **backstops only** — both are normally produced at promotion time (see 4); on a stable tag push each self-skips or no-ops when the promote flow already did the work. These stable-tag backstops only fire because finalize pushes the stable tag with the CI app token (a `GITHUB_TOKEN` push triggers no run — see 5). +3. [`e2e-tag.yaml`](../../.github/workflows/e2e-tag.yaml) — reusable from `tags.yaml::rc-e2e` and manually dispatchable for a published tag. It checks that the tag's release carries its nocloud disk, resolves the digest-pinned tree and runs the full install, OpenAPI, and Chainsaw suite on Talos containers. A tag cut before the container lane existed has to be dispatched from its own ref. Its dispatch run title is the constant workflow name, so the promote gate correlates a manual run through the successful tag-bearing E2E job name rather than the title. +4. [`promote-rc.yaml`](../../.github/workflows/promote-rc.yaml) — manual dispatch, from `main` only (the signature over a stable release's assets names that ref, see [Release signatures and SBOM](./signatures-and-sbom.md#release-signatures-and-sbom)). Five jobs: `parse` validates the rc tag and requires green full-E2E evidence before any staging; `promote` rewrites and commits the rc tags, publishes that packages tree as a run-specific temporary reproducible candidate, commits its digest pin in the `release-X.Y.Z` tree, and drafts the stable release; `changelog` calls the reusable `changelog-generate.yaml` **in parallel** to produce `docs/changelogs/vX.Y.Z.md` (regenerating it, or copying an rc-time changelog already committed to the `release-X.Y.Z-rc.N` staging branch by `changelog-rc.yaml` — see 7); `website-docs` (needs `parse`, `promote`) opens the `cozystack/website` docs PR from the staging branch via `FETCH_REF` (see [Phase 3](#phase-3--update-website-docs-now-the-backstop)); `open-pr` joins them, commits the changelog onto the staging branch, and opens the `release-X.Y.Z` promote PR with the `release` label but no automatic `full-e2e`. So the changelog and website docs are reviewed as part of the promotion, the already-checked rc suite is not repeated by default, and the PR body carries ✅ verified or ⚠️ bypassed plus ✅/⚠️ changelog and website-docs lines. Both `changelog` and `website-docs` are non-blocking. No stable registry name is created at dispatch. +5. [`.github/workflows/pull-requests.yaml`](../../.github/workflows/pull-requests.yaml) verifies a promotion candidate against the prospective merge tree and original rc artifact before the required `E2E Tests` status can turn green. [`pull-requests-release.yaml`](../../.github/workflows/pull-requests-release.yaml) fires after merge and repeats that verification before any stable tag, then cuts the write-once stable + Go-module tags, publishes the release **with the merged changelog as its body**, retags the candidate and rc images to stable by digest (`:latest` gated on newest-stable), and publishes the stable chart. +6. [`update-releasenotes.yaml`](../../.github/workflows/update-releasenotes.yaml) — fires on pushes to `main` that touch `docs/changelogs/v*.md`; syncs that content into the corresponding GitHub Release body. No longer the primary path (finalize sets the body directly, which is race-free and works for maintenance lines too) — this now covers later edits to a published changelog and manual re-syncs via `workflow_dispatch`. +7. [`changelog-rc.yaml`](../../.github/workflows/changelog-rc.yaml) — manual dispatch, **optional**: generate the changelog at rc time instead of waiting for promotion, while there is still time to review it. It calls the same reusable [`changelog-generate.yaml`](../../.github/workflows/changelog-generate.yaml) and commits the result to the `release-X.Y.Z-rc.N` staging branch as `docs/changelogs/vX.Y.Z.md`; the promote-time `changelog` job then copies that file instead of running the AI again. Skipping this workflow changes nothing — promote generates the changelog itself, exactly as before. + +### Phase 1 — `build-amd64`, `build-arm64` and `prepare-release` (hard gate) + +On an rc tag push: builds images for both architectures, commits digest pins, creates the draft release, and pushes the `release-X.Y.Z-rc.N` staging branch. `build-amd64` holds the release-exists no-op and the rejection of a hand-pushed stable tag, and builds the amd64 images and the release assets (its `make build` also pushes the packages artifact and the installer chart, pinned on amd64 digests); `prepare-release` stitches, gates, republishes those two from the repinned tree, and publishes the release. (The stable promote PR is opened later by `promote-rc.yaml`, not here. When the stable tag itself is pushed by finalize, a draft already exists, so this job is a no-op — see [Phase 5](#phase-5--pull-requests-releaseyaml-finalize).) + +The commit (`Prepare release vX.Y.Z`, authored by `cozystack-ci[bot]`) is **digest pins and image tags only**: + +- `packages/core/{installer,platform,testing}/values.yaml` +- `packages/system/*/values.yaml` (cozystack-api, dashboard, kamaji, linstor, kubevirt-csi-node, etc.) +- `packages/apps/kubernetes/images/{kubevirt-csi-driver,ubuntu-container-disk-*}.tag` +- `packages/system/dashboard/templates/configmap.yaml` (the `$tenantText` value) + +Things that look surprising in the diff but are normal: + +- **Zero-diff packages**: when buildx fully caches and upstream base images haven't moved, the digest is byte-identical to the previous release and won't appear. Verify the build step actually ran — don't assume "no diff = nothing built." +- **Sudden churn on `ubuntu-container-disk-*` tags**: `cloud-images.ubuntu.com/noble/current/` is a moving target; these often rebuild even without code changes. +- **Switched registry**: if a self-built image moved from `docker.io` to `ghcr.io`, the registry portion of the digest changes — that's a deliberate move, not a regression. +- **`targetVersion` is NOT touched by the release PR.** Platform migration `targetVersion` is bumped earlier in a feature commit (e.g. `[platform] Bump migration targetVersion to 39 for migration 38`). The release PR only re-pins the `platform-migrations` image digest. + +#### Multi-arch images + +Every pre-release is published for amd64 and arm64. `tags.yaml::build-arm64` builds the images on a native arm64 runner and pushes each as `-arm64`, while `build-amd64` builds amd64, the Talos installer and matchbox for both arches, and the assets on x86 at the same time. `build-amd64` hands its stamped tree, the log of the tags it pushed and the assets to `prepare-release` as workflow artifacts; a missing one fails the upload or the download rather than publishing a partial release. `prepare-release` waits for both builds and runs only if both succeeded: when either fails, the rc is not prepared at all, so a release is never published amd64 only. It applies the stamped tree and runs [`hack/stitch-multiarch.sh`](../../hack/stitch-multiarch.sh), which joins each image with its arm64 twin into one index, moves onto it every tag the build pushed for that image (the rc tag and, under `PUBLISH_VERSIONED=1`, its component version, which the build records in `PUSHED_TAGS_LOG`), and repins the tree on the index digests, then [`hack/verify-multiarch.sh`](../../hack/verify-multiarch.sh), then republishes the packages artifact and the installer chart from the repinned tree. A stable tag skips `build-arm64` and builds nothing: promotion copies the rc's indexes with every platform, so the stable release is exactly as multi-arch as its rc. Because the two builds run in parallel, an rc that is not prepared (its arm64 build failed, or `prepare-release` failed before the stitch) still leaves behind what the amd64 build pushed: amd64-only images under `:` and under the component-version tags, and the `cozystack-packages:` artifact and the installer chart, both pinned on those amd64 digests. A component tag an earlier rc had moved to an index then points at an amd64-only image again, until a run that succeeds stitches it, a re-run of the same run included. + +`verify-multiarch.sh` is a hard gate. It resolves every ref the tree pins, third-party images included, and fails naming each one that is not an index carrying both `linux/amd64` and `linux/arm64`, or that it cannot resolve at all. The fix is to make the image multi-arch (build it for both, or pin a multi-arch digest of the same version); an image that cannot exist for arm64 goes in [`hack/multiarch-allowlist`](../../hack/multiarch-allowlist) by repository, with the reason on the same line. + +That gate sees only what the tree pins by digest. An image a vendored chart renders from its own defaults, or one an operator launches at runtime, is invisible to it. `rc-e2e` closes most of that gap: before tearing the sandbox down, [`e2e-tag.yaml`](../../.github/workflows/e2e-tag.yaml) reads every image the three Talos nodes pulled from their image stores (`hack/collect-images.sh`), each by the digest the pull resolved to, and runs `verify-multiarch.sh --refs-file` on that list with the same allowlist. A pre-release fails on any single-arch image, on any ref it cannot read or that is still rate-limited after the retries, and on a list the collection could not produce; a stable tag's run only warns, since it ships its rc's images. A tag whose tree predates the audit (it has no `hack/verify-multiarch.sh`) only warns and passes, so an rc cut before the audit existed can still be re-validated. The list and the audit output are in the run's `image-list-` artifact. Neither check covers a package that e2e never installs and whose images the tree does not pin by digest: an arm64 break there shows up only on an arm64 cluster. + +[`build-arm64-nightly.yaml`](../../.github/workflows/build-arm64-nightly.yaml) builds `main` for arm64 every day, so an arm64 build break shows up there before the next rc. Its first step prints `verify-multiarch.sh --report` for `main`'s committed tree: `main` pins amd64 images, so its first-party refs are all listed and are expected to be, since the rc's stitch turns them into indexes. A third-party ref that an in-tree rebuild stamps over at build time, as the Harbor components and shadowbox are, is listed too and goes away on the rc. The lines that matter are the third-party refs no build replaces and refs that cannot be resolved; each of those fails the next rc until it is fixed or allowlisted. matchbox is listed too and does not matter: `build-amd64` rebuilds it as a two-arch index. The stitch names the images it skips in its own summary: an image with no `-arm64` twin, one whose digest is also pinned in a file the rewrite does not reach, and a pair that is not one amd64 and one arm64 image. matchbox (already an index) and the e2e sandbox (never built for arm64, and allowlisted) are skipped on every rc and pass the gate; any other skipped image fails it. + +### RC E2E — mandatory check before promotion + +For an rc, `prepare-release` must finish before `tags.yaml::rc-e2e` calls the published-tag lane, so the full suite tests the digest-pinned staging tree that promotion will reuse, and the release it runs against already carries its disk. `promote-rc.yaml::parse` then checks the latest `tags.yaml` push run whose `head_branch` is the rc tag and accepts it only when the reusable E2E job succeeded. GitHub exposes called-workflow job names as `E2E Release Candidate / E2E vX.Y.Z-rc.N (full suite)`, which the gate matches by the exact tag-bearing suffix. + +The alternate evidence path scans retained successful `workflow_dispatch` runs of `e2e-tag.yaml` and accepts one whose direct E2E job is named `E2E vX.Y.Z-rc.N (full suite)`. The workflow's run title is always `E2E Release Tag` and therefore cannot correlate the input tag; artifact names also carry the tag but expire independently, so the job name is the strongest available correlator. If Actions retention or manual deletion removes the run/job metadata, or that job is renamed without updating the matcher, the gate fails closed and tells the maintainer to run the E2E Release Tag button again. `skip_e2e_gate=true` is an emergency override, not alternate evidence: it writes a loud warning and a ⚠️ PR-body line. + +### Phase 2 — the changelog (generated at rc time or promotion, not here) + +The changelog for `vX.Y.Z` is produced by [`promote-rc.yaml`](../../.github/workflows/promote-rc.yaml)'s `changelog` job (a thin call to the reusable [`changelog-generate.yaml`](../../.github/workflows/changelog-generate.yaml)) and committed onto the `release-X.Y.Z` staging branch by `open-pr`, so it rides the promote PR and is on the base branch the moment the release publishes. Finalize then uses that file verbatim as the GitHub Release body. Generating it here — on the stable tag push — would be too late by construction: that tag is created by finalize, which has already published the release. It can also be produced earlier, at rc time, via the optional [`changelog-rc.yaml`](../../.github/workflows/changelog-rc.yaml) button — which runs the same reusable core and commits the file to the `release-X.Y.Z-rc.N` staging branch, from which the promote-time `changelog` job copies it (validated) instead of regenerating. + +The `changelog` job runs **in parallel** with `promote`, detached at the rc tag (the "promotion" configuration in §2 of [`agents/changelog.md`](../agents/changelog.md)), using a separate **read-only** GitHub App token for the AI step so the model cannot mutate the repo even with `--allow-all-tools`. Every write — the commit onto the staging branch and the PR — happens in `open-pr` under a write-scoped token. + +Generation is deliberately **non-blocking**: a Copilot outage or exhausted token quota must never block a release. Only the AI step carries `continue-on-error`, and `open-pr` is gated on `promote` alone (`if: !cancelled() && needs.promote.result == 'success'`) so the promote PR opens regardless. When the changelog is missing the PR body says so explicitly — that ⚠️ line is the signal to act on. + +Recovery, in order of preference: + +1. Commit `docs/changelogs/vX.Y.Z.md` to the `release-X.Y.Z` branch by hand (follow [`agents/changelog.md`](../agents/changelog.md)). `promote` preserves it across a re-dispatch, and `open-pr` will not overwrite it with generated output. +2. Re-dispatch `promote-rc.yaml` — generation runs again; anything already on the branch wins. +3. Merge without one and let `tags.yaml::generate-changelog` (the backstop) open a changelog PR against `main` after the fact. The release is published with the draft's body until that merges. + +Known failure modes: + +- Copilot quota exhausted (`COPILOT_GITHUB_TOKEN` 402). Refill or rotate, then re-dispatch. +- AI step timeout (hard 30-min cap). +- Output truncated or whitespace-only — caught by the `Verify changelog` step (`hack/validate-changelog.sh`), which accepts either header convention (`# Cozystack vX.Y.Z` for a minor or `# vX.Y.Z ()` for a patch), and requires the leading release-link comment pointing at `releases/tag/vX.Y.Z`, a `compare/...vX.Y.Z` link ending in this version, and at least one `## ` section — deliberately with no line-count floor, since a complete short patch changelog (v1.5.1 ships in 19 lines) must not be rejected as a fragment. It downgrades to the missing-changelog path rather than shipping a fragment as release notes. + +**`tags.yaml::generate-changelog` is the backstop.** It self-skips when the changelog is already on `main`. It earns its keep in two cases: generation failed during promotion, or the promote PR targeted `release-X.Y` so the file never reached `main`. Since the rc freeze the second case is **every** release, minor and patch alike — the promote PR always targets the release line (see [Regular Releases](./regular-releases.md#regular-releases)), which makes this backstop the only route by which a published changelog reaches `main`. In that case it **ports the reviewed file from the tag commit verbatim** rather than regenerating — a second AI pass there would spend quota and then overwrite already-published, already-reviewed release notes. + +### Phase 3 — `update-website-docs` (now the backstop) + +The `cozystack/website` "update managed apps reference" PR is normally opened **earlier, at promote time**, by [`promote-rc.yaml`](../../.github/workflows/promote-rc.yaml)'s `website-docs` job — not here. That job fetches the README content from the `release-X.Y.Z` staging branch `promote` just pushed (via the website Makefile's `FETCH_REF` variable), so the docs are ready to review alongside the promote PR while the stable tag is still unborn. It refreshes the trunk version pins from the staging ref before promoting `next/` → `vX.Y/`, so a new minor's docs inherit fresh Talos/cozystack pins instead of a stale `next.yaml`. It is **non-blocking**: if it fails (or trips its `FETCH_REF`-support guard against a website checkout that predates that Makefile variable), the promote PR opens with a ⚠️ website-docs line and this tag-time job backfills the same branch. + +**Merge-timing contract:** the website PR must NOT be merged before the release is published (finalize). Merging it early flips the site's latest-version pointer to a version whose versioned docs and `openapi.json` are not on GitHub yet, so every version-pin and API link for the new version 404s. Both the website PR body and the promote PR body say so; park the website PR until the GitHub release for `vX.Y.Z` is live, then merge. + +This tag-time `update-website-docs` job stays as the **backstop**. It runs with `if: !cancelled() && needs.prepare-release.result == 'success' && !contains(github.ref_name, '-')` (surviving a failed/skipped changelog phase, stopping on cancel, and skipping every pre-release tag), decides whether to promote `next/` → `vX.Y/`, runs `make update-all`, stages `content hugo.yaml data/versions`, and force-pushes the same `update-docs-vX.Y.Z` branch. On the normal path — where `promote-rc.yaml::website-docs` already did the work — it no-ops into "No changes to commit". At tag time the stable tag exists, so its `BRANCH=RELEASE_TAG` fetch resolves without needing `FETCH_REF`. For it to fire at all, finalize must push the stable tag with the **CI app token** (see [Phase 5](#phase-5--pull-requests-releaseyaml-finalize)) — a tag pushed with the default `GITHUB_TOKEN` triggers no workflow run. + +If anyone changes the website Makefile to write somewhere else (e.g. `static/`, `i18n/`), the `git add` list must grow in **both** jobs or the PR silently drops files. + +### Phase 4 — review and merge the promote PR + +Reviewer checklist for the `chore(release): promote vX.Y.Z-rc.N -> vX.Y.Z` PR: + +- [ ] The PR body says `✅ RC full e2e was verified`; if it says the gate was bypassed, obtain explicit maintainer acceptance or add `full-e2e` and wait for that opt-in run. +- [ ] `Verify release packages candidate` is green. It pulls the candidate and original rc artifact by digest, compares the candidate to GitHub's prospective merge tree, and feeds the required `E2E Tests` status even when full E2E is not repeated. Do not edit `packages/` on this PR after generation; if the guard reports drift, re-dispatch promotion to create and pin a new run-specific candidate. Note what a green here does *not* cover: GitHub fires no `pull_request` event when the base branch advances, so a `packages/` change merged to the base afterwards is never re-verified on the PR. Finalize repeats the check against the real merge commit and catches that case before any stable name exists — but it catches it after the promote PR has already merged, so a `packages/` change landing on the base while a promote PR is open is worth holding back. +- [ ] The PR body's **website-docs line** is present: if ✅, the `cozystack/website` docs PR is open and **parked** — do NOT merge it until `vX.Y.Z` is published (see [Phase 3](#phase-3--update-website-docs-now-the-backstop)); if ⚠️, the tag-time backstop will backfill it after finalize. +- [ ] Diff is digest pins + image tags only — nothing else. +- [ ] No accidental config drift (a value file you don't recognize). +- [ ] If any chart bumped, check the new digest pulls — `crane manifest ghcr.io/cozystack/cozystack/@` should return. +- [ ] Build artifacts on the draft release page exist and match the expected count. +- [ ] The PR includes `docs/changelogs/vX.Y.Z.md`, it has content, and the entries match the commit range (see [Changelog pre-publish verification](./changelogs.md#changelog-pre-publish-verification)). If the PR body carries the ⚠️ "No changelog in this PR" line, resolve that before merging — finalize publishes this file as the release body, unless the PR also carries `docs/releasenotes/vX.Y.Z.md` (see [Phase 6](#phase-6--update-releasenotesyaml-sync-github-release-body)). + +### Phase 5 — `pull-requests-release.yaml` (finalize) + +Fires on merge of a PR that is merged, carries the `release` label, and is authored by `cozystack-ci[bot]` (the last guard closes the "name a branch `release-X.Y.Z`, get it labelled, merge it" hole). Head branch must match `release-X.Y.Z[-suffix]`. This is where **every consumer-visible or write-once side effect of a promotion happens** — after the rc's mandatory E2E was checked at dispatch and the PR merged, making promotion transactional at stable names. Steps: + +1. **Verify the packages candidate before creating any stable tag.** [`hack/verify-promoted-packages.sh`](../../hack/verify-promoted-packages.sh) pulls the candidate by the digest committed in installer values, proves it matches the merged `packages/` tree after normalizing only the impossible self-reference, rejects surviving rc image tags, then follows the candidate's embedded pre-push `platformSourceRef` back to the original rc artifact and compares normalized container `repo@digest` sets. Any package edit after candidate publication or any changed container digest aborts finalize while all stable names are still absent. +2. **Create the tag at the merge commit** (write-once). The merge commit of `Prepare release vX.Y.Z` did not exist before the PR opened, so there is nothing to move — the tag is created here for the first time. A pre-existing tag at a different commit fails the step loudly rather than being force-moved (see [Tag immutability](./tag-immutability.md#tag-immutability)). The checkout uses `persist-credentials: false` so this push authenticates as the **CI app** (via `git remote set-url`), not the default `GITHUB_TOKEN` — a `GITHUB_TOKEN` push creates no workflow run, so a persisted-credential push would silently skip `tags.yaml` entirely and its stable-tag backstops (`generate-changelog`, `update-website-docs`) would never fire. +3. **Cut the `api/apps/v1alpha1/vX.Y.Z` Go-module tag** (write-once, stable only) at the same commit, so Go consumers of `api/apps/v1alpha1` get the release. Moved here from `tags.yaml`, whose `prepare-release` body is skipped for a promoted stable (the draft already exists). +4. **Ensure the maintenance branch `release-X.Y` exists** at the tag commit. Since the rc freeze creates it, this is normally a no-op fast-forward — the merge commit is already the branch tip. Still created if missing; updated fast-forward-only — a non-fast-forward update warns and is left for a maintainer rather than being force-updated. +5. **Publish the draft release**, with `docs/releasenotes/vX.Y.Z.md`, or without it `docs/changelogs/vX.Y.Z.md`, from the merge commit as its body (absent or whitespace-only files warn and leave the draft's body in place, rather than publishing blank notes, and a body over 100000 bytes is published as a link, see [Phase 6](#phase-6--update-releasenotesyaml-sync-github-release-body)). `make_latest` is computed against published-non-prerelease tags: prereleases stay `false`; tags older than the current max stay `false` (and the current max is force-restored to `latest` if necessary, so an older patch tag cut after a newer minor won't downgrade `latest`). +6. **Retag the verified packages candidate and rc container images to stable** by digest (`hack/promote-retag.sh`, no container rebuild) and **publish the stable `cozy-installer` chart**. `:latest` (on both the images and the chart) moves only when this release's `make_latest` was `true` — the same decision as step 5, so the release's `latest` and the images' `:latest` never disagree. The chart is packaged with `platformVersion` stamped into its default values so the documented `helm --install --version X.Y.Z` path reports the stable version. + +### Phase 6 — `update-releasenotes.yaml` (sync GitHub Release body) + +Fires on pushes to `main` that touch `docs/changelogs/v*.md`. Reads each `docs/changelogs/vX.Y.Z.md` and PATCHes the matching GitHub Release's `body` if it differs. Since Phase 5 now sets the body directly from the merge commit, this is no longer on the critical path — it covers later **edits** to a published changelog, the backstop PR landing a changelog that reached `main` after the fact, and manual re-syncs via `workflow_dispatch`. It only watches `main`, which is why finalize (not this job) is what populates a release promoted onto `release-X.Y` — since the freeze, that is every release rather than only a patch. + +The release body is `docs/releasenotes/vX.Y.Z.md` when it exists and is not blank, otherwise the changelog, which stays the full record either way, and a push to `main` touching either file fires this sync. Finalize sets the body after the stable tags exist, where a body GitHub refuses would strand the release, so at publish time a body over 100000 bytes is replaced by a one-line link to `docs/changelogs/vX.Y.Z.md` on the tag, with a warning in the run's log. This sync never writes that link: it warns and leaves such a release's body as it is. The `tags.yaml` backstop ports only the changelog to `main`, so release notes have to be added to `main` as well, otherwise the sync falls back to the changelog and replaces the release notes with it whenever the changelog fits. diff --git a/docs/release/cleanup.md b/docs/release/cleanup.md new file mode 100644 index 000000000..b192c5af5 --- /dev/null +++ b/docs/release/cleanup.md @@ -0,0 +1,6 @@ +## Cleanup after release + +- The `release-X.Y.Z` branch is deleted by GitHub when its PR merges. The `release-X.Y` maintenance branch is created by `cut-prerelease.yaml` at the rc freeze (create-only, never force-moved) and fast-forwarded afterwards by `pull-requests-release.yaml::Ensure maintenance branch`. +- The draft release is published by the same workflow. +- The release body is set by finalize from `docs/changelogs/vX.Y.Z.md` at publication. Afterwards, `update-releasenotes.yaml` re-syncs that file into the GitHub Release body on any push to `main` that touches it — so edits to a published changelog land on the release page the next time `main` moves. +- Local cleanup: remove your worktree (`git worktree remove`) and prune merged release branches. diff --git a/docs/release/introduction.md b/docs/release/introduction.md new file mode 100644 index 000000000..78c0e1781 --- /dev/null +++ b/docs/release/introduction.md @@ -0,0 +1,11 @@ +## Introduction + +Cozystack uses a staged release process to ensure stability and flexibility during development. + +There are three types of releases: + +- **Release Candidates (RC)** – Preview versions (e.g., `v1.2.0-rc.1`) used for final testing and validation. +- **Regular Releases** – Final versions (e.g., `v1.2.0`) that are feature-complete and thoroughly tested. +- **Patch Releases** – Bugfix-only updates (e.g., `v1.2.1`) made after a stable release, based on a dedicated release branch. + +All three are matched by `tags.yaml`'s regex `^v\d+\.\d+\.\d+(-(alpha|beta|rc)\.\d+)?$`. The tag push is the trigger for the whole pipeline. **Pre-release tags (`-alpha` / `-beta` / `-rc`) are cut with the [`Cut Pre-release Tag`](../../.github/workflows/cut-prerelease.yaml) workflow** (manual dispatch from `main` or `release-X.Y`) — it pushes the tag as the CI app at the dispatch branch's tip, so GitHub fills `base_ref` (`tags.yaml`'s `Get base branch` step refuses tags pushed without a base) and the push triggers `tags.yaml` (a tag pushed with the default `GITHUB_TOKEN` would not). Stable `vX.Y.Z` tags are never pushed by hand at all — they are cut write-once by the promote flow at a PR merge commit. Only `-rc.N` pre-releases feed the promotion flow ([`promote-rc.yaml`](../../.github/workflows/promote-rc.yaml) accepts `vX.Y.Z-rc.N` alone); `-alpha.N` / `-beta.N` tags are built and published for download and validated on demand with the [`e2e-tag.yaml`](../../.github/workflows/e2e-tag.yaml) button, but are never promoted to a stable release. diff --git a/docs/release/nightly-builds.md b/docs/release/nightly-builds.md new file mode 100644 index 000000000..df83de7f2 --- /dev/null +++ b/docs/release/nightly-builds.md @@ -0,0 +1,21 @@ +## Nightly builds + +A nightly is an **installable copy of `main` on GHCR — not a rebuild and not a release**. [`build-main.yaml`](../../.github/workflows/build-main.yaml) already builds every push to `main` into the CI registry (OCIR); the nightly promotes that build to the public release registry (GHCR) and proves it installs. + +[`nightly.yaml`](../../.github/workflows/nightly.yaml) runs daily (gated by the `NIGHTLY_ENABLED` repo variable) as three jobs; build-disk and e2e both start once mirror has finished: + +1. **mirror** — resolve the exact commit `cozystack-packages:main` was built from, then [`hack/nightly-mirror.sh`](../../hack/nightly-mirror.sh) copies every cozystack-owned component image OCIR→GHCR **by digest** (bit-for-bit, no rebuild) and re-publishes the rewritten `cozystack-packages` artifact and the `cozy-installer` chart to GHCR, tagged `0.0.0-nightly...` plus a floating `nightly`. +2. **build-disk** — assemble the Talos `nocloud` disk from the upstream siderolabs imager (the profile references only `ghcr.io/siderolabs/*`, so this needs no cozystack image and no rebuild) and publish it as a GHCR OCI artifact (`cozystack-nocloud`) so a nightly is installable on real hardware. The nightly e2e does not boot it. +3. **e2e** — stage the published GHCR closure (rewritten tree + the `cozy-installer` chart pinned to the GHCR packages artifact) and run the **full** app suite on Talos containers, which do not boot the disk. A nightly has no diff, so Test Impact Analysis does not apply. + +No GitHub release and no `api/apps/v1alpha1/*` Go-module tag are created for a nightly. [`retention.yaml`](../../.github/workflows/retention.yaml) prunes old GHCR nightly versions (keeps the newest 14 per package the current nightly publishes, named from the published `cozystack-packages:nightly` tree by [`hack/retention-packages.sh`](../../hack/retention-packages.sh), except packages linked to another repository, which are skipped with a warning; the floating `nightly`, release tags and untagged versions are never touched) and abandoned packages candidates. A candidate version is eligible only when all of these hold: it carries at least one tag and **every** tag on that manifest matches the strict `promotion-vX.Y.Z-from-vX.Y.Z-rc.N-run--` form, so a manifest that has been retagged stable is excluded; it was last updated more than 30 days ago; its digest is not pinned by `packages/core/installer/values.yaml` at the head of an **open** pull request that is same-repository, authored by `cozystack-ci[bot]`, on a `release-X.Y.Z` branch and carrying the `release` label; and its digest is not pinned by that same file at the tip of `main` or of any `release-X.Y` branch — which is what keeps a candidate safe between the promote PR merging and finalize retagging it. Any such PR head whose pin is not exactly one `digest=sha256:<64 hex>` stops the candidate sweep for that run and fails the job, without affecting the nightly sweep. + +Install a nightly: + +```bash +helm upgrade --install cozystack \ + oci://ghcr.io/cozystack/cozystack/cozy-installer --version 0.0.0-nightly.20260626.15992304129.1 +# ...or --version nightly for the latest +``` + +The matching Talos node image is `ghcr.io/cozystack/cozystack/cozystack-nocloud:0.0.0-nightly.20260626.15992304129.1` (pull with `oras`). diff --git a/docs/release/patch-releases.md b/docs/release/patch-releases.md new file mode 100644 index 000000000..9f23e23d6 --- /dev/null +++ b/docs/release/patch-releases.md @@ -0,0 +1,82 @@ +## Patch Releases + +A patch release now follows exactly the same shape as a [regular release](./regular-releases.md#regular-releases) — by the time `vX.Y.0` ships, everything is already happening on `release-X.Y`. The only difference is where the line starts: + +* `release-X.Y` already exists, created by the freeze at `vX.Y.0-rc.1`, so there is no branch to create. +* Patch commits are cherry-picked onto it, and the rc is cut by dispatching **from `release-X.Y`** — the same dispatch used for `rc.2` of the original release. + + +Let's assume that we've released `v1.2.0` and that development is ongoing. We have introduced a couple of new features and some fixes to features that we have released in `v1.2.0`. + +Once problems were found and fixed, a patch release is due. + +```mermaid +gitGraph + commit id: "feature 3" tag: "v1.2.0-rc.1" + branch release-1.2 + checkout release-1.2 + commit id: "Release v1.2.0" tag: "v1.2.0" + checkout main + commit id: "feature 4" + commit id: "patch 1" + commit id: "feature 5" + commit id: "patch 2" +``` + + +1. Fixes reach the existing `release-1.2` branch from `main` through the backport batch, which cherry-picks what the [backport policy](./backports.md) admits and nothing else. + + The batch runs twice a week, so a fix merged into `main` reaches the line with the next batch that can pick it cleanly, without anyone asking for it. + + ```mermaid + gitGraph + commit id: "feature 3" tag: "v1.2.0-rc.1" + branch release-1.2 + checkout release-1.2 + commit id: "Release v1.2.0" tag: "v1.2.0" + checkout main + commit id: "feature 4" + commit id: "patch 1" + commit id: "feature 5" + commit id: "patch 2" + checkout release-1.2 + cherry-pick id: "patch 1" + cherry-pick id: "patch 2" + ``` + + Merge the open batch pull request first. Before the cut, `./backport-batch check --line release-1.2 --cut` (build it with `go build ./cmd/backport-batch`) has to exit 0: it exits 1 while a fix the rules take is not on the line, including one that is only on the open batch pull request, which the cut would not carry, and prints the URLs; it prints what the batch deferred as warnings. See [Cherry-pick triage before a patch](./backport-mechanics.md#cherry-pick-triage-before-a-patch). + +2. The maintainer cuts a release candidate (`v1.2.1-rc.N`) via the [`Cut Pre-release Tag`](../../.github/workflows/cut-prerelease.yaml) workflow (manual dispatch **from `release-1.2`**), which tags that branch's `HEAD`. CI builds and publishes the rc, pushes the `release-1.2.1-rc.N` staging branch, and runs the mandatory full `rc-e2e` job against the published tag. +3. Watch `rc-e2e` and wait for it to pass, then complete the other release checks. A successful manual `e2e-tag.yaml` run for `v1.2.1-rc.N` is also valid evidence if the latest `tags.yaml` run does not carry a green `rc-e2e`. **Optional:** press the `Generate RC Changelog` button ([`changelog-rc.yaml`](../../.github/workflows/changelog-rc.yaml)) to generate `docs/changelogs/v1.2.1.md` at rc time and bank it on the rc staging branch; promotion then reuses it instead of regenerating. +4. Once the checks are green, run [`promote-rc.yaml`](../../.github/workflows/promote-rc.yaml) (manual dispatch **from `main`**, as for every promotion, not from `release-1.2`) with that rc tag. It runs the same five jobs as a regular promotion: the dispatch first gates on the latest tag-push `rc-e2e` or a successful tag-correlated manual E2E run (`skip_e2e_gate` overrides it), verifies that `release-1.2` already carries the candidate-aware pipeline, then commits and publishes the rewritten packages tree under a run-specific temporary `promotion-*` tag, adds a second commit pinning the candidate on the `release-1.2.1` branch, drafts the `v1.2.1` release with the restamped assets, generates or picks up `docs/changelogs/v1.2.1.md` and commits it onto that branch, opens the parked `cozystack/website` docs PR (updating the existing `v1.2/` directory in place, since a patch does not promote `next/`), and opens the promote PR into `release-1.2` with only the `release` label. The promote PR body carries the same ✅/⚠️ E2E, changelog, and website-docs lines and runs no E2E by default; add `full-e2e` manually to force a repeat. As with a regular release every stable name is deferred to merge; retention protects the temporary candidate while this PR is open and, after it merges, while `release-1.2` still pins it — until finalize retags it stable. + + ```mermaid + gitGraph + commit id: "feature 3" tag: "v1.2.0-rc.1" + branch release-1.2 + checkout release-1.2 + commit id: "Release v1.2.0" tag: "v1.2.0" + checkout main + commit id: "feature 4" + commit id: "patch 1" + commit id: "feature 5" + commit id: "patch 2" + checkout release-1.2 + cherry-pick id: "patch 1" + cherry-pick id: "patch 2" tag: "v1.2.1-rc.1" + branch release-1.2.1 + commit id: "Prepare release v1.2.1" + checkout release-1.2 + merge release-1.2.1 id: "Pull request" + ``` + + Finally, when release is confirmed, the release sequence goes on. + +5. Maintainer reviews the PR against the [Phase 4 checklist](./ci-pipeline.md#phase-4--review-and-merge-the-promote-pr), confirms the E2E-verification and changelog lines and notes the parked website-docs line, and merges it — **do not squash-merge**. GitHub removes the merged branch `release-1.2.1` (auto-delete-on-merge is enabled). +6. CI workflow triggers on merge (all consumer-visible or write-once side effects, after the rc E2E gate and PR review): + 1. Verifies the pinned packages candidate against the merged tree and the original rc artifact's container digests. + 2. Creates the tag `v1.2.1` at the newly created merge commit — write-once. The tag is published here for the first time, never moved. + 3. Cuts the write-once `api/apps/v1alpha1/v1.2.1` Go-module tag at the same commit. + 4. Publishes the release page (`draft` → `latest`; `latest` moves only if `v1.2.1` is the newest published stable). + 5. Retags the verified packages candidate and rc container images by digest to `v1.2.1` and publishes the stable `cozy-installer` chart — no container rebuild. +7. Once the release is published, merge the parked `cozystack/website` docs PR, then announce the release to the community. diff --git a/docs/release/pre-release-checklist.md b/docs/release/pre-release-checklist.md new file mode 100644 index 000000000..8e6257304 --- /dev/null +++ b/docs/release/pre-release-checklist.md @@ -0,0 +1,14 @@ +## Pre-release verification checklist + +For RCs and final releases, run this before merging the release PR. Each item is here because something has shipped without it and broken users. + +- [ ] **The published rc passed mandatory full E2E.** Confirm the promote PR says `✅ RC full e2e was verified`; the normal promote PR itself runs no E2E. Add `full-e2e` manually only when a repeat is required, and treat a ⚠️ bypass line as an explicit release-risk decision. +- [ ] **Upgrade from previous patch** (`vX.Y.(Z-1)`) on a real cluster. `helm upgrade` succeeds, all HelmReleases reach Ready, no CRD schema rejections. +- [ ] **Upgrade from previous minor** (`v(X-1).Y.0`) for RC and minor releases. Same assertions. +- [ ] **At least one tenant with `publishing.ingressName != tenant-root`** and a real Let's Encrypt-staging cert issuance. +- [ ] **Apply-mutate-reapply** on the kubernetes umbrella HelmRelease (catches second-reconcile bugs). +- [ ] **For every CRD-source bump** (kubevirt, cert-manager, flux, cilium, kamaji): `helm template | kubectl apply --dry-run=server` against the freshly-installed CRDs. +- [ ] **For every flux / helm-controller / kubevirt-operator / cert-manager bump:** paste the upstream breaking-changes section of the bump's CHANGELOG into the PR body before merge. +- [ ] **After cutting the tag,** watch `pull-requests-release.yaml::Finalize Release`. If it fails on `Draft release for v... not found`, undraft the release manually and file the workflow regression — this has been a known recurring failure since the `Publish draft release` step lost its explicit `github-token` in refactor `66a756b6`. +- [ ] **The promote PR carries `docs/changelogs/vX.Y.Z.md` and it was verified** per [Changelog pre-publish verification](./changelogs.md#changelog-pre-publish-verification). Finalize publishes this file as the release body, so verifying it before merge is verifying the release notes. +- [ ] **The `cozystack/website` docs PR stays parked until publish.** Promotion opens it early; merging it before the GitHub release for `vX.Y.Z` is live 404s the new version's docs and API links. Merge it right after finalize publishes the release (regular-release step 6, patch step 7). diff --git a/docs/release/regular-releases.md b/docs/release/regular-releases.md new file mode 100644 index 000000000..cdb007025 --- /dev/null +++ b/docs/release/regular-releases.md @@ -0,0 +1,78 @@ +## Regular Releases + +A regular release `vX.Y.0` is **promoted from a release-candidate that already passed e2e** — never tagged by hand and never rebuilt. The bytes shipped as `vX.Y.0` are the exact `vX.Y.0-rc.N` images, retagged by digest. We'll use `v1.2.0` as an example. + +```mermaid +gitGraph + commit id: "feature" + commit id: "feature 2" + commit id: "feature 3" tag: "v1.2.0-rc.1" +``` + +A regular release sequence runs as follows: + +1. Cut the first release candidate (`v1.2.0-rc.1`) from the last good commit on `main`: run the [`Cut Pre-release Tag`](../../.github/workflows/cut-prerelease.yaml) workflow (manual dispatch **from `main`**) with the tag. It tags `main`'s HEAD as the CI app, then **creates `release-1.2` at that commit, freezing the line**; `tags.yaml` then builds the rc images, publishes the rc prerelease, pushes the digest-vendored `release-1.2.0-rc.N` staging branch, and runs its mandatory `rc-e2e` job by calling [`e2e-tag.yaml`](../../.github/workflows/e2e-tag.yaml) against that published tag. +2. Watch the rc's mandatory full E2E and wait for it to pass, then complete the other checks in [Pre-release verification checklist](./pre-release-checklist.md#pre-release-verification-checklist). If the latest `tags.yaml` run cannot provide a green `rc-e2e`, a successful manual dispatch of [`e2e-tag.yaml`](../../.github/workflows/e2e-tag.yaml) for the same tag is equivalent gate evidence. `main` is already open for the next minor, so anything landing there is **not** in this release until it reaches `release-1.2`: a fix merged into `main` gets there through the [backport batch](./backports.md#which-lines-the-batch-runs-for), which runs for `release-1.2` from the freeze on, and a fix with no counterpart on `main` through a maintainer's pull request against `release-1.2`. A later rc is cut by dispatching the workflow **from `release-1.2`**, and only once `./backport-batch check --line release-1.2 --cut` exits 0: merge the open batch pull request first, so that the rc carries every fix the policy takes. **Optional:** once the notes are worth reviewing, press the `Generate RC Changelog` button ([`changelog-rc.yaml`](../../.github/workflows/changelog-rc.yaml)) to generate `docs/changelogs/v1.2.0.md` now and bank it on the `release-1.2.0-rc.N` staging branch — so there is time to review and hand-edit it before promotion. Skipping the button changes nothing; promotion generates the changelog itself. + + ```mermaid + gitGraph + commit id: "feature" + commit id: "feature 2" + commit id: "feature 3" tag: "v1.2.0-rc.1" + branch release-1.2 + checkout main + commit id: "feature 4 (next minor)" + checkout release-1.2 + commit id: "backported fix" tag: "v1.2.0-rc.2" + ``` + +3. Once the checks are green, run the [`promote-rc.yaml`](../../.github/workflows/promote-rc.yaml) workflow (manual dispatch **from `main`**, the only branch it is dispatched from, whichever line the rc belongs to) with that rc tag. Its `parse` job verifies E2E before any staging: it accepts a successful `rc-e2e` job in the latest `tags.yaml` push run for the tag, or any retained successful manual `e2e-tag.yaml` run whose expanded E2E job name targets the tag. The emergency `skip_e2e_gate` input bypasses this check, logs a loud warning, and marks the promote PR with ⚠️. Before its first registry write, promotion also proves that the selected `main` or `release-X.Y` target already contains the candidate-aware PR gate, finalizer and trusted verifier. A maintenance branch that lacks them gets them before its next patch is promoted, through the batch with `backport/include` on the pull request that brought them to `main`, or through a maintainer's pull request against the line. Promotion **creates no stable name before merge**: dispatch does write to the registry — it publishes one `promotion-*` packages candidate, and that tag is real and publicly listable — but it creates no `vX.Y.Z` tag, moves no `latest`, and publishes no stable installer, so nothing a consumer resolves changes until the PR merges. It: + 1. Rewrites the rc version substring to `1.2.0` and commits that exact tree, serializes its `packages/` directory under a run-specific temporary OCI tag, then adds a second commit pinning the candidate's immutable digest in the installer before pushing `release-1.2.0`. Container digests remain exactly the rc's; the two commits give the OCI revision an honest source SHA without pretending the artifact can contain its own digest. + 2. Drafts the `v1.2.0` release and uploads the (restamped) assets. + 3. Generates `docs/changelogs/v1.2.0.md` (in a parallel job, detached at the rc tag) — or, if you pressed the rc-time `Generate RC Changelog` button, copies the file already banked on the `release-1.2.0-rc.N` staging branch instead of regenerating — and commits it onto the `release-1.2.0` branch, so the changelog is reviewed as part of the promotion and finalize can publish the release with it already in place. Non-blocking: if generation fails the PR still opens, carrying a ⚠️ line that says the changelog is missing. + 4. Opens the `cozystack/website` "update managed apps reference" PR (`update-docs-v1.2.0` branch), generating the docs from the `release-1.2.0` staging branch via `FETCH_REF`. Non-blocking, and **do not merge that PR until `v1.2.0` is published** — merging early breaks the live site's version routing (see [Phase 3](./ci-pipeline.md#phase-3--update-website-docs-now-the-backstop)). + 5. Opens the `chore(release): promote v1.2.0-rc.N -> v1.2.0` PR into `release-1.2`, labelled `release` only. The PR body records whether E2E was verified or bypassed, plus ✅/⚠️ changelog and website-docs lines. E2E does not run on this promote PR by default because the immutable rc already passed the mandatory full suite; a maintainer may add `full-e2e` to run it again. The stable retag itself is deferred to the merge (step 5), so an abandoned promotion leaves no stable-named images and cannot wedge a re-promotion; retention protects the temporary candidate for as long as this release PR remains open, then may remove it after 30 days. + + The PR targets the maintenance branch, not `main`: `promote-rc.yaml` prefers `release-X.Y` whenever it exists, and since the rc freeze it always does. The digest-vendored `Prepare release` commit therefore stays on the release line instead of landing on `main`. + + ```mermaid + gitGraph + commit id: "feature 3" tag: "v1.2.0-rc.1" + branch release-1.2 + checkout release-1.2 + commit id: "backported fix" tag: "v1.2.0-rc.2" + branch release-1.2.0 + checkout release-1.2.0 + commit id: "Prepare release v1.2.0" + commit id: "Pin promoted packages artifact" + checkout release-1.2 + merge release-1.2.0 id: "Pull Request" + ``` + +4. Maintainer reviews the PR and the draft release against the [Phase 4 checklist](./ci-pipeline.md#phase-4--review-and-merge-the-promote-pr): confirm the E2E-verification line is ✅ (or explicitly accept its ⚠️ bypass), the changelog line is ✅, and note the website-docs line — the `cozystack/website` docs PR that promotion parked, which stays unmerged for now. E2E does not run on this promote PR by default. Then merge — **do not squash-merge**, the stable tag must attach to a real merge commit. GitHub removes the merged branch `release-1.2.0` (the repo has auto-delete-on-merge enabled). +5. CI workflow triggers on merge (this is where every consumer-visible or write-once side effect happens, after the rc E2E gate and PR review): + 1. Pulls the pinned packages candidate by digest and verifies that it matches the merged `packages/` tree apart from the artifact's impossible self-reference, carries no rc image tags, and preserves the original rc artifact's container `repo@digest` set. + 2. Creates the tag `v1.2.0` at the newly created merge commit — write-once. The tag is published here for the first time, never moved. + 3. Cuts the write-once `api/apps/v1alpha1/v1.2.0` Go-module tag at the same commit. + 4. Ensures the `release-1.2` maintenance branch exists at the tag commit. Since the rc freeze created it, this is normally a no-op fast-forward: the merge commit is already its tip. + 5. Publishes the release page (`draft` → `latest`), using `docs/changelogs/v1.2.0.md` from the merge commit as the release body. + 6. Retags the verified packages candidate and rc container images by digest to `v1.2.0` (and `:latest` only when `v1.2.0` is the newest published stable), and publishes the stable `cozy-installer` chart — no container rebuild. +6. Once the release is published, merge the parked `cozystack/website` docs PR (opened back at promote time, step 3.iv) so the live site's version routing flips to `v1.2.0` — its versioned docs and `openapi.json` are on GitHub now. The maintainer can then announce the release to the community. + +```mermaid +gitGraph + commit id: "feature 2" + commit id: "feature 3" tag: "v1.2.0-rc.1" + branch release-1.2 + checkout main + commit id: "feature 4 (next minor)" + checkout release-1.2 + commit id: "backported fix" tag: "v1.2.0-rc.2" + branch release-1.2.0 + checkout release-1.2.0 + commit id: "Prepare release v1.2.0" + checkout release-1.2 + merge release-1.2.0 id: "Release v1.2.0" tag: "v1.2.0" +``` + +Note that `main` never receives the release commit. It forked away at the freeze and carries the next minor's work. diff --git a/docs/release/release-candidates.md b/docs/release/release-candidates.md new file mode 100644 index 000000000..55f7eec61 --- /dev/null +++ b/docs/release/release-candidates.md @@ -0,0 +1,18 @@ +## Release Candidates + +Release candidates are Cozystack versions that introduce new features and are published before a stable release. Their purpose is to help validate stability before finalizing a new feature release. + +Release candidates are given numbers `vX.Y.0-rc.N`, for example, `v1.2.0-rc.1`. The first one is cut from `main`, once all major features for the upcoming release have merged and the release enters its testing phase. + +**Cutting the first rc freezes the line.** [`cut-prerelease.yaml`](../../.github/workflows/cut-prerelease.yaml) creates `release-X.Y` at the tagged commit, and from that point the release's content is closed: + +- Every later cut for that line — `rc.2`, `rc.3`, an `alpha`/`beta`, or a patch-line rc — must be dispatched from `release-X.Y`. A dispatch from `main` is refused. +- Fixes reach the release only through the backport batch onto `release-X.Y`, or a maintainer's pull request against it (see [Backports](./backports.md)). The batch runs for the line from its next scheduled run on, [while it has not shipped](./backports.md#which-lines-the-batch-runs-for): it takes the fixes merged into `main` since the freeze, and an older line takes each of them only once this line's batch that carries it has merged. +- A later rc is cut only once `backport-batch check --line release-X.Y --cut` exits 0, so that it carries every fix the batch takes: the open batch pull request merges first. +- `main` reopens immediately for the next minor, so feature work never has to wait for the release to ship. + +This is what makes an rc mean something. Previously `release-X.Y` was created only when the stable release merged, so `rc.2` was cut from `main`'s tip and silently absorbed everything that had landed since `rc.1` — the shipped release could contain code that no rc had ever validated. + +**Un-freezing is manual and deliberate.** If an `rc.1` turns out to be unusable and the line has to be re-cut from `main`, delete `release-X.Y` by hand first; the refuse step blocks every other route back to a `main` dispatch, which is the point of it. Nothing automates the deletion, and nothing should — throwing away a frozen line is a decision worth making explicitly. + +Each RC contributes to a cumulative set of release notes that will be finalized when `vX.Y.0` is released. After testing, if no critical issues remain, the last good rc is **promoted** to the regular release `vX.Y.0` — the exact rc images retagged by digest, never rebuilt and never tagged from a later commit (see [Regular Releases](./regular-releases.md#regular-releases)). Promotion cuts the write-once `vX.Y.0` tag at the promote PR's merge commit, fast-forwards the `release-X.Y` maintenance branch the freeze already created, and opens the way for patch releases. diff --git a/docs/release/release-time-fires.md b/docs/release/release-time-fires.md new file mode 100644 index 000000000..f58fd48b7 --- /dev/null +++ b/docs/release/release-time-fires.md @@ -0,0 +1,35 @@ +## Release-time fires — what's gone wrong recently + +These are real regressions that escaped to users. The pattern in each: code passed CI, shipped in a stable release, broke customers. Read them as a working list of pre-release verification gaps. + +### v1.3.0 — cert-manager ingressClassName regression (fix #2562) + +**Bug:** A commit migrated ACME HTTP-01 to use the modern `acme.cert-manager.io/http01-ingress-ingressclassname` annotation. The matching ingress-shim code that reads that annotation was added by cert-manager upstream PR #8244 and was **never backported** to the `release-1.19` branch — but cozystack 1.3.0 shipped cert-manager v1.19.3. The annotation was silently dropped at runtime and every solver Ingress fell back to the ClusterIssuer's default class `tenant-root`. Let's Encrypt validation broke for every tenant whose `publishing.ingressName != tenant-root`. + +**Blast radius:** v1.3.0, v1.3.1, and v1.1.7 (the migration was cherry-picked to `release-1.1`). + +**Why CI missed it:** the migration commit was self-contained and `helm template` rendered cleanly. There was no E2E that creates a tenant with a non-default ingress class and watches a real Let's Encrypt cert issue. Verification had been done from the docs side ("the API has been available since cert-manager 1.12"), not against the shipped cert-manager source. + +**Would have caught it:** non-root-tenant E2E with LE-staging cert issuance, asserting the solver Ingress lands on the tenant's class. + +### v1.4.0 — kubevirt-instancetypes upgrade failure (fix #2612) + +**Bug:** `packages/system/kubevirt-instancetypes/Makefile` contained `sed -i '/persistent: true/d' templates/preferences.yaml`, which stripped the only child of `preferredTPM`, leaving `preferredTPM:` (null) in six Windows preferences. KubeVirt v1.6.x silently accepted it. The v1.6.3 → v1.8.2 operator bump (2026-04-27) hardened the CRD's OpenAPI schema and started rejecting null for an object-typed field. `helm upgrade` then failed on every cluster with `kubevirt-instancetypes` enabled. + +**Why CI missed it:** the kubevirt-operator bump and the inert `preferences.yaml` were two weeks apart in commit history. CI only tests fresh installs against the new CRDs; it doesn't run `helm upgrade` from prior versions. Schema regression on a vendored asset that hadn't been touched in 18 months. + +**Would have caught it:** `helm template | kubectl apply --dry-run=server -f -` against the freshly-installed CRDs of every bumped operator. Or an upgrade-from-N-1 E2E lane. + +### v1.4.0 — Flux 2.7 → 2.8 readiness deadlock (#2602) + +**Bug:** helm-controller v1.5.0 (shipped in Flux 2.8) changes the default wait strategy to kstatus polling, which polls **every applied resource including child HelmReleases**. The `packages/apps/kubernetes` umbrella has 19 child HRs that each `dependsOn: parent` (with a `lookup` guard so the dependency only activates after the parent exists). Pre-2.8: parent went Ready as soon as Helm returned. Post-2.8: parent waits for children, children wait for parent. Deadlock. + +**Why CI missed it:** the cycle only manifests on the second reconcile (parent exists, so the `lookup` activates the child's `dependsOn`). Fresh-install E2E dodges this — the parent-already-exists branch isn't taken on the first apply. + +**Would have caught it:** apply-mutate-reapply E2E (any chart bump in the kubernetes umbrella triggers a second reconcile). Plus an explicit PR-template requirement: for any flux/helm-controller bump, paste the upstream breaking-changes section into the PR body. + +### Patterns these share + +1. **Fresh-install CI is insufficient.** All three regressions passed fresh-install lanes. +2. **Upstream breaking-defaults bumps are the common shape.** kubevirt CRD hardening, helm-controller default wait strategy, cert-manager API surface drift. Pre-merge reading of upstream changelogs would have caught two of three. +3. **One-engineer-bitten-once is the only safety net for live verification.** The cert-manager bump PR included an explicit live-cluster verification step — because the same engineer had been bitten the prior week. There is no checklist requiring it. diff --git a/docs/release/signatures-and-sbom.md b/docs/release/signatures-and-sbom.md new file mode 100644 index 000000000..8aa47051e --- /dev/null +++ b/docs/release/signatures-and-sbom.md @@ -0,0 +1,29 @@ +## Release signatures and SBOM + +A release cut from a tree that has [`hack/sign-release-assets.sh`](../../hack/sign-release-assets.sh) carries three files beside its other assets, which [`hack/upload-assets.sh`](../../hack/upload-assets.sh) has that script write before it uploads anything. Releases cut before it have none of them, and neither does a maintenance line until the script is backported to it (see below). + +- `cozystack-source-sbom.spdx.json` is an SPDX SBOM, made with syft, of the committed source tree (the Go modules, npm lockfiles, GitHub Actions references and other manifests syft reads in it) and of the `cozypkg` binaries in the `cozypkg-*.tar.gz` assets. It does not describe what runs in the cluster: the container images carry their own SBOMs, see [SBOM of the container images](#sbom-of-the-container-images), and the Talos installer image, ISO, disk, kernel and initramfs images have none. Its name says what it covers, so that `cozystack-sbom` stays free for an SBOM of the release as a whole. +- `cozystack-checksums.txt` holds the SHA-256 of every other asset and of the SBOM. +- `cozystack-checksums.txt.sigstore.json` is a Sigstore bundle with a keyless cosign signature over the checksums. Its certificate names the workflow that published the release: `tags.yaml` for a pre-release, `promote-rc.yaml` for a stable one. + +One signature covers every asset through the checksums. To check a download, verify the checksums, then the file against them, with cosign v3.1.3 or later (v2.6.5 or later on the v2 line): + +```sh +cosign verify-blob cozystack-checksums.txt \ + --bundle cozystack-checksums.txt.sigstore.json \ + --certificate-identity-regexp '^https://github\.com/cozystack/cozystack/\.github/workflows/(tags\.yaml@refs/tags/v|promote-rc\.yaml@refs/heads/main$)' \ + --certificate-oidc-issuer https://token.actions.githubusercontent.com && + sha256sum --check --ignore-missing cozystack-checksums.txt +``` + +Older cosign accepts a legacy-format bundle that carries a bare public key in place of a certificate and skips the identity and issuer checks for it ([GHSA-fx35-mq7g-6g98](https://github.com/sigstore/cosign/security/advisories/GHSA-fx35-mq7g-6g98)), so a bundle swapped in next to the download, by a mirror or a proxy, passes there. The bundles this repository writes are in the new format, but cosign picks the format from the file, and `--new-bundle-format` does not stop that on the v3 line (v3.1.2 still accepts such a bundle with it), so the cosign version is what protects the check. + +The regexp pins the ref each workflow runs from: `tags.yaml` on a `v*` tag push, and `promote-rc.yaml` dispatched from `main`, the only branch it is dispatched from. A passing check proves that the checksums were signed by one of those runs in `cozystack/cozystack`. A `promote-rc.yaml` dispatched from another branch fails this check in its own upload step, with no asset uploaded, and an edited `promote-rc.yaml` has to be merged into `main` before it can sign. Until the `v*` [tag rulesets](./tag-immutability.md#repo-side-enforcement-tag-protection-rulesets) restrict tag creation to the CI app, though, anyone with write access can push a `v*` tag whose tree carries an edited `tags.yaml`, and its signature passes. + +The script runs the same `cosign verify-blob` before it returns, so a signature this check would reject fails the job before the first upload, and the release is not published with assets but without a signature. Both jobs that call `make upload_assets`, `tags.yaml::prepare-release` and `promote-rc.yaml::promote`, hold `id-token: write` for the signing identity and install syft and cosign v3.1.3, the version users are asked for above. They install syft from its release tarball, checked against a SHA-256 committed in the workflow, and not with `anchore/sbom-action/download-syft`, which runs an install script fetched at run time in a job that holds the release credentials; [`hack/ci-tool-installs-contract.bats`](../../hack/ci-tool-installs-contract.bats) keeps it that way. A stable release gets its own three files rather than its rc's: promotion restamps several assets, so the checksums are recomputed and signed again. + +`promote-rc.yaml` runs the `hack/upload-assets.sh` of the rc tree, not the dispatch ref's. A stable release is therefore signed only when its rc was tagged from a tree that has `hack/sign-release-assets.sh`, and a maintenance line starts carrying signatures once that script is backported to its `release-X.Y` branch. + +### SBOM of the container images + +The container images a release pins by digest each carry an SPDX SBOM of the packages in them, which BuildKit attaches at build time as an attestation (`SBOM=1` in `tags.yaml`, scanner and flags in [`hack/common-envs.mk`](../../hack/common-envs.mk)). The attestation is an entry of the image's index, so the digest the release pins names both, and promotion copies it with the image. Read it with `docker buildx imagetools inspect @ --format '{{ json .SBOM }}'`, which prints one document per platform. The attestations are not signed. A release cut before `SBOM=1` was set has none, and neither has the Talos installer image, which the imager builds and `skopeo` pushes, nor the third-party images `packages/` vendors by digest. diff --git a/docs/release/splitting-bundle-prs.md b/docs/release/splitting-bundle-prs.md new file mode 100644 index 000000000..ace989a88 --- /dev/null +++ b/docs/release/splitting-bundle-prs.md @@ -0,0 +1,10 @@ +## Splitting a release-blocking bundle PR + +Sometimes the work that has to land before a release is a 40-commit grab bag (CI stabilization, dependency bumps, chart fixes). Splitting it makes it reviewable and survivable. The strategy that has worked: + +1. **Verify what's already on `main`.** Use `git merge-base --is-ancestor` and subject grep to drop commits that have already landed. +2. **Find existing open PRs that cover the same commits.** Force-push to the existing branch instead of opening a duplicate — preserves review threads. +3. **Identify the "bottleneck" PR.** The one whose changes make previously-silent misconfigurations into hard errors (typically an operator-version bump). Everything else can fan out in parallel. +4. **Squash iterative same-author bug-on-bug fixes** inside each split. Preserve authorship via `--author` on the squashed commit. +5. **Mark the keystone PR as draft** and link in the body to the dependency PRs. Reviewers know it intentionally fails CI until the chain lands. +6. **Beware of concurrent registry pushes.** When fanning out 5+ PR CI runs simultaneously, multiple `make image` jobs can collide on shared floating tags. The `IMAGE_TAG=pr--` refactor solved this; if you see `Conflicted with another upload of the same manifest`, `gh run rerun --failed`. diff --git a/docs/release/stable-tags.md b/docs/release/stable-tags.md new file mode 100644 index 000000000..af908d046 --- /dev/null +++ b/docs/release/stable-tags.md @@ -0,0 +1,7 @@ +## Stable tags come from rc promotion + +A stable `vX.Y.Z` is created only by **promoting an existing release-candidate** that already passed e2e — never by rebuilding and never by a cron. + +- [`promote-rc.yaml`](../../.github/workflows/promote-rc.yaml) is triggered manually once an rc has gone green. It rewrites the rc version substring in the vendored image tags (the container digests stay the rc's), commits and publishes the resulting declarative packages tree under a unique run-specific `promotion-*` tag, commits that digest pin, and opens the `release-X.Y.Z` staging PR. The PR gate verifies the candidate against the prospective merge and original rc artifact; finalize repeats that check before creating the write-once stable tag at the merge commit, then retags the verified packages artifact and rc's already-built, e2e-passed container digests to the stable tag **by digest** (no container rebuild — see [`hack/promote-retag.sh`](../../hack/promote-retag.sh)) and publishes the release. An abandoned promotion leaves no stable-named bytes; its temporary candidate is retention-managed. + +So a commit on a supported `release-X.Y` line ships when a maintainer promotes the next rc for that line — not automatically within 24h. Pushing a stable `vX.Y.Z` tag by hand is **not** a supported path: `tags.yaml` fails fast on a stable tag that has no pre-existing draft ("stable tags come from promote-rc.yaml"), and even so the finalize step would refuse to move a pre-existing tag. Pre-releases (`vX.Y.Z-rc.N`, `-alpha.N`, `-beta.N`) are cut with the [`Cut Pre-release Tag`](../../.github/workflows/cut-prerelease.yaml) workflow, which pushes the tag as the CI app; [`tags.yaml`](../../.github/workflows/tags.yaml) then fires on that push, builds it, and publishes the pre-release. Cutting via the workflow (rather than a manual `git push`) is what lets repo admins lock `v*` tag creation to the CI app — see the tag-protection note below. diff --git a/docs/release/tag-immutability.md b/docs/release/tag-immutability.md new file mode 100644 index 000000000..fe7418279 --- /dev/null +++ b/docs/release/tag-immutability.md @@ -0,0 +1,18 @@ +## Tag immutability + +Published tags are **write-once** — once a `vX.Y.Z` or rc tag is pushed it is never moved or deleted. (Nightlies are not git tags at all — they are GHCR OCI tags, see [Nightly builds](./nightly-builds.md#nightly-builds).) Moving a tag silently poisons the Go module proxy / pkg.go.dev cache for `api/apps/v1alpha1/vX.Y.Z` and drifts SBOM/provenance toolchains, so the release flow is built so a move is impossible by construction: + +| File | Tag / branch handling | +|------|------------------------| +| [`pull-requests-release.yaml`](../../.github/workflows/pull-requests-release.yaml) | Verifies the pinned packages candidate before creating a stable name. Creates `vX.Y.Z` at the PR merge commit **write-once** (create if absent, no-op if unchanged, fail loudly if it would move — the merge commit is new, so there is nothing to move). Cuts the `api/apps/v1alpha1/` Go-submodule tag write-once at the same commit, **stable only** (never rc/beta/alpha). The `release-X.Y` maintenance branch is fast-forward-only. Retags the verified packages artifact and rc container digests to the stable image tag (also write-once at the image level). | +| [`tags.yaml`](../../.github/workflows/tags.yaml) | The `release-X.Y.Z-rc.N` staging branch is a mutable staging ref (compare-before-force: skipped when unchanged, force+log only when it genuinely moves). Fails fast on a stable `vX.Y.Z` tag with no pre-existing draft — stable tags come from `promote-rc.yaml`, never a hand push. | +| [`promote-rc.yaml`](../../.github/workflows/promote-rc.yaml) | Mutates no stable tags. Before staging, verifies green full E2E from the latest rc tag-push run or a tag-correlated manual published-tag run (unless loudly bypassed). Commits and publishes the rewritten packages tree under a run-specific temporary `promotion-*` tag, adds a second commit pinning its digest on the `release-X.Y.Z` branch, generates the changelog there, and opens the promote PR with `release` but no automatic `full-e2e`; the PR gate verifies the candidate and finalize repeats that verification before the stable tag and image retag. The staging branch is force-pushed on re-dispatch, but an existing `docs/changelogs/vX.Y.Z.md` is preserved across the rebuild. | + +This is the immutable-tag + rc-promotion model from [#2677](https://github.com/cozystack/cozystack/issues/2677): stable `vX.Y.Z` is created only by promoting an existing rc, rc tags are write-once, and `api/apps/v1alpha1/vX.Y.Z` is created only on a stable release. The old nightly `auto-release.yaml` (which delete-recreated auto-bumped patch tags) has been removed. rc and stable tags accrete permanently; the only churning artifacts are GHCR nightlies and abandoned temporary promotion candidates, which [`retention.yaml`](../../.github/workflows/retention.yaml) prunes (see [Nightly builds](./nightly-builds.md#nightly-builds)) — GHCR storage is the cost vector to watch. + +### Repo-side enforcement (tag-protection rulesets) + +The guarantees above are enforced in the workflows. Repo admins back them with two GitHub **tag rulesets** targeting `v*`: + +- **Immutability** — *Restrict updates* + *Restrict deletions*, **no bypass**. No actor (not even the CI app) can move or delete a shipped `v*` tag. Safe to enable at any time: nothing in the release flow ever moves or deletes a `v*` tag, it only creates new ones. +- **Creation control** — *Restrict creations* with the **CI app as the sole bypass actor**, plus *Limit branches/tags updated in a single push* = 1. This turns "don't hand-push tags" from convention into hard enforcement: every `v*` tag — pre-release **and** stable — can then be created only by CI. Enable this **only after** [`cut-prerelease.yaml`](../../.github/workflows/cut-prerelease.yaml) is in use, since that workflow is what makes CI the sole creator of pre-release tags; enabling it earlier would lock maintainers out of cutting rc/alpha/beta. (The Go-module tag `api/apps/v1alpha1/*` gets an equivalent pair of rulesets.) diff --git a/docs/security/incident-response.md b/docs/security/incident-response.md index 62469519e..156ce4f2f 100644 --- a/docs/security/incident-response.md +++ b/docs/security/incident-response.md @@ -40,11 +40,7 @@ One person may hold more than one role on a small incident. 4. **Private fix development.** The fix is developed under a **GitHub Security Advisory** (private fork) so that code and discussion stay confidential until release. -5. **Coordinated release.** The fix is shipped through the normal patch-release - and backport process. Which supported lines receive the backport is decided - per fix, weighing severity against backport risk — see the *Supported - Versions* table in `SECURITY.md`, which also records that no documented rule - governs that choice. +5. **Coordinated release.** The fix is shipped through the normal patch-release and backport process: the backport batch carries it onto the supported lines, the two latest minor releases, newest first, by the rules in [`docs/release/backports.md`](../release/backports.md), which a maintainer can override for a single fix. See the *Supported Versions* table in `SECURITY.md`. 6. **Disclosure.** A GHSA — and, when applicable, a CVE — is published. Public disclosure follows the outbound channels: GitHub Releases and release notes, the changelog, and the GHSA itself. The reporter is credited unless anonymity diff --git a/docs/security/self-assessment.md b/docs/security/self-assessment.md index 551bed8b3..ca49853ab 100644 --- a/docs/security/self-assessment.md +++ b/docs/security/self-assessment.md @@ -10,7 +10,7 @@ This document is a security self-assessment for [Cozystack](https://github.com/c | Software | | | Security Provider | No. Cozystack is a cloud platform, not a security product; security is a supporting property, not its primary function. | | Languages | Go, Helm, shell | -| SBOM | Not published at this time. Image builds can emit a CycloneDX SBOM attestation (`SBOM=1` in `hack/common-envs.mk`), but this is disabled by default; SBOM generation on release is a planned improvement. | +| SBOM | Not published at this time. Image builds can emit an SPDX SBOM attestation (`SBOM=1` in `hack/common-envs.mk`), but this is disabled by default; SBOM generation on release is a planned improvement. | ### Security links @@ -55,7 +55,7 @@ Actors are decomposed by **trust boundary**: two components are distinct actors | GitOps / Flux delivery layer | T1 — platform control plane | Reconciles HelmReleases/Kustomizations into arbitrary privileged manifests; effectively cluster-admin. | Tenants cannot create HelmReleases (RBAC); not tenant-network-reachable. | | `cozystack-api` aggregated API server | T1 — platform control plane | Converts tenant CRs into HelmReleases; can CRUD HelmReleases, Secrets, and Cilium policies cluster-wide. Acts as the policy-enforcing gateway. | Constrains tenants via fixed chart reference, name/quota/host validation, and admission. | | System operators / controllers | T1 — platform control plane | Domain-scoped cluster privileges (provision control planes, mint certs/secrets, program CNI). | Distinct ServiceAccounts; isolated from tenants by RBAC and network policy. | -| Tenant administrator (OIDC `-admin` / `-super-admin`) | T2 — tenant boundary | CRUD on `apps.cozystack.io` application kinds and `sdn.cozystack.io/securitygroups` in its namespace subtree; read on pods/services/ingress plus `delete` on a fixed set (pods/services/endpoints/events); no create/update of arbitrary core resources. (The ClusterRole also lists `persistentvolumes`, but that grant is inert under the namespace-scoped RoleBinding, since PVs are cluster-scoped.) `super-admin` holds the `apps.cozystack.io/*` wildcard (and can create child `Tenant`s); `admin` has an enumerated allowlist excluding some kinds (e.g. `tenants`, `monitoring`, `etcd`, `ingress`). | Namespace-scoped RBAC + admission policies + quota; no HelmRelease or cross-tenant access. | +| Tenant administrator (OIDC `-admin` / `-super-admin`) | T2 — tenant boundary | CRUD on `apps.cozystack.io` application kinds and `sdn.cozystack.io/securitygroups` in its namespace subtree; read on pods/services/ingress plus `delete` on a fixed set (pods/services/endpoints/events); `get` on persistentvolumeclaims and `create` on `upload.cdi.kubevirt.io/uploadtokenrequests`, the pair `virtctl image-upload` needs to upload into an existing VMDisk; no create/update of arbitrary core resources. (The ClusterRole also lists `persistentvolumes`, but that grant is inert under the namespace-scoped RoleBinding, since PVs are cluster-scoped.) `super-admin` holds the `apps.cozystack.io/*` wildcard (and can create child `Tenant`s); `admin` has an enumerated allowlist excluding some kinds (e.g. `tenants`, `monitoring`, `etcd`, `ingress`). | Namespace-scoped RBAC + admission policies + quota; no HelmRelease or cross-tenant access. | | Tenant user (OIDC `-view` / `-use`) | T2 — tenant boundary | Read-only view plus operational verbs (VM console/vnc/portforward, start/stop/restart). Cannot create Application CRs. | Strictly dominated by tenant-admin; cannot escalate. | | Parent vs child (nested) tenant | T2 — tenant boundary | Parent ServiceAccounts bind into descendant namespaces; children do not bind upward. Quota hierarchically capped. | Ancestor→descendant trust is one-way. | | Tenant workloads / managed services | T3 — workload boundary | Run tenant-controlled code; no cluster-API rights beyond their ServiceAccount. | Namespace-scoped RBAC/identity isolate API objects; on the network, Cilium egress confines each tenant pod to its own subtree + platform system services + `world`, so unrelated tenants cannot reach each other over the pod network (enforced on egress; ingress is open to `cluster` — see Non-goals). | @@ -93,6 +93,7 @@ Actors are decomposed by **trust boundary**: two components are distinct actors - **Upstream-only vulnerabilities** not introduced or worsened by Cozystack packaging or defaults. - **Ingress-side isolation of tenant pods.** Tenant-pod ingress is open to `world` and `cluster`, so a tenant pod is reachable by any in-cluster peer whose own egress permits it (platform components) or by a workload not governed by Cozystack's tenant egress policies. Cross-tenant isolation is enforced on the *egress* side, not tenant-pod ingress. - **Blocking cross-tenant reachability through externally-exposed services.** If a tenant publishes a LoadBalancer external IP, another tenant can reach it via `world` egress. +- **Network isolation between tenants on a hosted cluster without Cilium.** On the `isp-hosted` and `isp-hosted-slim` variants the CNI belongs to the host, and tenant Cilium policies are created only if the host serves the Cilium policy API. Without it, tenants get no network isolation from Cozystack, and isolating them is up to the host. - **Noisy-neighbour / side-channel** guarantees for co-located tenant pods beyond namespace scoping (and, for tenant Kubernetes/VMs, virtualization). - Acting as an **egress firewall**: tenant workloads may egress to `world` by default. - Supporting **pre-release builds and end-of-life versions**. diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md index 122364264..0a4ea0bb3 100644 --- a/docs/security/threat-model.md +++ b/docs/security/threat-model.md @@ -39,7 +39,7 @@ The actors below are decomposed **by trust boundary**, not by component: two com | GitOps / Flux delivery layer | T1 | Reconciles HelmReleases/Kustomizations into arbitrary privileged manifests; effectively cluster-admin. | Tenants cannot create HelmReleases/Kustomizations (RBAC); not tenant-network-reachable. | | `cozystack-api` aggregated API server (ServiceAccount) | T1 | CRUD HelmReleases, Secrets, and CiliumNetworkPolicies cluster-wide; reads Namespaces/RBAC/quotas/nodes. Acts as the policy-enforcing gateway that converts tenant CRs to HelmReleases. | A distinct, network-exposed attack surface from Flux; constrains tenants via fixed chart ref + name/quota/host validation + admission. | | System operators / controllers | T1 | Domain-scoped cluster privileges (provision control planes, mint certs/secrets, program CNI). | Distinct ServiceAccounts, but all cluster-admin-adjacent; isolated from tenants only by RBAC and network policy. | -| Tenant administrator (OIDC groups `-admin`, `-super-admin`) | T2 | CRUD on `apps.cozystack.io` application kinds and `sdn.cozystack.io/securitygroups` within its namespace subtree; read on pods/services/ingress plus `delete` on a fixed set (pods/services/endpoints/events); no create/update of arbitrary core resources. (The ClusterRole also lists `persistentvolumes`, but that grant is inert under the namespace-scoped RoleBinding, since PVs are cluster-scoped.) The `-super-admin` group holds the `apps.cozystack.io/*` wildcard (and so can create child `Tenant`s); the `-admin` group has an enumerated allowlist that excludes some kinds (e.g. `tenants`, `monitoring`, `etcd`, `ingress`, `external-dns`, `bootbox`). | Namespace-scoped RoleBindings + admission policies + quota; no access to HelmReleases, arbitrary core writes, or other tenants. | +| Tenant administrator (OIDC groups `-admin`, `-super-admin`) | T2 | CRUD on `apps.cozystack.io` application kinds and `sdn.cozystack.io/securitygroups` within its namespace subtree; read on pods/services/ingress plus `delete` on a fixed set (pods/services/endpoints/events); `get` on persistentvolumeclaims and `create` on `upload.cdi.kubevirt.io/uploadtokenrequests`, the pair `virtctl image-upload` needs to upload into an existing VMDisk; no create/update of arbitrary core resources. (The ClusterRole also lists `persistentvolumes`, but that grant is inert under the namespace-scoped RoleBinding, since PVs are cluster-scoped.) The `-super-admin` group holds the `apps.cozystack.io/*` wildcard (and so can create child `Tenant`s); the `-admin` group has an enumerated allowlist that excludes some kinds (e.g. `tenants`, `monitoring`, `etcd`, `ingress`, `external-dns`, `bootbox`). | Namespace-scoped RoleBindings + admission policies + quota; no access to HelmReleases, arbitrary core writes, or other tenants. | | Tenant user (OIDC groups `-view`, `-use`) | T2 | Read-only view of Application CRs, pods, and services, plus operational verbs only (VM console/vnc/portforward, start/stop/restart). Cannot create Application CRs. | Strictly dominated by tenant-admin; cannot escalate to create/delete, so it is a distinct actor. | | Parent tenant vs child (nested) tenant | T2 | Parent ServiceAccounts are bound into descendant namespaces; child ServiceAccounts are not bound upward. Quota is hierarchically capped. | Ancestor→descendant only; compromising a parent compromises its children, not the reverse. | | Tenant workloads / managed services | T3 | Run tenant-controlled code; no cluster-API rights beyond their ServiceAccount. | Namespace-scoped RBAC/identity isolate their API objects. On the network, Cilium egress confines each tenant pod to its own tenant subtree, platform system services, and `world` (out-of-cluster), so unrelated tenants cannot reach each other over the pod network — enforced on the egress side (tenant-pod ingress is open to `cluster`; see Non-goals for residual caveats). | @@ -83,6 +83,7 @@ The following are explicitly out of scope for the platform's security guarantees - **Upstream-only vulnerabilities** that Cozystack packaging and defaults do not introduce or worsen. - **Ingress-side isolation of tenant pods.** Tenant-pod ingress is open to the `world` and `cluster` entities, so a tenant pod is reachable by any in-cluster peer whose own egress permits it (platform components) and by a workload not governed by Cozystack's tenant egress policies (e.g. a privileged or system pod). Cross-tenant isolation is enforced on the *egress* side, not on tenant-pod ingress. - **Blocking cross-tenant reachability through externally-exposed services.** If a tenant publishes a LoadBalancer with an external IP, another tenant can reach it via `world` egress. +- **Network isolation between tenants on a hosted cluster without Cilium.** On the `isp-hosted` and `isp-hosted-slim` variants the CNI belongs to the host, and the tenant chart creates its Cilium policies only if the host serves the Cilium policy API (`packages/apps/tenant/templates/_helpers.tpl`, helper `tenant.ciliumPolicies`). Without it, tenants get no network isolation from Cozystack, and isolating them is up to the host. - **Noisy-neighbour and side-channel guarantees** for co-located tenant pods beyond namespace scoping (and, for tenant Kubernetes/VMs, virtualization). Co-located pods are not claimed to be side-channel isolated. - **Acting as an egress firewall.** Tenant workloads are allowed egress to `world` by default (`packages/apps/tenant/templates/networkpolicy.yaml`). - **Supporting pre-release builds and end-of-life versions** (`SECURITY.md`). @@ -91,7 +92,7 @@ The following are explicitly out of scope for the platform's security guarantees The single most load-bearing isolation control is the combination of two facts: -1. The tenant ClusterRoles (`packages/system/cozystack-basics/templates/clusterroles.yaml`) grant **no** `helm.toolkit.fluxcd.io` access and **no** create/update of arbitrary core resources — only CRUD on `apps.cozystack.io` application kinds (super-admin holds the `*` wildcard; admin an enumerated allowlist) and `sdn.cozystack.io/securitygroups`, read access to pods/services/ingresses, and (for tenant-admins) `delete` on a fixed set of core objects (pods/services/endpoints/events; the `persistentvolumes` entry in the ClusterRole is inert under the namespace-scoped RoleBinding). Tenant isolation is enforced by the *absence* of privileged grants in RBAC, not by an admission policy that whitelists `apps.cozystack.io/*` writes. +1. The tenant ClusterRoles (`packages/system/cozystack-basics/templates/clusterroles.yaml`) grant **no** `helm.toolkit.fluxcd.io` access and **no** create/update of arbitrary core resources — only CRUD on `apps.cozystack.io` application kinds (super-admin holds the `*` wildcard; admin an enumerated allowlist) and `sdn.cozystack.io/securitygroups`, read access to pods/services/ingresses, and (for tenant-admins) `delete` on a fixed set of core objects (pods/services/endpoints/events; the `persistentvolumes` entry in the ClusterRole is inert under the namespace-scoped RoleBinding), `get` on persistentvolumeclaims and `create` on `upload.cdi.kubevirt.io/uploadtokenrequests` (for uploading an image into an existing VMDisk with `virtctl image-upload`). Tenant isolation is enforced by the *absence* of privileged grants in RBAC, not by an admission policy that whitelists `apps.cozystack.io/*` writes. 2. The Application-to-HelmRelease conversion (`pkg/registry/apps/application/rest.go`) takes the chart reference, release-name prefix, and `valuesFrom` from server-side configuration; the tenant controls only the Helm values (`app.Spec`). If a future `ApplicationDefinition`, RBAC change, or API change ever let a tenant influence the chart reference, `valuesFrom`, or write HelmReleases directly, the T2→T1 isolation would collapse. Changes touching tenant RBAC or the Application REST layer should be reviewed against this invariant. @@ -101,7 +102,7 @@ If a future `ApplicationDefinition`, RBAC change, or API change ever let a tenan Cozystack has two admission enforcement points, and the distinction matters when reasoning about which policies protect which resources: - The **core kube-apiserver** evaluates ValidatingAdmissionPolicy for resources it serves directly — Namespaces, Gateways, HTTPRoutes/TLSRoutes/GRPCRoutes, Ingresses, and the no-delete guardrail. -- **`cozystack-api` itself** evaluates the admission chain (validating webhooks and ValidatingAdmissionPolicy) for aggregated `apps.cozystack.io` resources, because those are served by the aggregated API server and never reach the core apiserver's admission chain. The `cozystack-tenant-host-policy` on `apps.cozystack.io/tenants` is therefore enforced inside `cozystack-api`. +- **`cozystack-api` itself** evaluates the admission chain (validating webhooks and ValidatingAdmissionPolicy) for aggregated `apps.cozystack.io` resources, because those are served by the aggregated API server and never reach the core apiserver's admission chain. The `cozystack-tenant-host-policy` on `apps.cozystack.io/tenants` is therefore enforced inside `cozystack-api`. So is `cozystack-database-external-tls-policy`, which refuses a `redises` object that asks for a plaintext endpoint outside the cluster: `external: true` without `tls.enabled: true` on create, any update that turns external access on, since an existing instance's spec does not prove its TLS state, and any change of `tls.enabled` by a tenant while external access stays on (the callers trusted by `cozystack-tenant-host-policy` are exempt, to repair such an instance), since before the first reconcile nothing else stops TLS being dropped. A release already external and plaintext before the policy existed stays editable. Two hostname-policy details are worth stating precisely. The **HTTPRoute/TLSRoute/GRPCRoute** policies (`route-hostname-policy.yaml`) and the **legacy-Ingress** policy (`ingress-hostname-policy.yaml`) are fail-closed: a route or Ingress in a tenant namespace missing `namespace.cozystack.io/host` is denied, so an absent label cannot open those layers (the route policies also deny a route that declares no hostnames, since such a route inherits the hostnames of the listener it attaches to rather than matching nothing; the Ingress policy likewise denies hostless rules and `spec.defaultBackend`, and permits external custom domains outside the platform root apex). The **namespace host-label** policy is an immutability guard — it stops an untrusted caller from scrubbing or changing an already-set label, but it does not itself reject a namespace that never carried one. The **Gateway-listener** policy (`gateway-hostname-policy.yaml`) applies the same subdomain rule but its CEL short-circuits to allow when the host label is empty, so it is permissive (fail-open) for a tenant namespace that lacks the label. In normal operation the platform sets that label at tenant creation and the namespace host-label policy keeps it immutable, closing the gap in practice — but the Gateway-side guarantee is conditional on the label being present, not unconditional. @@ -114,7 +115,7 @@ The claims in this document can be re-verified against these sources: - Aggregated API server: `cmd/cozystack-api/`, `pkg/apiserver/apiserver.go`, `pkg/registry/apps/application/rest.go`, `pkg/config/config.go`. - Dynamic Application kinds: `pkg/cmd/server/start.go`, `api/v1alpha1/applicationdefinitions_types.go`, `internal/controller/applicationdefinition_controller.go`. - Tenant RBAC: `packages/system/cozystack-basics/templates/clusterroles.yaml`. -- Admission policies: `packages/system/cozystack-basics/templates/gateway-hostname-policy.yaml`, `route-hostname-policy.yaml`, `ingress-hostname-policy.yaml`, `packages/core/platform/templates/deletion-protection.yaml`. +- Admission policies: `packages/system/cozystack-basics/templates/gateway-hostname-policy.yaml`, `route-hostname-policy.yaml`, `ingress-hostname-policy.yaml`, `database-external-tls-policy.yaml`, `packages/core/platform/templates/deletion-protection.yaml`. - Tenant provisioning and isolation: `packages/apps/tenant/templates/` (`tenant.yaml`, `namespace.yaml`, `networkpolicy.yaml`), `pkg/registry/apps/application/quota.go`. - UI OIDC front door (oauth2-proxy): `packages/system/dashboard/templates/gatekeeper.yaml`, `packages/system/linstor-gui/templates/gatekeeper.yaml`. - Reporting and supported versions: `SECURITY.md`. diff --git a/docs/storage-immutability.md b/docs/storage-immutability.md deleted file mode 100644 index 35c03a515..000000000 --- a/docs/storage-immutability.md +++ /dev/null @@ -1,45 +0,0 @@ -# `storageClass` is immutable after creation - -Every stateful Cozystack application that exposes a `storageClass` parameter declares it immutable in the chart schema (`x-kubernetes-validations: [{rule: "self == oldSelf"}]`). This document explains the contract and where it is enforced. - -## Why - -`storageClass` binds the StatefulSet's PVC template. Kubernetes fixes `PersistentVolumeClaim.spec.storageClassName` at PVC creation time — editing `volumeClaimTemplates[].spec.storageClassName` on an existing StatefulSet does not retroactively migrate any data. A user who edits `storageClass` on an existing resource may believe their data is being moved to the new class; it is not. Locking the field at the schema layer makes that contract explicit. - -## What enforces it - -| Consumer | Behavior | -| --- | --- | -| Cozystack UI (`packages/system/dashboard/images/console`) | Reads the CEL rule from the chart's `openAPISchema` and renders `storageClass` as a disabled, helper-text-annotated field on edit forms. Save-time overlay reinstates the original value before PUT. | -| `kubectl edit` / `kubectl patch` against the cozystack aggregated apiserver | **Currently accepted** — the apiserver does not yet evaluate CEL rules embedded in `ApplicationDefinition.openAPISchema`. The change passes through but does not propagate to existing PVCs (see "Why" above), so no data corruption is possible. Apiserver enforcement is tracked in cozystack/cozystack#2657. | -| `kubectl edit` / `kubectl patch` against native CRDs | Enforced today by the standard apiextensions apiserver. | - -## Apps covered - -The following charts annotate at least one `storageClass` field as immutable: - -- `clickhouse`, `foundationdb`, `harbor`, `kafka` (Kafka broker + KRaft controller), `kubernetes`, `kubernetes-nodes`, `mariadb`, `mongodb`, `nats`, `openbao`, `opensearch`, `postgres`, `qdrant`, `rabbitmq`, `redis`, `valkey`, `vm-disk`. - -The `kubernetes-nodes` chart annotates both its per-pool `storageClass` (the worker node system-disk class, defaulted `replicated`) and its `cluster` field immutable. `storageClass` binds the same PVC-template contract as every other chart in the table, so the plain `self == oldSelf` rule applies for the reason in "Why" above. `cluster` is immutable for a different reason: it wires the pool's CAPI objects to one parent cluster `kubernetes-`, and repointing a live pool at another cluster would orphan its running worker VMs rather than migrate them. - -## `vm-disk` also freezes `source` - -The `vm-disk` chart annotates `source` immutable in addition to `storageClass`, for a mechanism distinct from the PVC-template reasoning above. A `vm-disk` renders a single `DataVolume`, and `DataVolume.spec` is immutable in CDI: once the DataVolume exists, editing `spec.source` (or `spec.storage.storageClassName`) has no effect. The chart therefore looks the existing DataVolume up and reuses its stored `spec`, so an edit to `.Values.source` would otherwise render as a silent no-op while the HelmRelease still reported success — the CR and the cluster diverge with no diagnostic (cozystack/cozystack#2985). - -Because the aggregated apiserver does not yet evaluate the CEL rule (see the table above, cozystack/cozystack#2657), `vm-disk` adds a second, chart-level guard that is the substantive enforcement today: `templates/dv.yaml` fails the render when the requested `storageClass` or `source` differs from what the disk was created with. Both checks compare the operator's input recorded in an annotation at creation — `vm-disk.cozystack.io/storage-class` and `vm-disk.cozystack.io/source` — written only at creation and preserved verbatim afterward, never overwritten with an unapplied edit. The storage-class annotation is written even for the cluster default (`""`), and its key presence — not its value — marks a recorded class, so a disk created with `""` is still caught if later changed to a concrete class. Recording the input rather than reading the live object matters on both axes: the image-clone PVC name carries a chart-version prefix (`vm-image-` was renamed to `vm-default-images-`) that drifts across upgrades with no operator edit, and the live PVC's `storageClassName` on an adopted or foreign DataVolume may legitimately differ from the CR's default without being a change. - -Disks created before these annotations existed (or out-of-band) are handled conservatively so a working release never deadlocks. For `source`, such a disk is compared against its stored `spec.source` directly, but only when that stored source is a shape the chart itself produces (`blank`, `http` with just a `url`, `upload`, or a `pvc` with just `name`/`namespace`). An adopted DataVolume using `spec.sourceRef`, or a source type the chart cannot render (`registry`, `snapshot`, `imageio`, `http` with a `secretRef`, a foreign-namespace `pvc`), has no comparable provenance and is left alone rather than failed on a mismatch. The image-clone exemption fires only when the stored source is a `cozy-public` `pvc` **and** the request is itself an image — the one case where the `vm-image-` → `vm-default-images-` prefix drift is indistinguishable from a real image-name change; a change away from an image source to another type is still caught. For `storageClass` there is no safe live fallback (the CR default need not reflect an adopted disk's real class), so an un-annotated disk is simply not guarded here; apiserver CEL (cozystack/cozystack#2657) is the eventual guard for those. To actually change `storageClass` or `source`, delete and recreate the disk; size growth is the one mutable dimension and is handled separately by `templates/pvc-resize-hook.yaml`. - -The `storageClass` annotation records the effective value applied at creation, including when it came from the chart's `values.yaml` default (`replicated`) rather than an explicit operator value. Applications created through the aggregated apiserver have the default stamped into the CR, so it stays stable; but a direct HelmRelease consumer that omits `storageClass` records the chart default of the day, so changing that default in a future chart version would make every such untouched release start failing the render until its CR pins the old value or the disk is recreated. Treat the `storageClass` default as a frozen contract for the same reason the `source` serialization above is. - -The `source` annotation is a byte-for-byte `toJson` of `.Values.source`, so it is coupled to the exact serialization of the source schema. Adding a subfield with a schema default (which the apiserver would stamp onto every CR) would make the recorded and requested JSON diverge on an untouched disk; such a change needs an annotation-migration story rather than a bare schema bump. - -If you add a new stateful chart that exposes `storageClass`, annotate it the same way: - -```yaml -## @param {string} storageClass - StorageClass used to store the data. -## @immutable -storageClass: "" -``` - -For fields declared inside a `@typedef`, place `## @immutable` on the line below the `## @field` it should attach to. diff --git a/docs/vm-external-vlan.md b/docs/vm-external-vlan.md deleted file mode 100644 index 1a7bad792..000000000 --- a/docs/vm-external-vlan.md +++ /dev/null @@ -1,155 +0,0 @@ -# Attaching a virtual machine to an external VLAN - -This document describes how to attach a Cozystack virtual machine (the `vm-instance` application) directly to an external, physically-routed VLAN — the layer-2 segment a VM needs when it must appear on the same broadcast domain as external hardware (a licensing appliance, a storage box, a gateway managed outside the cluster), with an address from that VLAN's subnet rather than from the cluster overlay. - -The default Cozystack VM networking is overlay-only (the pod network, plus optional KubeOVN VPC subnets). Bridging a VM onto a real VLAN is a different pattern and has one non-obvious constraint: **it works with a Linux bridge and the `bridge` CNI plugin, and it does not work with `macvlan`.** The rest of this guide explains why and gives a working recipe. - -## Why `bridge` and not `macvlan` - -KubeVirt attaches a VM interface to a secondary network using **bridge binding** by default (this is what the `vm-instance` chart emits for every network in `.spec.networks`). With bridge binding the guest's own MAC address is placed on the wire — the launcher pod does not masquerade or translate it. - -A `macvlan` attachment is incompatible with that model. `macvlan` demultiplexes inbound frames strictly by the MAC address of the macvlan child interface. Because KubeVirt puts the *guest's* MAC on the wire — not the macvlan child's — replies from the gateway or other hosts arrive at the parent interface addressed to the guest MAC, do not match any macvlan child, and are silently dropped before they ever reach the VM. The symptom is a guest that can transmit (ARP requests and pings leave, visible in `tcpdump` on the parent interface) but never receives a reply (its neighbor entry for the gateway stays `FAILED`). As a secondary consequence, the host cannot reach macvlan children through the parent interface either, so a host-side service on the parent IP is unreachable from the VMs. - -A **Linux bridge** does not have this limitation: it forwards by learned MAC on all bridged ports, so the guest MAC is reachable, and the host can carry an address on the bridge itself to talk to the VMs. Attach the VLAN sub-interface to a bridge and point a `bridge`-type NAD at it. - -## Overview - -Three pieces cooperate: - -1. A **Linux bridge on each node** that enslaves the tagged VLAN sub-interface. This is node-level networking — it is configured by your node provisioning (netplan / Talos machine config / systemd-networkd), not by a Cozystack chart. -2. A **`NetworkAttachmentDefinition`** of type `bridge` referencing that bridge, created in the VM's tenant namespace. -3. The **`vm-instance`** application referencing the NAD by name in `.networks`, with the guest's static address supplied through cloud-init. - -## Prerequisites - -- The `multus` package is enabled (it provides the `NetworkAttachmentDefinition` CRD and the secondary-network plumbing). -- The `bridge` CNI plugin is present in `/opt/cni/bin` on every node. The `multus` package puts it there itself on every platform, which is the subject of the next section — read it before upgrading a cluster whose `/opt/cni/bin` you provision yourself. Verify with `ls /opt/cni/bin/bridge`; a missing binary makes the NAD fail with `failed to find plugin "bridge" in path [/opt/cni/bin]`. -- There is no IPAM plugin in this path — addresses are assigned inside the guest, not by the CNI. Plan static addresses per VM. - -## Staging the reference CNI plugins - -The `multus` package installs the reference plugins into `/opt/cni/bin` itself, on every platform, because no platform supplies all of them. That is the `stageCniPlugins` chart value, and the platform turns it on for every bundle. What differs is only how much is missing before staging runs. Talos puts six binaries in that directory — `bridge`, `firewall`, `host-local`, `loopback` and `portmap` from the same upstream release, plus `flannel`, which is a different project — so a NAD naming `macvlan`, `ipvlan` or `vlan` fails there too; staging adds the ten it does not carry and rewrites the four that overlap with the same upstream version (`v1.9.1` on both sides), not an older one. Generic Linux offers no guarantee at all — k3s keeps its own copies under `/var/lib/rancher/k3s/data/cni` (`/var/lib/rancher/k3s/data/current/bin` on releases older than October 2024) and Cilium installs only `cilium-cni` and `loopback`, so `/opt/cni/bin` there can lack even `bridge`. - -Carrying the plugins costs roughly 67 MiB uncompressed per architecture in the `multus` image, which every node pulls whether staging is on or off. Size airgap mirrors accordingly. - -Where staging is on, it tries to replace any file of the same name already in that directory, every time the Multus pod is recreated, so a hand-placed or locally patched `bridge` will normally not survive — carry such a change in the `multus` image instead. A plugin it fails to write is reported and skipped rather than removed, so whatever was there stays — an older copy where the node had one, and nothing at all where it did not. It installs 14 of the upstream reference plugins and leaves `loopback`, `dhcp`, `dummy` and `tap` alone. Leaving them alone is not a promise that something else provides them: `loopback` is installed by Cilium and kube-ovn, while `dhcp`, `dummy` and `tap` are simply not staged — `dhcp` needs a host daemon this package does not run, and the other two have no consumer here. If you need one of those, put it on the node yourself. - -**If you provision `/opt/cni/bin` yourself, set the opt-out before upgrading.** The replacement happens as soon as Multus rolls, and turning `stageCniPlugins` off afterwards does not undo it: nothing in this package removes or restores a plugin, so the copies stay until you re-provision the node. Operators pinned to a particular plugin version should decline first and upgrade second. This applies on Talos too, where four of the names staging writes are ones the node image also carries. Declining looks like this, on the `platform` component of the `cozystack.cozystack-platform` Package CR: - -```yaml -apiVersion: cozystack.io/v1alpha1 -kind: Package -metadata: - name: cozystack.cozystack-platform -spec: - components: - platform: - values: - networking: - stageCniPlugins: false -``` - -Editing the multus HelmRelease or the child `Package cozystack.multus` directly does not hold: both are re-rendered by the platform reconcile. An unreadable value there — a spelling that is neither a `true` nor a `false` form — stops the whole platform render rather than resolving to off, so a typo in this key halts reconciliation cluster-wide. - -If `bridge` is missing on a node where staging is on, read the log with `kubectl --namespace cozy-multus logs --container install-cni-plugins`. The line `no /cni-plugins in this image; skipping staging` means the running `multus` image predates the plugin staging and installed nothing: the image reference and the manifest are re-pinned on different schedules, so a tree taken between a Dockerfile change and the next release bake can carry one without the other. Move to a release whose `multus` image carries the plugins. A line beginning `failed to install:` names plugins the container could not write, one of which may be the `bridge` you are looking for. The reason for each is earlier in the same log, printed as that plugin was attempted rather than next to the summary — so with more than one failure the causes are spread above it, not adjacent to it, and the one naming your plugin is the one to read. The container reports these and exits successfully on purpose, so the pod shows Ready and `kubectl get` will not point you here: failing it instead would leave the node unable to start any pod that goes through CNI, since Multus remains the primary CNI with no daemon behind it — host-network pods bypass CNI and still start. That means a NAD failing with `failed to find plugin` is the symptom to trust, and this log is where the reason is. - -If the init container is absent from the Multus pod altogether, staging is off for this cluster. That means `networking.stageCniPlugins` was set to `false` somewhere: no bundle defaults it off, on Talos or anywhere else. Turn it back on with the same block as above and `true` in place of `false`, or stage the plugins through node provisioning instead. - -Changing this value edits the Multus DaemonSet's pod template, so Multus rolls node by node. While a node's `multus-daemon` is down its CNI shim has no daemon behind it, and pod creation and deletion on that node fail for the length of the restart. Flip it during a window where that is acceptable, not while something else is rolling. - -## Step 1 — Linux bridge on the node - -Create a bridge that enslaves the tagged VLAN sub-interface. The VLAN sub-interface itself carries no address; the bridge carries the host's presence on that VLAN (optional, but useful for a gateway-reachability sanity path and for any host-side service the VMs must reach). - -This example uses netplan on an Ubuntu/Debian node; the VLAN id and subnet are illustrative (`203.0.113.0/24`, VLAN 100, gateway `203.0.113.1`). Adapt to your uplink naming and to Talos/`systemd-networkd` if that is your provisioning: - -```yaml -network: - version: 2 - vlans: - # Tagged VLAN sub-interface, no address of its own — enslaved to the bridge. - uplink.100: - id: 100 - link: uplink - bridges: - br100: - interfaces: - - uplink.100 - # Optional host presence on the VLAN. Keep the node's default route on - # its management interface — do not add a default route here. - addresses: - - 203.0.113.2/24 -``` - -Notes: - -- The node's **default route must stay on the management interface.** The bridge address (if any) is only for on-VLAN reachability, not a second default gateway. -- `netplan apply` cannot move an interface into a bridge while a consumer still holds it (for example a `virt-launcher` pod using a previous `macvlan` attachment). Remove the consumer first (delete the VMI so the launcher releases the interface), then reconfigure. -- After a reboot, `systemd-networkd` may briefly report the bridge "routable" while the link is not yet actually up. If your VMs need the VLAN immediately at boot, gate their start on a reachability check, or re-run `netplan apply` until the gateway answers. - -## Step 2 — NetworkAttachmentDefinition - -Create a `bridge`-type NAD in the tenant namespace that will host the VM. The `vm-instance` chart resolves a network by name **in the VM's own namespace**, so one copy of the NAD must exist in every tenant namespace that runs VMs on this VLAN. - -```yaml -apiVersion: k8s.cni.cncf.io/v1 -kind: NetworkAttachmentDefinition -metadata: - name: vlan100 - namespace: tenant-example -spec: - config: | - { - "cniVersion": "0.3.1", - "type": "bridge", - "bridge": "br100", - "ipam": {} - } -``` - -- `bridge` must match the bridge name from step 1 (`br100` here). -- `ipam: {}` — no cluster-side address assignment; the guest configures its address itself (step 3). - -## Step 3 — Attach the VM and assign a static address - -Reference the NAD by name in the `vm-instance` values. Because the chart does not support `networkData`, the static address goes into cloud-init `userData` (`cloudInit`), written by the guest at first boot: - -```yaml -# vm-instance values -instanceType: u1.medium -instanceProfile: ubuntu -disks: - - name: example-system -networks: - - name: vlan100 -cloudInit: | - #cloud-config - write_files: - - path: /etc/netplan/60-vlan100.yaml - permissions: "0600" - content: | - network: - version: 2 - ethernets: - # Match the second NIC (the pod-network NIC is the first). Use the - # interface that comes up without a DHCP lease. - enp2s0: - addresses: - - 203.0.113.10/24 - runcmd: - - netplan apply -``` - -The VM ends up with two interfaces: the always-present **pod-network** NIC (`default`, used for cluster-internal traffic and for the `vm-instance` external-access features) and the **VLAN** NIC. The `/24` address above brings up only the connected route for the VLAN subnet — it adds no default route, so the guest's egress stays wherever you want it (typically the pod NIC). If the VLAN is meant to be the guest's default gateway instead, add a default route under the VLAN NIC and remove it from the pod NIC. - -## Gotchas - -- **VMs are dual-homed.** The `vm-instance` chart always adds the pod-network NIC in addition to any `networks` you declare; there is no single-homed (VLAN-only) option today. Address the VLAN NIC inside the guest and leave the pod NIC to the cluster. -- **No `networkData`.** The chart wires cloud-init through `userData` only, so in-guest static configuration (netplan `write_files` + `netplan apply`, as above) is the way to assign the VLAN address. -- **MAC changes on VM re-creation.** KubeVirt generates a fresh guest MAC each time the VM object is re-created, and `vm-instance` exposes no way to pin it, so re-creating a VM changes its MAC. The upstream gateway then holds a stale ARP entry for the old MAC for a few minutes, so "gateway unreachable" immediately after re-creating a VM is expected — wait for the ARP entry to age out (~5 min) rather than treating it as a fault. -- **Host ↔ VM traffic.** If the host must talk to the VMs (a proxy, a health check), give the bridge a host address on the VLAN (step 1) — traffic through a bare VLAN sub-interface to bridge-attached guests will not work the way `macvlan` users expect. - -## See also - -- [`docs/gpu-vgpu.md`](./gpu-vgpu.md) — passing NVIDIA GPUs and vGPU profiles into the same VMs. -- KubeVirt user guide, [Interfaces and Networks](https://kubevirt.io/user-guide/network/interfaces_and_networks/) — bridge binding vs other binding methods. diff --git a/examples/backups/_lib/wait-helpers.sh b/examples/backups/_lib/wait-helpers.sh new file mode 100644 index 000000000..cec241d13 --- /dev/null +++ b/examples/backups/_lib/wait-helpers.sh @@ -0,0 +1,165 @@ +#!/bin/bash +# Wait helpers shared by every backup walkthrough under examples/backups/. +# Each walkthrough's 00-helpers.sh sources this file after defining the log_* +# functions these call; wait_hr_ready and wait_deleted read $NAMESPACE. +# hack/backup-examples-shared-helpers.bats fails if a walkthrough grows its own +# copy again. + +# Wait until a JSONPath value on a resource matches the desired string. +# +# The optional 7th argument is a TERMINAL value to bail on: a BackupJob or +# RestoreJob that reaches Failed never reaches Succeeded, so polling out the +# remaining budget only delays the report, lets the TTL reaper take the Job's +# Pod log, and under Chainsaw risks the step being SIGKILLed at its op timeout +# instead of failing cleanly. +# +# kubectl's stderr is left attached: a read that fails for RBAC or transport +# reasons says so instead of reading as an empty value. --ignore-not-found +# keeps a resource that does not exist yet, the usual case at the start of a +# wait, from printing an error on every poll. +wait_for_field() { + local resource_type="$1" + local resource_name="$2" + local jsonpath="$3" + local desired="$4" + local namespace="${5:-}" + local timeout="${6:-300}" + local fail_value="${7:-}" + + log_substep "Waiting for $resource_type/$resource_name $jsonpath to become '$desired'..." + local elapsed=0 + local ns_flag=() + [[ -n "$namespace" ]] && ns_flag=(-n "$namespace") + + while true; do + local current + current=$(kubectl get "$resource_type" "$resource_name" "${ns_flag[@]}" --ignore-not-found -o jsonpath="$jsonpath" || true) + if [[ "$current" == "$desired" ]]; then + log_success "$resource_type/$resource_name reached '$desired'" + return 0 + fi + if [[ -n "$fail_value" && "$current" == "$fail_value" ]]; then + log_error "$resource_type/$resource_name reached terminal '$current' (expected '$desired')" + return 1 + fi + if [[ $elapsed -ge $timeout ]]; then + log_error "Timeout waiting for $resource_type/$resource_name (current: '$current', expected: '$desired')" + return 1 + fi + sleep 5 + elapsed=$((elapsed + 5)) + done +} + +# Wait for a HelmRelease to become Ready, with an existence backstop (the apps +# controller creates the HR asynchronously, so a bare `kubectl wait` right after +# `kubectl apply` races it) and a fail-fast on Stalled=True: a stalled HR has +# exhausted its remediation retries and will never turn Ready, so polling to the +# timeout only hides the real error. +wait_hr_ready() { + local name="$1" + local timeout="${2:-300}" + local elapsed=0 + local lookup state seen=0 + + log_substep "Waiting for HelmRelease/$name to become Ready..." + while true; do + # --ignore-not-found makes an absent release exit 0, so a non-zero exit + # is kubectl failing to answer. Presence is read off the name line, + # because a warning on stderr lands in the same string. + if ! lookup=$(kubectl -n "$NAMESPACE" get hr "$name" --ignore-not-found -o name 2>&1); then + state=error + elif [[ $'\n'"$lookup"$'\n' != *"/$name"$'\n'* ]]; then + state=absent + else + state=present + seen=1 + local ready stalled + ready=$(kubectl -n "$NAMESPACE" get hr "$name" \ + -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}' || true) + if [[ "$ready" == "True" ]]; then + log_success "HelmRelease/$name is Ready" + return 0 + fi + stalled=$(kubectl -n "$NAMESPACE" get hr "$name" \ + -o jsonpath='{.status.conditions[?(@.type=="Stalled")].status}' || true) + if [[ "$stalled" == "True" ]]; then + log_error "HelmRelease/$name is Stalled (terminal):" + break + fi + fi + if [[ $elapsed -ge $timeout ]]; then + log_error "Timeout waiting for HelmRelease/$name to become Ready:" + case "$state" in + error) + echo " could not look up HelmRelease/$name: $lookup" >&2 + # Seen earlier: the reads below may answer where this lookup + # did not. + [[ $seen -eq 1 ]] || return 1 + ;; + absent) + if [[ $seen -eq 1 ]]; then + echo " HelmRelease/$name was deleted from $NAMESPACE while waiting" >&2 + else + echo " HelmRelease/$name never appeared in $NAMESPACE" >&2 + fi + return 1 + ;; + esac + break + fi + sleep 5 + elapsed=$((elapsed + 5)) + done + # Reached on Stalled or on timeout. Conditions and history rather than the + # Ready message alone: a failed install is retried on an interval, so Ready + # may describe the retry rather than the failure behind it. + kubectl -n "$NAMESPACE" get hr "$name" \ + -o jsonpath='{range .status.conditions[*]} {.type}={.status} ({.reason}): {.message}{"\n"}{end}' >&2 || true + local hist + if ! hist=$(kubectl -n "$NAMESPACE" get hr "$name" \ + -o jsonpath='{range .status.history[*]} history: {.status} {.chartVersion} {.lastDeployed}{"\n"}{end}'); then + echo " history: kubectl could not read it" >&2 + elif [[ -n "${hist//[[:space:]]/}" ]]; then + printf '%s\n' "$hist" >&2 + else + # A release with no history prints nothing and exits 0; say so, + # because a blank in a failure dump reads as a dump that broke. + echo " history: (none recorded)" >&2 + fi + return 1 +} + +# Wait until a namespaced resource is really gone. +# +# `kubectl wait --for=delete` is not used: it errors out when the resource is +# already absent, which is the normal case on a clean namespace (cleanup.sh is +# idempotent and runs as a pre-clean too), and swallowing that error would also +# swallow a genuine failure. Polling `get --ignore-not-found` treats "already +# gone" and "gone now" as the same success (empty output, exit 0) while a +# retrieval failure — RBAC, API-server, transport — is a non-zero exit that +# must NOT be read as deletion, or cleanup settles on a false success and leaves +# half-uninstalled resources for the next run. Such an error just keeps us +# polling until the resource is confirmed gone or the timeout fires. +wait_deleted() { + local resource_type="$1" + local resource_name="$2" + local timeout="${3:-300}" + local elapsed=0 + local got + + while true; do + if got=$(kubectl -n "$NAMESPACE" get "$resource_type" "$resource_name" --ignore-not-found 2>/dev/null) && [[ -z "$got" ]]; then + [[ $elapsed -gt 0 ]] && log_success "$resource_type/$resource_name is gone" + return 0 + fi + if [[ $elapsed -ge $timeout ]]; then + log_error "Timeout waiting for $resource_type/$resource_name to be deleted; it is still present after ${timeout}s:" + kubectl -n "$NAMESPACE" get "$resource_type" "$resource_name" -o wide >&2 || true + return 1 + fi + [[ $elapsed -eq 0 ]] && log_substep "Waiting for $resource_type/$resource_name to be deleted..." + sleep 5 + elapsed=$((elapsed + 5)) + done +} diff --git a/examples/backups/clickhouse/00-helpers.sh b/examples/backups/clickhouse/00-helpers.sh index a4e5c19c4..d3d56b034 100755 --- a/examples/backups/clickhouse/00-helpers.sh +++ b/examples/backups/clickhouse/00-helpers.sh @@ -79,128 +79,10 @@ print_header() { echo -e "\n${MAGENTA}${BOLD}== $title ==${NC}\n" >&2 } -# Wait until a JSONPath value on a resource matches the desired string. -# -# The optional 7th argument is a TERMINAL value to bail on: a BackupJob or -# RestoreJob that reaches Failed will never reach Succeeded, so polling out the -# remaining budget only delays the report and — when this runs under Chainsaw — -# risks the step being SIGKILLed at its op timeout with nothing collected -# instead of failing cleanly. Same contract as the postgres/mariadb helpers. -wait_for_field() { - local resource_type="$1" - local resource_name="$2" - local jsonpath="$3" - local desired="$4" - local namespace="${5:-}" - local timeout="${6:-300}" - local fail_value="${7:-}" - - log_substep "Waiting for $resource_type/$resource_name $jsonpath to become '$desired'..." - local elapsed=0 - local ns_flag=() - [[ -n "$namespace" ]] && ns_flag=(-n "$namespace") - - while true; do - local current - current=$(kubectl get "$resource_type" "$resource_name" "${ns_flag[@]}" -o jsonpath="$jsonpath" 2>/dev/null || true) - if [[ "$current" == "$desired" ]]; then - log_success "$resource_type/$resource_name reached '$desired'" - return 0 - fi - if [[ -n "$fail_value" && "$current" == "$fail_value" ]]; then - log_error "$resource_type/$resource_name reached terminal '$current' (expected '$desired')" - return 1 - fi - if [[ $elapsed -ge $timeout ]]; then - log_error "Timeout waiting for $resource_type/$resource_name (current: '$current', expected: '$desired')" - return 1 - fi - sleep 5 - elapsed=$((elapsed + 5)) - done -} - -# Wait for a HelmRelease to become Ready, failing fast on Stalled=True. -# -# `kubectl wait hr ... --for=condition=ready` cannot do either half of this: it -# errors out if the HelmRelease does not exist yet (the app CR is reconciled -# asynchronously, so the HR appears a moment after `kubectl apply` returns), and -# it keeps waiting through a terminal Stalled — a chart that will never install -# burns the whole timeout instead of reporting the reason. Same contract as the -# postgres/mariadb helpers. -wait_hr_ready() { - local name="$1" - local timeout="${2:-300}" - local elapsed=0 - local lookup state seen=0 - - log_substep "Waiting for HelmRelease/$name to become Ready..." - while true; do - # --ignore-not-found makes an absent release exit 0, so a non-zero exit - # is kubectl failing to answer. Presence is read off the name line, - # because a warning on stderr lands in the same string. - if ! lookup=$(kubectl -n "$NAMESPACE" get hr "$name" --ignore-not-found -o name 2>&1); then - state=error - elif [[ $'\n'"$lookup"$'\n' != *"/$name"$'\n'* ]]; then - state=absent - else - state=present - seen=1 - local ready stalled - ready=$(kubectl -n "$NAMESPACE" get hr "$name" \ - -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}' || true) - if [[ "$ready" == "True" ]]; then - log_success "HelmRelease/$name is Ready" - return 0 - fi - stalled=$(kubectl -n "$NAMESPACE" get hr "$name" \ - -o jsonpath='{.status.conditions[?(@.type=="Stalled")].status}' || true) - if [[ "$stalled" == "True" ]]; then - log_error "HelmRelease/$name is Stalled (terminal):" - break - fi - fi - if [[ $elapsed -ge $timeout ]]; then - log_error "Timeout waiting for HelmRelease/$name to become Ready:" - case "$state" in - error) - echo " could not look up HelmRelease/$name: $lookup" >&2 - # Seen earlier: the reads below may answer where this lookup - # did not. - [[ $seen -eq 1 ]] || return 1 - ;; - absent) - if [[ $seen -eq 1 ]]; then - echo " HelmRelease/$name was deleted from $NAMESPACE while waiting" >&2 - else - echo " HelmRelease/$name never appeared in $NAMESPACE" >&2 - fi - return 1 - ;; - esac - break - fi - sleep 5 - elapsed=$((elapsed + 5)) - done - # Reached on Stalled or on timeout. Conditions and history rather than the - # Ready message alone: a failed install is retried on an interval, so Ready - # may describe the retry rather than the failure behind it. - kubectl -n "$NAMESPACE" get hr "$name" \ - -o jsonpath='{range .status.conditions[*]} {.type}={.status} ({.reason}): {.message}{"\n"}{end}' >&2 || true - local hist - if ! hist=$(kubectl -n "$NAMESPACE" get hr "$name" \ - -o jsonpath='{range .status.history[*]} history: {.status} {.chartVersion} {.lastDeployed}{"\n"}{end}'); then - echo " history: kubectl could not read it" >&2 - elif [[ -n "${hist//[[:space:]]/}" ]]; then - printf '%s\n' "$hist" >&2 - else - # A release with no history prints nothing and exits 0; say so, - # because a blank in a failure dump reads as a dump that broke. - echo " history: (none recorded)" >&2 - fi - return 1 -} +# wait_for_field, wait_hr_ready and wait_deleted live in one file shared by +# every backup walkthrough, so a fix to one reaches all of them. +# shellcheck source-path=SCRIPTDIR source=../_lib/wait-helpers.sh +source "$(dirname "${BASH_SOURCE[0]}")/../_lib/wait-helpers.sh" # Wait for a StatefulSet to report a ready replica, tolerating its asynchronous # creation (the ClickHouse operator creates it after the CHI is reconciled). @@ -237,40 +119,6 @@ wait_sts_ready() { done } -# Wait until a namespaced resource is really gone. -# -# `kubectl wait --for=delete` is not used: it errors out when the resource is -# already absent, which is the normal case on a clean namespace (cleanup.sh is -# idempotent and runs as a pre-clean too), and swallowing that error would also -# swallow a genuine failure. Polling `get --ignore-not-found` treats "already -# gone" and "gone now" as the same success (empty output, exit 0) while a -# retrieval failure — RBAC, API-server, transport — is a non-zero exit that -# must NOT be read as deletion, or cleanup settles on a false success and leaves -# half-uninstalled resources for the next run. Such an error just keeps us -# polling until the resource is confirmed gone or the timeout fires. -wait_deleted() { - local resource_type="$1" - local resource_name="$2" - local timeout="${3:-300}" - local elapsed=0 - local got - - while true; do - if got=$(kubectl -n "$NAMESPACE" get "$resource_type" "$resource_name" --ignore-not-found 2>/dev/null) && [[ -z "$got" ]]; then - [[ $elapsed -gt 0 ]] && log_success "$resource_type/$resource_name is gone" - return 0 - fi - if [[ $elapsed -ge $timeout ]]; then - log_error "Timeout waiting for $resource_type/$resource_name to be deleted; it is still present after ${timeout}s:" - kubectl -n "$NAMESPACE" get "$resource_type" "$resource_name" -o wide >&2 || true - return 1 - fi - [[ $elapsed -eq 0 ]] && log_substep "Waiting for $resource_type/$resource_name to be deleted..." - sleep 5 - elapsed=$((elapsed + 5)) - done -} - # Run a SQL statement against the ClickHouse cluster of the given app instance. # Args: # Note: the Cozystack ClickHouse RD prefixes Helm release names with diff --git a/examples/backups/clickhouse/03-create-bucket.sh b/examples/backups/clickhouse/03-create-bucket.sh index 826287e9c..f2828a416 100755 --- a/examples/backups/clickhouse/03-create-bucket.sh +++ b/examples/backups/clickhouse/03-create-bucket.sh @@ -27,7 +27,9 @@ spec: EOF log_substep "Waiting for bucket HelmRelease to be Ready..." -wait_hr_ready "bucket-${BUCKET_NAME}" 300 +# 660s, above this generated release's 600s install timeout; see "Sizing an +# HR-Ready budget" in docs/agents/e2e-testing.md. +wait_hr_ready "bucket-${BUCKET_NAME}" 660 kubectl -n "$NAMESPACE" wait bucketclaims.objectstorage.k8s.io "bucket-${BUCKET_NAME}" --for=jsonpath='{.status.bucketReady}'=true --timeout=180s # Cozystack's bucket app provisions a BucketAccess named "-backup" # (the "-backup" suffix is the BucketAccessClass name); the BucketInfo Secret diff --git a/examples/backups/clickhouse/README.md b/examples/backups/clickhouse/README.md index 3b9fc0d3e..1d392df5d 100644 --- a/examples/backups/clickhouse/README.md +++ b/examples/backups/clickhouse/README.md @@ -6,7 +6,7 @@ > `backup.enabled: true` and `backup.useSystemBucket: true` on the > ClickHouse release; tenants do not provision a Bucket or supply S3 > credentials. See -> [Backup Classes](../../../docs/operations/backup-classes.md) +> [Backup Classes](https://cozystack.io/docs/v1/operations/services/backup-classes/) > for the supported BackupJob / Plan flow against `cozy-default`. The > walk-through below covers the **legacy** path that wires a per-app > Bucket, custom strategy CR, and bespoke BackupClass — useful when an diff --git a/examples/backups/etcd/00-helpers.sh b/examples/backups/etcd/00-helpers.sh index 6ea958606..f1f095944 100755 --- a/examples/backups/etcd/00-helpers.sh +++ b/examples/backups/etcd/00-helpers.sh @@ -43,46 +43,10 @@ print_header() { echo -e "\n${MAGENTA}${BOLD}== $title ==${NC}\n" >&2 } -# Wait until a JSONPath value on a resource matches the desired string. -# Optional 7th arg is a TERMINAL failure value: once the field reaches it the -# wait returns 1 immediately instead of polling to the timeout. BackupJob and -# RestoreJob settle on a terminal phase=Failed that never becomes Succeeded, so -# waiting the full timeout only wastes wall-clock AND risks the snapshot Job's -# Pod being TTL-reaped (TTLSecondsAfterFinished=600s) before diagnostics can read -# its log. Failing fast on the terminal phase keeps that log in reach. -wait_for_field() { - local resource_type="$1" - local resource_name="$2" - local jsonpath="$3" - local desired="$4" - local namespace="${5:-}" - local timeout="${6:-300}" - local fail_value="${7:-}" - - log_substep "Waiting for $resource_type/$resource_name $jsonpath to become '$desired'..." - local elapsed=0 - local ns_flag=() - [[ -n "$namespace" ]] && ns_flag=(-n "$namespace") - - while true; do - local current - current=$(kubectl get "$resource_type" "$resource_name" "${ns_flag[@]}" -o jsonpath="$jsonpath" 2>/dev/null || true) - if [[ "$current" == "$desired" ]]; then - log_success "$resource_type/$resource_name reached '$desired'" - return 0 - fi - if [[ -n "$fail_value" && "$current" == "$fail_value" ]]; then - log_error "$resource_type/$resource_name reached terminal '$current' (expected '$desired')" - return 1 - fi - if [[ $elapsed -ge $timeout ]]; then - log_error "Timeout waiting for $resource_type/$resource_name (current: '$current', expected: '$desired')" - return 1 - fi - sleep 5 - elapsed=$((elapsed + 5)) - done -} +# wait_for_field, wait_hr_ready and wait_deleted live in one file shared by +# every backup walkthrough, so a fix to one reaches all of them. +# shellcheck source-path=SCRIPTDIR source=../_lib/wait-helpers.sh +source "$(dirname "${BASH_SOURCE[0]}")/../_lib/wait-helpers.sh" # Ephemeral etcdctl pod name. Created on first etcdctl_exec call; reused # for subsequent calls in the same script run. cleanup.sh removes it. diff --git a/examples/backups/etcd/README.md b/examples/backups/etcd/README.md index c0775cb0a..d2b7a7858 100644 --- a/examples/backups/etcd/README.md +++ b/examples/backups/etcd/README.md @@ -5,7 +5,7 @@ > the system bucket `cozy-backups`. Tenants reference `cozy-default` > directly from BackupJob / Plan / RestoreJob without provisioning a > Bucket or supplying S3 credentials. See -> [Backup Classes](../../../docs/operations/backup-classes.md). +> [Backup Classes](https://cozystack.io/docs/v1/operations/services/backup-classes/). > The walk-through below covers the **legacy** path that wires a > per-app Bucket and bespoke BackupClass — useful for tuned non-default > policies. diff --git a/examples/backups/foundationdb/00-helpers.sh b/examples/backups/foundationdb/00-helpers.sh index d7c3c204d..f2707f131 100755 --- a/examples/backups/foundationdb/00-helpers.sh +++ b/examples/backups/foundationdb/00-helpers.sh @@ -47,35 +47,10 @@ print_header() { echo -e "\n${MAGENTA}${BOLD}== $title ==${NC}\n" >&2 } -# Wait until a JSONPath value on a resource matches the desired string. -wait_for_field() { - local resource_type="$1" - local resource_name="$2" - local jsonpath="$3" - local desired="$4" - local namespace="${5:-}" - local timeout="${6:-300}" - - log_substep "Waiting for $resource_type/$resource_name $jsonpath to become '$desired'..." - local elapsed=0 - local ns_flag=() - [[ -n "$namespace" ]] && ns_flag=(-n "$namespace") - - while true; do - local current - current=$(kubectl get "$resource_type" "$resource_name" "${ns_flag[@]}" -o jsonpath="$jsonpath" 2>/dev/null || true) - if [[ "$current" == "$desired" ]]; then - log_success "$resource_type/$resource_name reached '$desired'" - return 0 - fi - if [[ $elapsed -ge $timeout ]]; then - log_error "Timeout waiting for $resource_type/$resource_name (current: '$current', expected: '$desired')" - return 1 - fi - sleep 5 - elapsed=$((elapsed + 5)) - done -} +# wait_for_field, wait_hr_ready and wait_deleted live in one file shared by +# every backup walkthrough, so a fix to one reaches all of them. +# shellcheck source-path=SCRIPTDIR source=../_lib/wait-helpers.sh +source "$(dirname "${BASH_SOURCE[0]}")/../_lib/wait-helpers.sh" # Run an fdbcli statement against a FoundationDB cluster of the given app # instance. Args: diff --git a/examples/backups/foundationdb/03-create-foundationdb-src.sh b/examples/backups/foundationdb/03-create-foundationdb-src.sh index 6eaafc1a3..41068762f 100755 --- a/examples/backups/foundationdb/03-create-foundationdb-src.sh +++ b/examples/backups/foundationdb/03-create-foundationdb-src.sh @@ -19,8 +19,8 @@ metadata: name: ${FDB_NAME} namespace: ${NAMESPACE} spec: + version: v7.3 cluster: - version: "7.3.63" processCounts: storage: 1 stateless: -1 diff --git a/examples/backups/foundationdb/06-restore-to-copy.sh b/examples/backups/foundationdb/06-restore-to-copy.sh index 9a2b9819c..8709912ca 100755 --- a/examples/backups/foundationdb/06-restore-to-copy.sh +++ b/examples/backups/foundationdb/06-restore-to-copy.sh @@ -20,8 +20,8 @@ metadata: name: ${FDB_RESTORE_NAME} namespace: ${NAMESPACE} spec: + version: v7.3 cluster: - version: "7.3.63" processCounts: storage: 1 stateless: -1 diff --git a/examples/backups/kafka-metadata/00-helpers.sh b/examples/backups/kafka-metadata/00-helpers.sh index eb40dbb61..08a44b8bc 100755 --- a/examples/backups/kafka-metadata/00-helpers.sh +++ b/examples/backups/kafka-metadata/00-helpers.sh @@ -63,7 +63,7 @@ export CA_MOUNT_DIR="${CA_MOUNT_DIR:-/etc/ssl/kafka-backup-ca}" # the target broker's own image at reconcile time and renders it as the # strategy's .ClientImage. Override this only to match your operator's image if # the CLI it carries differs. -export KAFKA_IMAGE="${KAFKA_IMAGE:-quay.io/strimzi/kafka:0.45.1-rc1-kafka-3.9.1@sha256:ba52ed046b1dccdbd96f4e68057ce014d862a7c9c1fc670760c023b9aa09f23f}" +export KAFKA_IMAGE="${KAFKA_IMAGE:-quay.io/strimzi/kafka:1.2.0-kafka-4.3.1@sha256:fef34b5438e8556cc08c01f3e254e47346f061b53a4e38d4289853777e0ea7f1}" export KAFKA_BIN="${KAFKA_BIN:-/opt/kafka/bin}" # Name of that long-lived CLI Pod; cleanup.sh removes it. export KAFKA_CLI_POD="${KAFKA_CLI_POD:-kafka-cli}" @@ -134,65 +134,10 @@ provision_demo_strategy() { kubectl apply -f "$SCRIPT_DIR/03-backupclass.yaml" >&2 } -# Wait until a JSONPath value on a resource matches the desired string. Optional -# 7th arg is a TERMINAL failure value: once the field reaches it the wait returns -# 1 immediately instead of polling to the timeout. -wait_for_field() { - local resource_type="$1" resource_name="$2" jsonpath="$3" desired="$4" - local namespace="${5:-}" timeout="${6:-300}" fail_value="${7:-}" - - log_substep "Waiting for $resource_type/$resource_name $jsonpath to become '$desired'..." - local elapsed=0 - local ns_flag=() - [[ -n "$namespace" ]] && ns_flag=(-n "$namespace") - - while true; do - local current - current=$(kubectl get "$resource_type" "$resource_name" "${ns_flag[@]}" -o jsonpath="$jsonpath" 2>/dev/null || true) - if [[ "$current" == "$desired" ]]; then - log_success "$resource_type/$resource_name reached '$desired'" - return 0 - fi - if [[ -n "$fail_value" && "$current" == "$fail_value" ]]; then - log_error "$resource_type/$resource_name reached terminal '$current' (expected '$desired')" - return 1 - fi - if [[ $elapsed -ge $timeout ]]; then - log_error "Timeout waiting for $resource_type/$resource_name (current: '$current', expected: '$desired')" - return 1 - fi - sleep 5 - elapsed=$((elapsed + 5)) - done -} - -# Wait for a HelmRelease to become Ready, with an existence backstop and a -# fail-fast on Stalled=True. -wait_hr_ready() { - local name="$1" timeout="${2:-300}" elapsed=0 - log_substep "Waiting for HelmRelease/$name to become Ready..." - while true; do - if kubectl -n "$NAMESPACE" get hr "$name" >/dev/null 2>&1; then - local ready stalled - ready=$(kubectl -n "$NAMESPACE" get hr "$name" -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}' 2>/dev/null || true) - if [[ "$ready" == "True" ]]; then - log_success "HelmRelease/$name is Ready" - return 0 - fi - stalled=$(kubectl -n "$NAMESPACE" get hr "$name" -o jsonpath='{.status.conditions[?(@.type=="Stalled")].status}' 2>/dev/null || true) - if [[ "$stalled" == "True" ]]; then - log_error "HelmRelease/$name is Stalled: $(kubectl -n "$NAMESPACE" get hr "$name" -o jsonpath='{.status.conditions[?(@.type=="Ready")].message}' 2>/dev/null)" - return 1 - fi - fi - if [[ $elapsed -ge $timeout ]]; then - log_error "Timeout waiting for HelmRelease/$name to become Ready" - return 1 - fi - sleep 5 - elapsed=$((elapsed + 5)) - done -} +# wait_for_field, wait_hr_ready and wait_deleted live in one file shared by +# every backup walkthrough, so a fix to one reaches all of them. +# shellcheck source-path=SCRIPTDIR source=../_lib/wait-helpers.sh +source "$(dirname "${BASH_SOURCE[0]}")/../_lib/wait-helpers.sh" # Wait until the Strimzi Kafka cluster kafka- reports Ready=True — the same # precondition the driver gates on. @@ -205,21 +150,36 @@ kafka_wait_ready() { # Ensure the long-lived kafka-cli Pod exists and is Ready, so kafka_run can exec # into it. Idempotent: a Ready Pod this demo owns is reused across calls and # across the numbered demo scripts; a leftover in a terminal phase (Succeeded / -# Failed) is replaced rather than waited on; and a same-named Pod this demo does -# not own is refused rather than hijacked or deleted. cleanup.sh removes it. +# Failed) is replaced rather than waited on, and so is one started before the +# Pod ran under the restricted profile, since a Pod's securityContext cannot be +# changed in place; and a same-named Pod this demo does not own is refused +# rather than hijacked or deleted. cleanup.sh removes it. +# Every step returns on failure explicitly: this runs as the left side of +# `|| return 1`, and some callers also wrap it in $(...), so errexit never +# applies inside it and a bare failure would carry on to the next step. kafka_cli_pod() { - local phase owner - phase=$(kubectl -n "$NAMESPACE" get pod "$KAFKA_CLI_POD" -o jsonpath='{.status.phase}' 2>/dev/null || true) - owner=$(kubectl -n "$NAMESPACE" get pod "$KAFKA_CLI_POD" -o jsonpath='{.metadata.labels.cozystack\.io/backup-demo}' 2>/dev/null || true) + local phase owner nonroot overrides + phase=$(kubectl -n "$NAMESPACE" get pod "$KAFKA_CLI_POD" --ignore-not-found -o jsonpath='{.status.phase}') || return 1 + owner=$(kubectl -n "$NAMESPACE" get pod "$KAFKA_CLI_POD" --ignore-not-found -o jsonpath='{.metadata.labels.cozystack\.io/backup-demo}') || return 1 if [ -n "$phase" ] && [ "$owner" != "kafka-metadata" ]; then log_error "Pod $NAMESPACE/$KAFKA_CLI_POD exists but this demo does not own it; refusing to use or delete it" return 1 fi - if [ "$phase" != "Running" ] && [ "$phase" != "Pending" ]; then - kubectl -n "$NAMESPACE" delete pod "$KAFKA_CLI_POD" --grace-period=1 --ignore-not-found >/dev/null + # Only this helper creates the Pod, and it sets every restricted field at + # once, so one of them tells a current Pod from an older one. + nonroot=$(kubectl -n "$NAMESPACE" get pod "$KAFKA_CLI_POD" --ignore-not-found -o jsonpath='{.spec.securityContext.runAsNonRoot}') || return 1 + if { [ "$phase" != "Running" ] && [ "$phase" != "Pending" ]; } || [ "$nonroot" != "true" ]; then + # The Strimzi image runs as non-root UID 1001, so runAsNonRoot and + # seccomp at the Pod level plus allowPrivilegeEscalation=false and + # drop-ALL on the container satisfy PSA "restricted" without pinning a + # runAsUser specific to this image tag. The add-only JSON patch leaves + # the run-generated Pod's image, command and args untouched. + overrides='[{"op":"add","path":"/spec/securityContext","value":{"runAsNonRoot":true,"seccompProfile":{"type":"RuntimeDefault"}}},{"op":"add","path":"/spec/containers/0/securityContext","value":{"allowPrivilegeEscalation":false,"capabilities":{"drop":["ALL"]}}}]' + kubectl -n "$NAMESPACE" delete pod "$KAFKA_CLI_POD" --grace-period=1 --ignore-not-found >/dev/null || return 1 kubectl -n "$NAMESPACE" run "$KAFKA_CLI_POD" --image="$KAFKA_IMAGE" \ --labels=cozystack.io/backup-demo=kafka-metadata \ - --restart=Never --command -- sleep infinity >/dev/null + --override-type=json --overrides="$overrides" \ + --restart=Never --command -- sleep infinity >/dev/null || return 1 fi kubectl -n "$NAMESPACE" wait --for=condition=Ready "pod/$KAFKA_CLI_POD" \ --timeout=5m >/dev/null @@ -240,7 +200,7 @@ kafka_run() { local app="$1"; shift local snippet="$1" local boot="kafka-${app}-kafka-bootstrap.${NAMESPACE}.svc:9092" - kafka_cli_pod + kafka_cli_pod || return 1 kubectl -n "$NAMESPACE" exec -i "$KAFKA_CLI_POD" -- bash -c "set -eu BOOT=$(printf %q "$boot") BIN=$(printf %q "$KAFKA_BIN") diff --git a/examples/backups/kafka-metadata/05-kafka-src.yaml b/examples/backups/kafka-metadata/05-kafka-src.yaml index 041a8dc26..b905e12c5 100644 --- a/examples/backups/kafka-metadata/05-kafka-src.yaml +++ b/examples/backups/kafka-metadata/05-kafka-src.yaml @@ -14,8 +14,4 @@ spec: replicas: 1 size: 2Gi resourcesPreset: "c1.small" - zookeeper: - replicas: 1 - size: 1Gi - resourcesPreset: "c1.small" topics: [] diff --git a/examples/backups/kafka-metadata/20-kafka-target.yaml b/examples/backups/kafka-metadata/20-kafka-target.yaml index 7642f81bf..ff7e30b84 100644 --- a/examples/backups/kafka-metadata/20-kafka-target.yaml +++ b/examples/backups/kafka-metadata/20-kafka-target.yaml @@ -12,8 +12,4 @@ spec: replicas: 1 size: 2Gi resourcesPreset: "c1.small" - zookeeper: - replicas: 1 - size: 1Gi - resourcesPreset: "c1.small" topics: [] diff --git a/examples/backups/kafka/00-helpers.sh b/examples/backups/kafka/00-helpers.sh index 293aedb3a..5ae81170a 100755 --- a/examples/backups/kafka/00-helpers.sh +++ b/examples/backups/kafka/00-helpers.sh @@ -92,11 +92,15 @@ resolve_kafka_image() { # is being assumed. On an air-gapped or operator-less cluster - the persona # the README's override note is for - that literal is unreachable, so the # run must set KAFKA_IMAGE to an image the nodes can actually pull. - echo "! could not read STRIMZI_KAFKA_IMAGES from deploy/strimzi-cluster-operator in cozy-kafka-operator; assuming quay.io/strimzi/kafka:0.45.1-rc1-kafka-3.9.1. Set KAFKA_IMAGE explicitly if that image is wrong or unreachable (e.g. air-gapped)." >&2 - echo "quay.io/strimzi/kafka:0.45.1-rc1-kafka-3.9.1" + echo "! could not read STRIMZI_KAFKA_IMAGES from deploy/strimzi-cluster-operator in cozy-kafka-operator; assuming quay.io/strimzi/kafka:1.2.0-kafka-4.3.1. Set KAFKA_IMAGE explicitly if that image is wrong or unreachable (e.g. air-gapped)." >&2 + echo "quay.io/strimzi/kafka:1.2.0-kafka-4.3.1" } export KAFKA_IMAGE="${KAFKA_IMAGE:-$(resolve_kafka_image)}" export KAFKA_BIN="${KAFKA_BIN:-/opt/kafka/bin}" +# Name of the long-lived CLI Pod kafka_run execs into; cleanup.sh removes it. +# A variable of its own, not the kafka-metadata demo's KAFKA_CLI_POD: the two +# demos may share a namespace, and one setting must not move the other's Pod. +export KAFKA_TOPIC_CLI_POD="${KAFKA_TOPIC_CLI_POD:-kafka-topic-cli}" log_info() { echo -e "${BLUE}i${NC} $*" >&2; } log_success() { echo -e "${GREEN}OK${NC} $*" >&2; } @@ -115,158 +119,10 @@ print_header() { echo -e "\n${MAGENTA}${BOLD}== $title ==${NC}\n" >&2 } -# Wait until a JSONPath value on a resource matches the desired string. -# Optional 7th arg is a TERMINAL failure value: once the field reaches it the -# wait returns 1 immediately instead of polling to the timeout. BackupJob and -# RestoreJob settle on a terminal phase=Failed that never becomes Succeeded (the -# strategy Job exhausts its backoffLimit), so failing fast on it keeps -# wall-clock - and the strategy Pod's log - in reach instead of burning the full -# timeout and then mislabelling a deterministic failure as "Timeout". -wait_for_field() { - local resource_type="$1" - local resource_name="$2" - local jsonpath="$3" - local desired="$4" - local namespace="${5:-}" - local timeout="${6:-300}" - local fail_value="${7:-}" - - log_substep "Waiting for $resource_type/$resource_name $jsonpath to become '$desired'..." - local elapsed=0 - local ns_flag=() - [[ -n "$namespace" ]] && ns_flag=(-n "$namespace") - - while true; do - local current - current=$(kubectl get "$resource_type" "$resource_name" "${ns_flag[@]}" -o jsonpath="$jsonpath" 2>/dev/null || true) - if [[ "$current" == "$desired" ]]; then - log_success "$resource_type/$resource_name reached '$desired'" - return 0 - fi - if [[ -n "$fail_value" && "$current" == "$fail_value" ]]; then - log_error "$resource_type/$resource_name reached terminal '$current' (expected '$desired')" - return 1 - fi - if [[ $elapsed -ge $timeout ]]; then - log_error "Timeout waiting for $resource_type/$resource_name (current: '$current', expected: '$desired')" - return 1 - fi - sleep 5 - elapsed=$((elapsed + 5)) - done -} - -# Wait for a HelmRelease to become Ready, with an existence backstop (the apps -# controller creates the HR asynchronously, so a bare `kubectl wait` right after -# `kubectl apply` races it) and a fail-fast on Stalled=True - a stalled HR has -# exhausted its remediation retries and will never turn Ready, so polling to the -# timeout only hides the real error. -wait_hr_ready() { - local name="$1" - local timeout="${2:-300}" - local elapsed=0 - local lookup state seen=0 - - log_substep "Waiting for HelmRelease/$name to become Ready..." - while true; do - # --ignore-not-found makes an absent release exit 0, so a non-zero exit - # is kubectl failing to answer. Presence is read off the name line, - # because a warning on stderr lands in the same string. - if ! lookup=$(kubectl -n "$NAMESPACE" get hr "$name" --ignore-not-found -o name 2>&1); then - state=error - elif [[ $'\n'"$lookup"$'\n' != *"/$name"$'\n'* ]]; then - state=absent - else - state=present - seen=1 - local ready stalled - ready=$(kubectl -n "$NAMESPACE" get hr "$name" \ - -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}' || true) - if [[ "$ready" == "True" ]]; then - log_success "HelmRelease/$name is Ready" - return 0 - fi - stalled=$(kubectl -n "$NAMESPACE" get hr "$name" \ - -o jsonpath='{.status.conditions[?(@.type=="Stalled")].status}' || true) - if [[ "$stalled" == "True" ]]; then - log_error "HelmRelease/$name is Stalled (terminal):" - break - fi - fi - if [[ $elapsed -ge $timeout ]]; then - log_error "Timeout waiting for HelmRelease/$name to become Ready:" - case "$state" in - error) - echo " could not look up HelmRelease/$name: $lookup" >&2 - # Seen earlier: the reads below may answer where this lookup - # did not. - [[ $seen -eq 1 ]] || return 1 - ;; - absent) - if [[ $seen -eq 1 ]]; then - echo " HelmRelease/$name was deleted from $NAMESPACE while waiting" >&2 - else - echo " HelmRelease/$name never appeared in $NAMESPACE" >&2 - fi - return 1 - ;; - esac - break - fi - sleep 5 - elapsed=$((elapsed + 5)) - done - # Reached on Stalled or on timeout. Conditions and history rather than the - # Ready message alone: a failed install is retried on an interval, so Ready - # may describe the retry rather than the failure behind it. - kubectl -n "$NAMESPACE" get hr "$name" \ - -o jsonpath='{range .status.conditions[*]} {.type}={.status} ({.reason}): {.message}{"\n"}{end}' >&2 || true - local hist - if ! hist=$(kubectl -n "$NAMESPACE" get hr "$name" \ - -o jsonpath='{range .status.history[*]} history: {.status} {.chartVersion} {.lastDeployed}{"\n"}{end}'); then - echo " history: kubectl could not read it" >&2 - elif [[ -n "${hist//[[:space:]]/}" ]]; then - printf '%s\n' "$hist" >&2 - else - # A release with no history prints nothing and exits 0; say so, - # because a blank in a failure dump reads as a dump that broke. - echo " history: (none recorded)" >&2 - fi - return 1 -} - -# Wait until a namespaced resource is really gone. -# -# `kubectl wait --for=delete` is not used: it errors when the resource is -# already absent, the normal case on a clean namespace (cleanup.sh is -# idempotent and runs as a pre-clean too), and swallowing that error would also -# swallow a genuine failure. Polling `get --ignore-not-found` treats "already -# gone" and "gone now" alike (empty output, exit 0), while a retrieval failure - -# RBAC, API-server, transport - is a non-zero exit that must NOT be read as -# deletion, or the teardown settles on a false success and leaves -# half-uninstalled resources for the next run. -wait_deleted() { - local resource_type="$1" - local resource_name="$2" - local timeout="${3:-300}" - local elapsed=0 - local got - - while true; do - if got=$(kubectl -n "$NAMESPACE" get "$resource_type" "$resource_name" --ignore-not-found 2>/dev/null) && [[ -z "$got" ]]; then - [[ $elapsed -gt 0 ]] && log_success "$resource_type/$resource_name is gone" - return 0 - fi - if [[ $elapsed -ge $timeout ]]; then - log_error "Timeout waiting for $resource_type/$resource_name to be deleted; still present after ${timeout}s:" - kubectl -n "$NAMESPACE" get "$resource_type" "$resource_name" -o wide >&2 || true - return 1 - fi - [[ $elapsed -eq 0 ]] && log_substep "Waiting for $resource_type/$resource_name to be deleted..." - sleep 5 - elapsed=$((elapsed + 5)) - done -} +# wait_for_field, wait_hr_ready and wait_deleted live in one file shared by +# every backup walkthrough, so a fix to one reaches all of them. +# shellcheck source-path=SCRIPTDIR source=../_lib/wait-helpers.sh +source "$(dirname "${BASH_SOURCE[0]}")/../_lib/wait-helpers.sh" # In-cluster bootstrap address for a Kafka application instance. The Cozystack # chart names the Strimzi Kafka cluster "kafka-", and Strimzi names the @@ -278,7 +134,41 @@ kafka_bootstrap() { echo "kafka-${app}-kafka-bootstrap.${NAMESPACE}.svc:9092" } -# Run a bash snippet in a throwaway Strimzi Kafka Pod. The snippet runs with +# Ensure the long-lived CLI Pod exists and is Ready, so kafka_run can exec into +# it. A Ready Pod this demo owns is reused across calls and across the numbered +# scripts; a leftover in a terminal phase is replaced; a same-named Pod the demo +# does not own is refused rather than hijacked or deleted. +# Every step returns on failure explicitly: this runs as the left side of +# `|| return 1`, and some callers also wrap it in $(...), so errexit never +# applies inside it and a bare failure would carry on to the next step. +kafka_cli_pod() { + local phase owner overrides + phase=$(kubectl -n "$NAMESPACE" get pod "$KAFKA_TOPIC_CLI_POD" --ignore-not-found -o jsonpath='{.status.phase}') || return 1 + owner=$(kubectl -n "$NAMESPACE" get pod "$KAFKA_TOPIC_CLI_POD" --ignore-not-found -o jsonpath='{.metadata.labels.cozystack\.io/backup-demo}') || return 1 + if [ -n "$phase" ] && [ "$owner" != "kafka" ]; then + log_error "Pod $NAMESPACE/$KAFKA_TOPIC_CLI_POD exists but this demo does not own it; refusing to use or delete it" + return 1 + fi + if [ "$phase" != "Running" ] && [ "$phase" != "Pending" ]; then + # restricted-clean Pod. The Strimzi image runs as a non-root numeric + # UID (1001), so runAsNonRoot/seccomp at the Pod level plus the + # container's allowPrivilegeEscalation=false and drop-ALL satisfy PSA + # "restricted" without pinning runAsUser to a value specific to this + # image tag. An add-only JSON patch layers these onto the run-generated + # Pod's sole container (index 0), leaving image, command and args + # untouched. + overrides='[{"op":"add","path":"/spec/securityContext","value":{"runAsNonRoot":true,"seccompProfile":{"type":"RuntimeDefault"}}},{"op":"add","path":"/spec/containers/0/securityContext","value":{"allowPrivilegeEscalation":false,"capabilities":{"drop":["ALL"]}}}]' + kubectl -n "$NAMESPACE" delete pod "$KAFKA_TOPIC_CLI_POD" --grace-period=1 --ignore-not-found >/dev/null || return 1 + kubectl -n "$NAMESPACE" run "$KAFKA_TOPIC_CLI_POD" --image="$KAFKA_IMAGE" \ + --labels=cozystack.io/backup-demo=kafka \ + --override-type=json --overrides="$overrides" \ + --restart=Never --command -- sleep infinity >/dev/null || return 1 + fi + kubectl -n "$NAMESPACE" wait --for=condition=Ready "pod/$KAFKA_TOPIC_CLI_POD" \ + --timeout=5m >/dev/null +} + +# Run a bash snippet in the demo's Strimzi Kafka CLI Pod. The snippet runs with # these variables pre-set, so it needs no nested shell quoting of its own: # $BOOT - the target app's plaintext bootstrap (host:port) # $BIN - the kafka CLI directory @@ -286,25 +176,19 @@ kafka_bootstrap() { # This is the host-side analogue of the strategy Pod: same stock image, same # tools, no purpose-built backup container. Pass the snippet single-quoted so # its own $VAR references reach the Pod's bash unexpanded. +# +# The snippet runs by `kubectl exec`, not in a throwaway `kubectl run -i` Pod. +# That Pod's stdout comes back over an attach carrying only what the container +# writes after the attach registers, so a CLI that finishes first reads as an +# empty reply with exit 0. An exec'd process owns its pipes, so its output +# cannot be missed that way. kafka_run() { local app="$1"; shift local snippet="$1" - local boot pod + local boot boot="$(kafka_bootstrap "$app")" - pod="kafka-cli-$RANDOM" - # restricted-clean throwaway Pod. The Strimzi image runs as a non-root - # numeric UID (1001), so runAsNonRoot/seccomp at the Pod level plus the - # container's allowPrivilegeEscalation=false and drop-ALL satisfy PSA - # "restricted" without pinning runAsUser to a value specific to this image - # tag. An add-only JSON patch layers these onto the run-generated Pod's sole - # container (index 0), leaving image, command and args untouched. - local overrides - overrides='[{"op":"add","path":"/spec/securityContext","value":{"runAsNonRoot":true,"seccompProfile":{"type":"RuntimeDefault"}}},{"op":"add","path":"/spec/containers/0/securityContext","value":{"allowPrivilegeEscalation":false,"capabilities":{"drop":["ALL"]}}}]' - kubectl -n "$NAMESPACE" run "$pod" \ - --image="$KAFKA_IMAGE" --restart=Never --rm -i --quiet \ - --pod-running-timeout=5m \ - --override-type=json --overrides="$overrides" \ - --command -- bash -c "set -eu + kafka_cli_pod || return 1 + kubectl -n "$NAMESPACE" exec -i "$KAFKA_TOPIC_CLI_POD" -- bash -c "set -eu BOOT=$(printf %q "$boot") BIN=$(printf %q "$KAFKA_BIN") TOPIC=$(printf %q "$TOPIC") @@ -331,7 +215,7 @@ seed_topic() { printf "k-%s\torder-%s\n" "$i" "$i" i=$((i + 1)) done | "$BIN"/kafka-console-producer.sh --bootstrap-server "$BOOT" \ - --topic "$TOPIC" --property parse.key=true + --topic "$TOPIC" --reader-property parse.key=true ' } @@ -347,7 +231,7 @@ seed_decoy_topic() { printf "d-%s\tdecoy-%s\n" "$i" "$i" i=$((i + 1)) done | "$BIN"/kafka-console-producer.sh --bootstrap-server "$BOOT" \ - --topic "$DECOY_TOPIC" --property parse.key=true + --topic "$DECOY_TOPIC" --reader-property parse.key=true ' } @@ -403,7 +287,7 @@ topic_dump() { [ "${end:-0}" -gt 0 ] || continue "$BIN"/kafka-console-consumer.sh --bootstrap-server "$BOOT" --topic "$TOPIC" \ --partition "$p" --offset 0 --max-messages "$end" --timeout-ms 60000 \ - --property print.key=true --property print.timestamp=false \ + --formatter-property print.key=true --formatter-property print.timestamp=false \ | sed "s/^/$p\t/" done ' @@ -425,7 +309,7 @@ topic_replication_factor() { # Create the "-backup-s3" Secret the Job strategy Pod consumes, from the # bucket coordinates cached by 03-create-bucket.sh. The generic Job strategy - # unlike the app-specific drivers - has no chart support to emit this Secret, -# so the tenant provides it. Called for the source app (step 04) and the +# so the demo provides it. Called for the source app (step 04) and the # restore target (step 07). The S3 endpoint's CA, when 03-create-bucket.sh # cached one, rides along as ca.crt: the strategy Pod mounts that key and # verifies the endpoint against it instead of disabling verification. diff --git a/examples/backups/kafka/01-create-strategy.sh b/examples/backups/kafka/01-create-strategy.sh index 7abd2df9a..7c57c1f65 100755 --- a/examples/backups/kafka/01-create-strategy.sh +++ b/examples/backups/kafka/01-create-strategy.sh @@ -82,7 +82,7 @@ spec: value: "{{ .Release.Namespace }}" - name: MODE value: "{{ .Mode }}" - # S3 coordinates from the tenant-provided -backup-s3 Secret + # S3 coordinates from the demo-provided -backup-s3 Secret # (created by create_s3_secret in 00-helpers.sh from the Bucket). - name: AWS_ACCESS_KEY_ID valueFrom: @@ -169,7 +169,7 @@ spec: # curl --aws-sigv4 signs the request (SigV4) so no separate S3 # client image is needed. The certificate is verified: against the - # CA projected from the Secret when the tenant supplied one, else + # CA projected from the Secret when it carries one, else # against the image's trust store. \${CA_OPT} and \${CONNECT_TO} # are deliberately unquoted so an empty value expands to no # argument. @@ -324,7 +324,7 @@ spec: if [ "\${n}" -gt 0 ]; then "\${BIN}"/kafka-console-consumer.sh --bootstrap-server "\${BOOT}" \ --topic "\${t}" --partition "\${p}" --offset "\${begin}" --max-messages "\${n}" \ - --timeout-ms 120000 --property print.key=true --property print.timestamp=false \ + --timeout-ms 120000 --formatter-property print.key=true --formatter-property print.timestamp=false \ > "\${WORK}/data-\${t}-\${p}.tsv" # kafka-console-consumer exits 0 even on a short read: a # --timeout-ms expiry is swallowed inside ConsoleConsumer, @@ -509,7 +509,7 @@ spec: [ "\${mt}" = "\${t}" ] || continue [ "\${me}" -gt "\${mb}" ] || continue "\${BIN}"/kafka-console-producer.sh --bootstrap-server "\${BOOT}" \ - --topic "\${t}" --property parse.key=true < "\${WORK}/data-\${t}-\${mp}.tsv" + --topic "\${t}" --reader-property parse.key=true < "\${WORK}/data-\${t}-\${mp}.tsv" done < "\${WORK}/manifest.txt" echo " \${t}: replayed" done diff --git a/examples/backups/kafka/03-create-bucket.sh b/examples/backups/kafka/03-create-bucket.sh index cbd32cfb9..74688feba 100755 --- a/examples/backups/kafka/03-create-bucket.sh +++ b/examples/backups/kafka/03-create-bucket.sh @@ -1,7 +1,7 @@ #!/bin/bash # Step 03: Provision an in-cluster Bucket and cache its S3 coordinates. The # generic Job strategy has no chart support to emit a backup Secret, so the -# tenant materialises the "-backup-s3" Secret itself. This step only +# demo materialises the "-backup-s3" Secret itself. This step only # caches the coordinates; create_s3_secret (00-helpers.sh) turns them into # per-app Secrets in steps 04 and 07. set -euo pipefail @@ -26,7 +26,9 @@ spec: readonly: false EOF -wait_hr_ready "bucket-${BUCKET_NAME}" +# 660s, above this generated release's 600s install timeout; see "Sizing an +# HR-Ready budget" in docs/agents/e2e-testing.md. +wait_hr_ready "bucket-${BUCKET_NAME}" 660 kubectl -n "$NAMESPACE" wait bucketclaims.objectstorage.k8s.io "bucket-${BUCKET_NAME}" --for=jsonpath='{.status.bucketReady}'=true --timeout=300s # Cozystack's bucket app provisions a BucketAccess named "-backup" # (the "-backup" suffix is the BucketAccessClass name); the BucketInfo Secret diff --git a/examples/backups/kafka/90-scenario-admin-prepare.md b/examples/backups/kafka/90-scenario-admin-prepare.md index 06f639d51..42bc1d697 100644 --- a/examples/backups/kafka/90-scenario-admin-prepare.md +++ b/examples/backups/kafka/90-scenario-admin-prepare.md @@ -1,9 +1,6 @@ # Scenario: Cluster admin prepares Kafka topic-data backups -A cluster administrator performs the cluster-level preparation once. Tenants -will then be able to back up and restore the topic data of their Kafka -applications by referencing the BackupClass created here, with no further -admin action. +A cluster administrator performs the cluster-level preparation once. Tenant admins can then back up and restore the topic data of their Kafka applications with a `BackupJob` or `RestoreJob` that references the BackupClass created here. The demo scripts around those jobs still need admin access, because they create Secrets and work through a CLI Pod; the README's step table says which part of each step a tenant admin can do. ## Prerequisites @@ -11,9 +8,7 @@ admin action. backupstrategy-controller installed. - `kubectl` access with permissions to create cluster-scoped `Job.strategy.backups.cozystack.io` and `BackupClass.backups.cozystack.io`. -- Reachable S3-compatible storage. The demo uses the in-cluster `Bucket` app - (step 03); the tenant turns its coordinates and the endpoint's CA into a - `-backup-s3` Secret that the strategy Pod reads (step 04 / 07). +- Reachable S3-compatible storage. The demo uses the in-cluster `Bucket` app (step 03), and steps 04 and 07 turn its coordinates and the endpoint's CA into a `-backup-s3` Secret that the strategy Pod reads. Creating that Secret needs admin access, since no tenant role grants `create` on `secrets`. ## Steps diff --git a/examples/backups/kafka/91-scenario-user-backup.md b/examples/backups/kafka/91-scenario-user-backup.md index 0cbeee34c..9bff52ee3 100644 --- a/examples/backups/kafka/91-scenario-user-backup.md +++ b/examples/backups/kafka/91-scenario-user-backup.md @@ -2,14 +2,13 @@ This scenario assumes the admin steps (`01-...`, `02-...`) have already run. +The user's own action here, at the tenant admin level, is the `BackupJob` in step 05, plus creating the `Bucket` and the `Kafka`. Steps 03 and 04 as scripted need admin access: they read and create Secrets, wait on HelmReleases and operator resources, and seed the topic through a CLI Pod, which no tenant role allows. The README's step table has the details. + ## Prerequisites - Tenant namespace (default: `tenant-root`, the tenant whose Pods can reach the in-cluster seaweedfs; see the README). -- A Cozystack `Bucket` (step 03) and the `-backup-s3` Secret derived from - it (step 04). The generic `Job` strategy has no chart support to emit this - Secret, so the tenant creates it from the bucket's `BucketInfo` plus the S3 - endpoint's CA (see `create_s3_secret` in `00-helpers.sh`). +- A Cozystack `Bucket` (step 03) and the `-backup-s3` Secret derived from it (step 04). The generic `Job` strategy has no chart support to emit this Secret, so step 04 creates it from the bucket's `BucketInfo` plus the S3 endpoint's CA (see `create_s3_secret` in `00-helpers.sh`). Creating it needs admin access. - A `Kafka` application with at least one plain (neither compacted nor transactional) topic holding data. diff --git a/examples/backups/kafka/92-scenario-user-restore.md b/examples/backups/kafka/92-scenario-user-restore.md index 2501de2c8..d637a6c9f 100644 --- a/examples/backups/kafka/92-scenario-user-restore.md +++ b/examples/backups/kafka/92-scenario-user-restore.md @@ -4,6 +4,8 @@ Two restore variants are supported. Both append: the strategy recreates a topic only if it is absent and then replays every record, so it refuses a target topic that already holds data. +The user's own action in both variants, at the tenant admin level, is the `RestoreJob`, plus the second `Kafka` in variant B. The scripts as written need admin access: variant A deletes and checks the topic through a CLI Pod and reads the refused restore's Pod log, and variant B checks the topic the same way, creates the target's Secret and waits on its `HelmRelease` and Strimzi `Kafka`, none of which a tenant role allows. The README's step table has the details. + ## A. In-place restore Restore back into the same Kafka application. @@ -69,9 +71,6 @@ The script: had already replayed. The Pod log names each topic before its replay and again once it landed; empty or delete every topic it shows as started, not only the one the refusal names, then re-run. -- The tarball in object storage is not managed by the Cozystack `Backup` - lifecycle: deleting the `Backup` CR removes the reference but leaves the S3 - object in place. Tenants who need to reclaim space should delete the object - (or set a bucket lifecycle policy). +- The tarball in object storage is not managed by the Cozystack `Backup` lifecycle: deleting the `Backup` CR removes the reference but leaves the S3 object in place. Tenants who need to reclaim space should delete the object, or set a lifecycle rule on the bucket. A Simple or MultiZone Cozystack SeaweedFS applies such rules once a day only while its `lifecycle.enabled` is on, which is not the default; a Client instance applies none itself, so the SeaweedFS it connects to must have `lifecycle.enabled` on. Another object store applies them only if it implements bucket lifecycle. - Consumer-group offsets, topic configs, ACLs and users are not part of the backup; consumers start from the restored topic's fresh offsets. diff --git a/examples/backups/kafka/README.md b/examples/backups/kafka/README.md index 2d6fe075a..0a70558cd 100644 --- a/examples/backups/kafka/README.md +++ b/examples/backups/kafka/README.md @@ -25,7 +25,7 @@ This is a **logical DATA backup**, deliberately narrow — it captures topic rec - **Each backup overwrites the previous one**: the S3 object key is `//kafka-topics.tar` with no run identifier, so every `Backup` of the same application resolves to the same tarball and restoring an older `Backup` restores the latest data. The generic `Job` driver exposes no unique per-run handle at backup time — the `Backup` artifact is created only after the Job completes — so a per-run key would need a driver change. - **Local disk usage is unbounded**: the drain stages the whole topic under `/tmp` and then again as a tarball on the Pod's writable layer, and the strategy Pod requests no `ephemeral-storage`. A large topic can fill the node's ephemeral storage and evict other Pods; set an `ephemeral-storage` request and limit sized to your data before backing up anything substantial. - **TLS is verified against the endpoint's CA**: the in-cluster seaweedfs presents a self-signed certificate, so `03-create-bucket.sh` caches its CA (the `seaweedfs-ca-cert` Secret in `tenant-root`, or the cert-manager CA `Certificate` it discovers when that name is absent) and `create_s3_secret` adds it as `ca.crt` to each `-backup-s3` Secret. The strategy Pod projects that one key as a file and points `curl --cacert` at it; a Secret without the key leaves the file absent and curl falls back to the image's trust store, which is the right behaviour for a publicly-trusted endpoint — set `S3_CA_SECRET=""` to skip the copy there, since `--cacert` replaces the system bundle rather than extending it. The `rabbitmq` example mounts the same CA for the same reason. -- **Pod Security**: the strategy Pod and the demo's throwaway CLI Pods set `runAsNonRoot`, `allowPrivilegeEscalation: false`, drop all capabilities and a `RuntimeDefault` seccomp profile, so they satisfy the `restricted` Pod Security Standard on the stock Strimzi image, which runs as non-root UID 1001. Pinning an image that runs as root would need a `runAsUser` suited to that image instead. +- **Pod Security**: the strategy Pod and the demo's CLI Pod set `runAsNonRoot`, `allowPrivilegeEscalation: false`, drop all capabilities and a `RuntimeDefault` seccomp profile, so they satisfy the `restricted` Pod Security Standard on the stock Strimzi image, which runs as non-root UID 1001. Pinning an image that runs as root would need a `runAsUser` suited to that image instead. For a faithful, offset-preserving Kafka backup, prefer a volume-snapshot strategy over this logical one; this example exists to show the generic `Job` path end to end. @@ -36,15 +36,15 @@ For a faithful, offset-preserving Kafka backup, prefer a volume-snapshot strateg | `00-helpers.sh` | Shared bash helpers, env defaults, and the kafka-CLI / S3-secret helpers; sourced by every step. | n/a | | `01-create-strategy.sh` | Creates the cluster-scoped `Job` strategy (the Kafka backup/restore `PodTemplateSpec`). | admin | | `02-create-backupclass.sh` | Maps `apps.cozystack.io/Kafka` to that strategy, with the `topics` parameter (and the optional `replicationFactor` override). | admin | -| `03-create-bucket.sh` | Provisions a `Bucket` and caches its S3 coordinates plus the endpoint's CA into `.bucket-info.env` (chmod 600; raw access keys). `cleanup.sh` removes this file. | tenant, **plus admin** for the CA copy: it reads a Secret in `tenant-root`, which a tenant persona is not granted (see the TLS bullet above) | -| `04-create-kafka.sh` | Provisions a two-broker `Kafka`, creates the `-backup-s3` Secret, seeds a topic (replication factor 2) with sentinel messages. | tenant | +| `03-create-bucket.sh` | Provisions a `Bucket` and caches its S3 coordinates plus the endpoint's CA into `.bucket-info.env` (chmod 600; raw access keys). `cleanup.sh` removes this file. | **admin**. A tenant admin can create the `Bucket` itself, but the script also waits on its `HelmRelease` and COSI objects, reads the `bucket--backup` Secret, and copies the CA from a Secret in `tenant-root` (see the TLS bullet above); no tenant role grants access to `helmreleases` or `objectstorage.k8s.io`, or `get` on those Secrets | +| `04-create-kafka.sh` | Provisions a two-broker `Kafka`, creates the `-backup-s3` Secret, seeds a topic (replication factor 2) with sentinel messages. | **admin**. A tenant admin can create the `Kafka` itself, but the script also waits on its `HelmRelease` and Strimzi `Kafka`, creates the Secret, and seeds the topic through a CLI Pod it execs into; no tenant role grants access to `helmreleases` or `kafkas.kafka.strimzi.io`, `create` on `secrets` or `pods`, or `pods/exec` | | `05-create-backupjob.sh` | Submits a `BackupJob`, waits for Succeeded and caches the resolved `Backup` name into `.backup-name.env`. | tenant | -| `06-restore-in-place.sh` | Deletes the topic and restores it into the same instance via `RestoreJob`, then submits a second `RestoreJob` that must be refused because the topic is no longer empty. | tenant | -| `07-restore-to-copy.sh` | Provisions a second two-broker `Kafka` and restores into it via `RestoreJob.spec.targetApplicationRef`. | tenant | -| `cleanup.sh` | Removes everything created by the demo. | admin or tenant | +| `06-restore-in-place.sh` | Deletes the topic and restores it into the same instance via `RestoreJob`, then submits a second `RestoreJob` that must be refused because the topic is no longer empty. | **admin**. A tenant admin can submit the two `RestoreJob`s, but the script deletes and checks the topic through the CLI Pod and reads the refusal from the restore Pod's log; no tenant role grants `create` on `pods` or `pods/exec`, or `get` on `pods/log` | +| `07-restore-to-copy.sh` | Provisions a second two-broker `Kafka` and restores into it via `RestoreJob.spec.targetApplicationRef`. | **admin**, for the same reasons as step 04. The tenant admin's part is the second `Kafka` and the `RestoreJob` | +| `cleanup.sh` | Removes everything created by the demo. | **admin**: it deletes Secrets, the `Backup`, and the cluster-scoped `BackupClass` and strategy, and no tenant role grants `delete` on any of them | | `run-all.sh` | Convenience runner that executes 01..07 in order. | demo | -The scenario walk-throughs `90-scenario-admin-prepare.md`, `91-scenario-user-backup.md` and `92-scenario-user-restore.md` describe the same steps from the admin's and the tenant's side. +The scenario walk-throughs `90-scenario-admin-prepare.md`, `91-scenario-user-backup.md` and `92-scenario-user-restore.md` describe the same steps from the admin's and the tenant's side, and say which parts of the tenant's side need admin access. ## Running diff --git a/examples/backups/kafka/cleanup.sh b/examples/backups/kafka/cleanup.sh index 35d8cdf78..7f06bab82 100755 --- a/examples/backups/kafka/cleanup.sh +++ b/examples/backups/kafka/cleanup.sh @@ -27,12 +27,13 @@ kubectl -n "$NAMESPACE" delete secret "${KAFKA_NAME}-backup-s3" --ignore-not-fou kubectl -n "$NAMESPACE" delete kafka.apps.cozystack.io "$KAFKA_RESTORE_NAME" --ignore-not-found kubectl -n "$NAMESPACE" delete kafka.apps.cozystack.io "$KAFKA_NAME" --ignore-not-found kubectl -n "$NAMESPACE" delete bucket.apps.cozystack.io "$BUCKET_NAME" --ignore-not-found +kubectl -n "$NAMESPACE" delete pod -l cozystack.io/backup-demo=kafka --grace-period=1 --ignore-not-found rm -f "$SCRIPT_DIR/.bucket-info.env" "$SCRIPT_DIR/.source-dump.txt" "$SCRIPT_DIR/.backup-name.env" kubectl delete backupclass.backups.cozystack.io "$BACKUPCLASS_NAME" --ignore-not-found kubectl delete job.strategy.backups.cozystack.io "$STRATEGY_NAME" --ignore-not-found # `kubectl delete` returns as soon as deletionTimestamp is set, while the -# HelmRelease uninstall behind each Kafka app (two StatefulSets, ZooKeeper and +# HelmRelease uninstall behind each Kafka app (its broker and controller pods and # their PVCs) is still draining. Returning here lets the next suite start into a # namespace whose predecessor is still uninstalling - the neighbouring # chainsaw/kafka Test's PVC-reclaim step contends with exactly that. Wait for diff --git a/examples/backups/kubernetes/00-helpers.sh b/examples/backups/kubernetes/00-helpers.sh new file mode 100755 index 000000000..401b5edb8 --- /dev/null +++ b/examples/backups/kubernetes/00-helpers.sh @@ -0,0 +1,94 @@ +#!/bin/bash +# Shared helpers for the tenant Kubernetes backup/restore walkthrough. +# Source this file in other scripts: source "$(dirname "$0")/00-helpers.sh" + +export RED='\033[0;31m' +export GREEN='\033[0;32m' +export YELLOW='\033[1;33m' +export BLUE='\033[0;34m' +export MAGENTA='\033[0;35m' +export CYAN='\033[0;36m' +export NC='\033[0m' +export BOLD='\033[1m' + +export NAMESPACE="${NAMESPACE:-tenant-root}" +export CLUSTER_NAME="${CLUSTER_NAME:-backup-demo}" +export POOL_NAME="${POOL_NAME:-md0}" +export WORKER_DISK_SIZE="${WORKER_DISK_SIZE:-20Gi}" +export BACKUPCLASS_NAME="${BACKUPCLASS_NAME:-cozy-default}" +export BACKUPJOB_NAME="${BACKUPJOB_NAME:-kubernetes-backup-job}" +export RESTOREJOB_INPLACE_NAME="${RESTOREJOB_INPLACE_NAME:-kubernetes-restore-inplace}" +export RESTOREJOB_RECREATE_NAME="${RESTOREJOB_RECREATE_NAME:-kubernetes-restore-recreate}" +export TENANT_API_PORT="${TENANT_API_PORT:-16443}" +export MARKER_VALUE="${MARKER_VALUE:-roundtrip-7c2e91d4}" +export RELEASE="kubernetes-${CLUSTER_NAME}" + +log_info() { echo -e "${BLUE}i${NC} $*" >&2; } +log_success() { echo -e "${GREEN}OK${NC} $*" >&2; } +log_warning() { echo -e "${YELLOW}!${NC} $*" >&2; } +log_error() { echo -e "${RED}x${NC} $*" >&2; } +log_substep() { echo -e "${CYAN} -> $*${NC}" >&2; } + +print_header() { + echo -e "\n${MAGENTA}${BOLD}== $1 ==${NC}\n" >&2 +} + +# shellcheck source-path=SCRIPTDIR source=../_lib/wait-helpers.sh +source "$(dirname "${BASH_SOURCE[0]}")/../_lib/wait-helpers.sh" + +# The admin kubeconfig points at the in-cluster Service, so the walkthrough +# reaches the tenant API through a port-forward to it and keeps the TLS server +# name the certificate is issued for. +TENANT_KUBECONFIG="$(dirname "${BASH_SOURCE[0]}")/.tenant-kubeconfig" +export TENANT_KUBECONFIG + +tenant_connect() { + kubectl -n "$NAMESPACE" get secret "${RELEASE}-admin-kubeconfig" \ + -o jsonpath='{.data.super-admin\.svc}' | base64 -d > "$TENANT_KUBECONFIG" + chmod 600 "$TENANT_KUBECONFIG" + local cluster + cluster=$(kubectl --kubeconfig "$TENANT_KUBECONFIG" config view -o jsonpath='{.clusters[0].name}') + kubectl --kubeconfig "$TENANT_KUBECONFIG" config set-cluster "$cluster" \ + --server="https://127.0.0.1:${TENANT_API_PORT}" \ + --tls-server-name="${RELEASE}.${NAMESPACE}.svc" >/dev/null + pkill -f "port-forward svc/${RELEASE} ${TENANT_API_PORT}:6443" 2>/dev/null || true + kubectl -n "$NAMESPACE" port-forward "svc/${RELEASE}" "${TENANT_API_PORT}:6443" >/dev/null 2>&1 & + for _ in $(seq 1 30); do + tkubectl get --raw /readyz >/dev/null 2>&1 && return 0 + sleep 2 + done + log_error "tenant API of ${RELEASE} is not reachable through the port-forward" + return 1 +} + +tenant_disconnect() { + pkill -f "port-forward svc/${RELEASE} ${TENANT_API_PORT}:6443" 2>/dev/null || true +} + +tkubectl() { + kubectl --kubeconfig "$TENANT_KUBECONFIG" "$@" +} + +# The CA fingerprint is what proves a restore brought back the cluster rather +# than a new one: nodes, kubeconfigs and tokens all trust this CA. +cluster_ca_fingerprint() { + kubectl -n "$NAMESPACE" get secret "${RELEASE}-ca" -o jsonpath='{.data.ca\.crt}' \ + | base64 -d | openssl x509 -noout -fingerprint -sha256 | cut -d= -f2 +} + +# wait_tenant_marker checks both halves of the backup: the ConfigMap comes back +# with etcd, the file on the PVC with the volumes. +wait_tenant_marker() { + local timeout="${1:-900}" elapsed=0 cm data + while true; do + cm=$(tkubectl -n demo get configmap marker -o jsonpath='{.data.marker}' 2>/dev/null || true) + data=$(tkubectl -n demo exec deploy/writer -- cat /data/marker 2>/dev/null || true) + if [[ "$cm" == "$MARKER_VALUE" && "$data" == "$MARKER_VALUE" ]]; then + log_success "marker present in etcd (ConfigMap) and on the volume" + return 0 + fi + (( elapsed >= timeout )) && { log_error "marker not restored: configmap='${cm}' volume='${data}'"; return 1; } + sleep 10 + elapsed=$((elapsed + 10)) + done +} diff --git a/examples/backups/kubernetes/01-create-cluster.sh b/examples/backups/kubernetes/01-create-cluster.sh new file mode 100755 index 000000000..8577ec202 --- /dev/null +++ b/examples/backups/kubernetes/01-create-cluster.sh @@ -0,0 +1,102 @@ +#!/bin/bash +# Step 01: Create a tenant Kubernetes cluster with one worker pool and seed it +# with a marker held in etcd (a ConfigMap) and on a PersistentVolume. +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +source "$SCRIPT_DIR/00-helpers.sh" + +print_header "Step 01: Create Kubernetes '${CLUSTER_NAME}' and seed a marker" + +kubectl apply -f - </dev/null 2>&1 \ + && [[ -n "$(tkubectl get nodes -o name)" ]] \ + && [[ -n "$(tkubectl get storageclass -o name)" ]]; then + kubectl_ok=1 + break + fi + sleep 15 +done +(( kubectl_ok )) || { log_error "worker node or StorageClass did not appear"; exit 1; } + +tkubectl apply -f - < /data/marker; sync; sleep infinity"] + volumeMounts: + - {name: data, mountPath: /data} + volumes: + - name: data + persistentVolumeClaim: {claimName: data} +EOF + +wait_tenant_marker 900 +cluster_ca_fingerprint > "$SCRIPT_DIR/.ca-fingerprint" +log_success "cluster CA $(cat "$SCRIPT_DIR/.ca-fingerprint")" +tenant_disconnect + +echo -e "\n${GREEN}${BOLD}Next:${NC} ./02-create-backupjob.sh" diff --git a/examples/backups/kubernetes/02-create-backupjob.sh b/examples/backups/kubernetes/02-create-backupjob.sh new file mode 100755 index 000000000..c290711c1 --- /dev/null +++ b/examples/backups/kubernetes/02-create-backupjob.sh @@ -0,0 +1,36 @@ +#!/bin/bash +# Step 02: Back the cluster up through the cozy-default BackupClass. The +# controller dumps the cluster's etcd prefix to the platform bucket with a +# Job, then backs up its control-plane Secrets and volumes with Velero. +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +source "$SCRIPT_DIR/00-helpers.sh" + +print_header "Step 02: Create BackupJob '${BACKUPJOB_NAME}'" + +kubectl apply -f - </dev/null || true) +kubectl -n "$NAMESPACE" delete backupjob "$BACKUPJOB_NAME" --ignore-not-found +[[ -n "$backup_ref" ]] && kubectl -n "$NAMESPACE" delete backup "$backup_ref" --ignore-not-found +kubectl -n "$NAMESPACE" delete kubernetesnodeses.apps.cozystack.io "${CLUSTER_NAME}-${POOL_NAME}" --ignore-not-found +kubectl -n "$NAMESPACE" delete kuberneteses.apps.cozystack.io "$CLUSTER_NAME" --ignore-not-found +rm -f "$TENANT_KUBECONFIG" "$SCRIPT_DIR/.ca-fingerprint" +log_success "done" diff --git a/examples/backups/kubernetes/run-all.sh b/examples/backups/kubernetes/run-all.sh new file mode 100755 index 000000000..731448b4d --- /dev/null +++ b/examples/backups/kubernetes/run-all.sh @@ -0,0 +1,29 @@ +#!/bin/bash +# End-to-end tenant Kubernetes backup/restore walkthrough. It proves the +# restore brings back the same cluster: the CA fingerprint is unchanged, and a +# marker kept in etcd and one kept on a PersistentVolume both come back, first +# after rolling a live cluster back, then after rebuilding a deleted one. +# +# Needs the platform default backups (backupstrategy-controller with a Velero +# BSL and the system bucket), so cozy-default routes Kubernetes to +# cozy-default-kubernetes. +# +# Env knobs: see 00-helpers.sh. SKIP_RESTORE=1 stops after the backup. +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +source "$SCRIPT_DIR/00-helpers.sh" + +kubectl wait --for=create kubernetes.strategy.backups.cozystack.io/cozy-default-kubernetes --timeout=15m >/dev/null \ + || { log_error "cozy-default-kubernetes strategy is missing: enable the platform default backups first"; exit 1; } + +steps=(01 02 03 04) +[[ "${SKIP_RESTORE:-0}" == "1" ]] && steps=(01 02) +for step in "${steps[@]}"; do + script="$(find "$SCRIPT_DIR" -maxdepth 1 -type f -name "${step}-*.sh" | sort | head -n1)" + [[ -n "$script" ]] || { echo "no script found for step $step" >&2; exit 1; } + echo "=== Running $(basename "$script") ===" + bash "$script" +done + +print_header "Walkthrough complete" diff --git a/examples/backups/mariadb/00-helpers.sh b/examples/backups/mariadb/00-helpers.sh index 467790bf9..32f4c01d9 100755 --- a/examples/backups/mariadb/00-helpers.sh +++ b/examples/backups/mariadb/00-helpers.sh @@ -60,124 +60,10 @@ print_header() { echo -e "\n${MAGENTA}${BOLD}== $1 ==${NC}\n" >&2 } -# Wait until a JSONPath value on a resource matches the desired string. -# Optional 7th arg is a TERMINAL failure value: once the field reaches it the -# wait returns 1 immediately instead of polling to the timeout. BackupJob and -# RestoreJob settle on a terminal phase=Failed that never becomes Succeeded, so -# failing fast on it keeps wall-clock (and the operator Job's log, before its -# TTL reaper fires) in reach. -wait_for_field() { - local resource_type="$1" - local resource_name="$2" - local jsonpath="$3" - local desired="$4" - local namespace="${5:-}" - local timeout="${6:-300}" - local fail_value="${7:-}" - - log_substep "Waiting for $resource_type/$resource_name $jsonpath to become '$desired'..." - local elapsed=0 - local ns_flag=() - [[ -n "$namespace" ]] && ns_flag=(-n "$namespace") - - while true; do - local current - current=$(kubectl get "$resource_type" "$resource_name" "${ns_flag[@]}" -o jsonpath="$jsonpath" 2>/dev/null || true) - if [[ "$current" == "$desired" ]]; then - log_success "$resource_type/$resource_name reached '$desired'" - return 0 - fi - if [[ -n "$fail_value" && "$current" == "$fail_value" ]]; then - log_error "$resource_type/$resource_name reached terminal '$current' (expected '$desired')" - return 1 - fi - if [[ $elapsed -ge $timeout ]]; then - log_error "Timeout waiting for $resource_type/$resource_name (current: '$current', expected: '$desired')" - return 1 - fi - sleep 5 - elapsed=$((elapsed + 5)) - done -} - -# Wait for a HelmRelease to become Ready, with an existence backstop (the -# apps controller creates the HR asynchronously, so a bare `kubectl wait` -# right after `kubectl apply` races it) and a fail-fast on Stalled=True — -# a stalled HR has exhausted its remediation retries and will never turn -# Ready, so polling to the timeout only hides the real error. -wait_hr_ready() { - local name="$1" - local timeout="${2:-300}" - local elapsed=0 - local lookup state seen=0 - - log_substep "Waiting for HelmRelease/$name to become Ready..." - while true; do - # --ignore-not-found makes an absent release exit 0, so a non-zero exit - # is kubectl failing to answer. Presence is read off the name line, - # because a warning on stderr lands in the same string. - if ! lookup=$(kubectl -n "$NAMESPACE" get hr "$name" --ignore-not-found -o name 2>&1); then - state=error - elif [[ $'\n'"$lookup"$'\n' != *"/$name"$'\n'* ]]; then - state=absent - else - state=present - seen=1 - local ready stalled - ready=$(kubectl -n "$NAMESPACE" get hr "$name" \ - -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}' || true) - if [[ "$ready" == "True" ]]; then - log_success "HelmRelease/$name is Ready" - return 0 - fi - stalled=$(kubectl -n "$NAMESPACE" get hr "$name" \ - -o jsonpath='{.status.conditions[?(@.type=="Stalled")].status}' || true) - if [[ "$stalled" == "True" ]]; then - log_error "HelmRelease/$name is Stalled (terminal):" - break - fi - fi - if [[ $elapsed -ge $timeout ]]; then - log_error "Timeout waiting for HelmRelease/$name to become Ready:" - case "$state" in - error) - echo " could not look up HelmRelease/$name: $lookup" >&2 - # Seen earlier: the reads below may answer where this lookup - # did not. - [[ $seen -eq 1 ]] || return 1 - ;; - absent) - if [[ $seen -eq 1 ]]; then - echo " HelmRelease/$name was deleted from $NAMESPACE while waiting" >&2 - else - echo " HelmRelease/$name never appeared in $NAMESPACE" >&2 - fi - return 1 - ;; - esac - break - fi - sleep 5 - elapsed=$((elapsed + 5)) - done - # Reached on Stalled or on timeout. Conditions and history rather than the - # Ready message alone: a failed install is retried on an interval, so Ready - # may describe the retry rather than the failure behind it. - kubectl -n "$NAMESPACE" get hr "$name" \ - -o jsonpath='{range .status.conditions[*]} {.type}={.status} ({.reason}): {.message}{"\n"}{end}' >&2 || true - local hist - if ! hist=$(kubectl -n "$NAMESPACE" get hr "$name" \ - -o jsonpath='{range .status.history[*]} history: {.status} {.chartVersion} {.lastDeployed}{"\n"}{end}'); then - echo " history: kubectl could not read it" >&2 - elif [[ -n "${hist//[[:space:]]/}" ]]; then - printf '%s\n' "$hist" >&2 - else - # A release with no history prints nothing and exits 0; say so, - # because a blank in a failure dump reads as a dump that broke. - echo " history: (none recorded)" >&2 - fi - return 1 -} +# wait_for_field, wait_hr_ready and wait_deleted live in one file shared by +# every backup walkthrough, so a fix to one reaches all of them. +# shellcheck source-path=SCRIPTDIR source=../_lib/wait-helpers.sh +source "$(dirname "${BASH_SOURCE[0]}")/../_lib/wait-helpers.sh" # Name of the primary pod of a k8s.mariadb.com/MariaDB CR (the writer). # mariadb-operator 25.10.x reports the primary identity on diff --git a/examples/backups/mariadb/README.md b/examples/backups/mariadb/README.md index 97b2aa17e..fce3155a9 100644 --- a/examples/backups/mariadb/README.md +++ b/examples/backups/mariadb/README.md @@ -5,7 +5,7 @@ > the system bucket `cozy-backups`. Tenants reference `cozy-default` > directly from BackupJob / Plan / RestoreJob without provisioning a > Bucket or supplying S3 credentials. See -> [Backup Classes](../../../docs/operations/backup-classes.md). +> [Backup Classes](https://cozystack.io/docs/v1/operations/services/backup-classes/). > The walk-through below covers the **legacy** path that wires a > per-app Bucket and bespoke BackupClass — useful for tuned non-default > policies (custom retention, encryption, secondary buckets). diff --git a/examples/backups/mariadb/run-all.sh b/examples/backups/mariadb/run-all.sh index cf4a479c0..dbc845ce8 100755 --- a/examples/backups/mariadb/run-all.sh +++ b/examples/backups/mariadb/run-all.sh @@ -48,7 +48,9 @@ wait_app_grant_ready() { print_header "Step 00: Provision Bucket '${BUCKET_NAME}' in ${NAMESPACE}" kubectl -n "$NAMESPACE" apply -f "$SCRIPT_DIR/00-bucket.yaml" -wait_hr_ready "bucket-${BUCKET_NAME}" 300 +# 660s, above this generated release's 600s install timeout; see "Sizing an +# HR-Ready budget" in docs/agents/e2e-testing.md. +wait_hr_ready "bucket-${BUCKET_NAME}" 660 wait_for_field bucketclaims.objectstorage.k8s.io "bucket-${BUCKET_NAME}" \ '{.status.bucketReady}' true "$NAMESPACE" 300 wait_for_field bucketaccesses.objectstorage.k8s.io "bucket-${BUCKET_NAME}-${BUCKET_USER}" \ diff --git a/examples/backups/mongodb/00-helpers.sh b/examples/backups/mongodb/00-helpers.sh index 43499f87f..2f8b82cc4 100755 --- a/examples/backups/mongodb/00-helpers.sh +++ b/examples/backups/mongodb/00-helpers.sh @@ -43,124 +43,10 @@ print_header() { echo -e "\n${MAGENTA}${BOLD}== $1 ==${NC}\n" >&2 } -# Wait until a JSONPath value on a resource matches the desired string. -# Optional 7th arg is a TERMINAL failure value: once the field reaches it the -# wait returns 1 immediately instead of polling to the timeout. BackupJob and -# RestoreJob settle on a terminal phase=Failed that never becomes Succeeded, so -# failing fast on it keeps wall-clock (and the operator's pbm log, before its -# TTL reaper fires) in reach. -wait_for_field() { - local resource_type="$1" - local resource_name="$2" - local jsonpath="$3" - local desired="$4" - local namespace="${5:-}" - local timeout="${6:-300}" - local fail_value="${7:-}" - - log_substep "Waiting for $resource_type/$resource_name $jsonpath to become '$desired'..." - local elapsed=0 - local ns_flag=() - [[ -n "$namespace" ]] && ns_flag=(-n "$namespace") - - while true; do - local current - current=$(kubectl get "$resource_type" "$resource_name" "${ns_flag[@]}" -o jsonpath="$jsonpath" 2>/dev/null || true) - if [[ "$current" == "$desired" ]]; then - log_success "$resource_type/$resource_name reached '$desired'" - return 0 - fi - if [[ -n "$fail_value" && "$current" == "$fail_value" ]]; then - log_error "$resource_type/$resource_name reached terminal '$current' (expected '$desired')" - return 1 - fi - if [[ $elapsed -ge $timeout ]]; then - log_error "Timeout waiting for $resource_type/$resource_name (current: '$current', expected: '$desired')" - return 1 - fi - sleep 5 - elapsed=$((elapsed + 5)) - done -} - -# Wait for a HelmRelease to become Ready, with an existence backstop (the apps -# controller creates the HR asynchronously, so a bare `kubectl wait` right after -# `kubectl apply` races it) and a fail-fast on Stalled=True — a stalled HR has -# exhausted its remediation retries and will never turn Ready, so polling to the -# timeout only hides the real error. -wait_hr_ready() { - local name="$1" - local timeout="${2:-300}" - local elapsed=0 - local lookup state seen=0 - - log_substep "Waiting for HelmRelease/$name to become Ready..." - while true; do - # --ignore-not-found makes an absent release exit 0, so a non-zero exit - # is kubectl failing to answer. Presence is read off the name line, - # because a warning on stderr lands in the same string. - if ! lookup=$(kubectl -n "$NAMESPACE" get hr "$name" --ignore-not-found -o name 2>&1); then - state=error - elif [[ $'\n'"$lookup"$'\n' != *"/$name"$'\n'* ]]; then - state=absent - else - state=present - seen=1 - local ready stalled - ready=$(kubectl -n "$NAMESPACE" get hr "$name" \ - -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}' || true) - if [[ "$ready" == "True" ]]; then - log_success "HelmRelease/$name is Ready" - return 0 - fi - stalled=$(kubectl -n "$NAMESPACE" get hr "$name" \ - -o jsonpath='{.status.conditions[?(@.type=="Stalled")].status}' || true) - if [[ "$stalled" == "True" ]]; then - log_error "HelmRelease/$name is Stalled (terminal):" - break - fi - fi - if [[ $elapsed -ge $timeout ]]; then - log_error "Timeout waiting for HelmRelease/$name to become Ready:" - case "$state" in - error) - echo " could not look up HelmRelease/$name: $lookup" >&2 - # Seen earlier: the reads below may answer where this lookup - # did not. - [[ $seen -eq 1 ]] || return 1 - ;; - absent) - if [[ $seen -eq 1 ]]; then - echo " HelmRelease/$name was deleted from $NAMESPACE while waiting" >&2 - else - echo " HelmRelease/$name never appeared in $NAMESPACE" >&2 - fi - return 1 - ;; - esac - break - fi - sleep 5 - elapsed=$((elapsed + 5)) - done - # Reached on Stalled or on timeout. Conditions and history rather than the - # Ready message alone: a failed install is retried on an interval, so Ready - # may describe the retry rather than the failure behind it. - kubectl -n "$NAMESPACE" get hr "$name" \ - -o jsonpath='{range .status.conditions[*]} {.type}={.status} ({.reason}): {.message}{"\n"}{end}' >&2 || true - local hist - if ! hist=$(kubectl -n "$NAMESPACE" get hr "$name" \ - -o jsonpath='{range .status.history[*]} history: {.status} {.chartVersion} {.lastDeployed}{"\n"}{end}'); then - echo " history: kubectl could not read it" >&2 - elif [[ -n "${hist//[[:space:]]/}" ]]; then - printf '%s\n' "$hist" >&2 - else - # A release with no history prints nothing and exits 0; say so, - # because a blank in a failure dump reads as a dump that broke. - echo " history: (none recorded)" >&2 - fi - return 1 -} +# wait_for_field, wait_hr_ready and wait_deleted live in one file shared by +# every backup walkthrough, so a fix to one reaches all of them. +# shellcheck source-path=SCRIPTDIR source=../_lib/wait-helpers.sh +source "$(dirname "${BASH_SOURCE[0]}")/../_lib/wait-helpers.sh" # Wait until the psmdb.percona.com/PerconaServerMongoDB CR reports state=ready # (the operator's own readiness signal — the rs0 members are up and initialised diff --git a/examples/backups/mongodb/05-mongodb-src.yaml b/examples/backups/mongodb/05-mongodb-src.yaml index 8159fa800..3b8b1f3bf 100644 --- a/examples/backups/mongodb/05-mongodb-src.yaml +++ b/examples/backups/mongodb/05-mongodb-src.yaml @@ -4,8 +4,11 @@ # when the cluster has the percona-backup-mongodb agents running and a storage # declared — that is what `backup.enabled: true` wires up. The cozystack # backup-strategy driver names that storage ("s3-storage", the one the chart -# declares) via the cozy-default-mongodb Strategy; it does NOT inject storage -# into the cluster, so unlike MariaDB the application must opt into backups. +# declares) via the cozy-default-mongodb Strategy. This example uses the default +# flow, where the application owns the storage and the driver does not inject it +# — so, unlike MariaDB, the application must opt into backups. (Set +# backup.useSystemBucket: true instead to have the driver inject the platform +# system-bucket storage; see https://cozystack.io/docs/v1/operations/services/backup-classes/.) # # The bucket coordinates (destinationPath / endpointURL / s3AccessKey / # s3SecretKey) point the storage at the Bucket provisioned in 00-bucket.yaml. diff --git a/examples/backups/mongodb/README.md b/examples/backups/mongodb/README.md index 66f4c5944..f1fbf6118 100644 --- a/examples/backups/mongodb/README.md +++ b/examples/backups/mongodb/README.md @@ -23,15 +23,7 @@ Files are numbered so that `kubectl apply -f` order matches the dependency graph ## How MongoDB backups differ from the other drivers -The psmdb operator only services on-demand `PerconaServerMongoDBBackup` CRs when -the cluster has the pbm agents running and a storage declared — which is what -`backup.enabled: true` on the MongoDB application wires up. Unlike the MariaDB / -CNPG drivers, the strategy does **not** inject the storage into the cluster; it -only names it (`storageName: s3-storage`, the storage the chart declares) via -the platform's `cozy-default-mongodb` Strategy. So the application must opt into -backups (`backup.enabled: true`) with the bucket coordinates in its `backup.*` -values. The driver surfaces a clear `Ready=False` precondition (rather than a -silent hang) when the target cluster has backups disabled. +The psmdb operator runs the pbm agents when the cluster has `backup.enabled: true`, and services an on-demand `PerconaServerMongoDBBackup` only once the storage the CR names is declared on the cluster. Where that storage comes from depends on the flow the application picked. On the default flow (this example) the chart declares it from the application's own `backup.*` values, and the `cozy-default-mongodb` Strategy only names it (`storageName: s3-storage`); the driver injects nothing. With `backup.useSystemBucket: true` the chart leaves the storage out and the driver injects the platform bucket's coordinates onto the cluster before each backup. Either way the driver surfaces a clear `Ready=False` precondition (rather than a silent hang) when the target cluster has backups disabled; see `https://cozystack.io/docs/v1/operations/services/backup-classes/` for both flows. Restores use `PerconaServerMongoDBRestore.spec.backupSource`, carrying the S3 destination read back from the source backup, so the same artifact restores diff --git a/examples/backups/mongodb/run-all.sh b/examples/backups/mongodb/run-all.sh index 3b06ba28c..9793bea3b 100755 --- a/examples/backups/mongodb/run-all.sh +++ b/examples/backups/mongodb/run-all.sh @@ -44,7 +44,9 @@ subst() { print_header "Step 00: Provision Bucket '${BUCKET_NAME}' in ${NAMESPACE}" kubectl -n "$NAMESPACE" apply -f "$SCRIPT_DIR/00-bucket.yaml" -wait_hr_ready "bucket-${BUCKET_NAME}" 300 +# 660s, above this generated release's 600s install timeout; see "Sizing an +# HR-Ready budget" in docs/agents/e2e-testing.md. +wait_hr_ready "bucket-${BUCKET_NAME}" 660 wait_for_field bucketclaims.objectstorage.k8s.io "bucket-${BUCKET_NAME}" \ '{.status.bucketReady}' true "$NAMESPACE" 300 wait_for_field bucketaccesses.objectstorage.k8s.io "bucket-${BUCKET_NAME}-${BUCKET_USER}" \ diff --git a/examples/backups/nats/00-helpers.sh b/examples/backups/nats/00-helpers.sh index f98a75578..e717f172e 100755 --- a/examples/backups/nats/00-helpers.sh +++ b/examples/backups/nats/00-helpers.sh @@ -50,35 +50,10 @@ print_header() { echo -e "\n${MAGENTA}${BOLD}== $title ==${NC}\n" >&2 } -# Wait until a JSONPath value on a resource matches the desired string. -wait_for_field() { - local resource_type="$1" - local resource_name="$2" - local jsonpath="$3" - local desired="$4" - local namespace="${5:-}" - local timeout="${6:-300}" - - log_substep "Waiting for $resource_type/$resource_name $jsonpath to become '$desired'..." - local elapsed=0 - local ns_flag=() - [[ -n "$namespace" ]] && ns_flag=(-n "$namespace") - - while true; do - local current - current=$(kubectl get "$resource_type" "$resource_name" "${ns_flag[@]}" -o jsonpath="$jsonpath" 2>/dev/null || true) - if [[ "$current" == "$desired" ]]; then - log_success "$resource_type/$resource_name reached '$desired'" - return 0 - fi - if [[ $elapsed -ge $timeout ]]; then - log_error "Timeout waiting for $resource_type/$resource_name (current: '$current', expected: '$desired')" - return 1 - fi - sleep 5 - elapsed=$((elapsed + 5)) - done -} +# wait_for_field, wait_hr_ready and wait_deleted live in one file shared by +# every backup walkthrough, so a fix to one reaches all of them. +# shellcheck source-path=SCRIPTDIR source=../_lib/wait-helpers.sh +source "$(dirname "${BASH_SOURCE[0]}")/../_lib/wait-helpers.sh" # In-cluster NATS client URL for the given application instance. The NATS app # names its client Service after the application (fullnameOverride=) and @@ -97,19 +72,22 @@ nats_url() { # across the numbered demo scripts; a leftover in a terminal phase (Succeeded / # Failed) is replaced rather than waited on; and a same-named Pod this demo does # not own is refused rather than hijacked or deleted. cleanup.sh removes it. +# Every step returns on failure explicitly: this runs as the left side of +# `|| return 1`, and some callers also wrap it in $(...), so errexit never +# applies inside it and a bare failure would carry on to the next step. nats_cli_pod() { local phase owner - phase=$(kubectl -n "$NAMESPACE" get pod "$NATS_CLI_POD" -o jsonpath='{.status.phase}' 2>/dev/null || true) - owner=$(kubectl -n "$NAMESPACE" get pod "$NATS_CLI_POD" -o jsonpath='{.metadata.labels.cozystack\.io/backup-demo}' 2>/dev/null || true) + phase=$(kubectl -n "$NAMESPACE" get pod "$NATS_CLI_POD" --ignore-not-found -o jsonpath='{.status.phase}') || return 1 + owner=$(kubectl -n "$NAMESPACE" get pod "$NATS_CLI_POD" --ignore-not-found -o jsonpath='{.metadata.labels.cozystack\.io/backup-demo}') || return 1 if [ -n "$phase" ] && [ "$owner" != "nats" ]; then log_error "Pod $NAMESPACE/$NATS_CLI_POD exists but this demo does not own it; refusing to use or delete it" return 1 fi if [ "$phase" != "Running" ] && [ "$phase" != "Pending" ]; then - kubectl -n "$NAMESPACE" delete pod "$NATS_CLI_POD" --grace-period=1 --ignore-not-found >/dev/null + kubectl -n "$NAMESPACE" delete pod "$NATS_CLI_POD" --grace-period=1 --ignore-not-found >/dev/null || return 1 kubectl -n "$NAMESPACE" run "$NATS_CLI_POD" --image="$NATS_BOX_IMAGE" \ --labels=cozystack.io/backup-demo=nats \ - --restart=Never --command -- sleep infinity >/dev/null + --restart=Never --command -- sleep infinity >/dev/null || return 1 fi kubectl -n "$NAMESPACE" wait --for=condition=Ready "pod/$NATS_CLI_POD" \ --timeout=5m >/dev/null @@ -130,7 +108,7 @@ nats_cli_pod() { # reads NATS_PASSWORD from its environment. nats_cli() { local app="$1"; shift - nats_cli_pod + nats_cli_pod || return 1 printf '%s\n' "$NATS_PASSWORD" | kubectl -n "$NAMESPACE" exec -i "$NATS_CLI_POD" -- sh -c ' IFS= read -r NATS_PASSWORD || true export NATS_PASSWORD @@ -153,7 +131,7 @@ stream_message_count() { # Create the "-backup-s3" Secret the Job strategy Pod consumes, from the # bucket coordinates cached by 03-create-bucket.sh. The generic Job strategy - # unlike the app-specific drivers - has no chart support to emit this Secret, -# so the tenant provides it. Called for the source app (step 04) and the +# so the demo provides it. Called for the source app (step 04) and the # restore target (step 07). create_s3_secret() { local app="$1" diff --git a/examples/backups/nats/01-create-strategy.sh b/examples/backups/nats/01-create-strategy.sh index da5f84b39..1e3b803be 100755 --- a/examples/backups/nats/01-create-strategy.sh +++ b/examples/backups/nats/01-create-strategy.sh @@ -64,7 +64,7 @@ spec: value: "{{ if .Backup }}{{ .Backup.ApplicationRef.Name }}{{ end }}" - name: MODE value: "{{ .Mode }}" - # S3 coordinates from the tenant-provided -backup-s3 Secret + # S3 coordinates from the demo-provided -backup-s3 Secret # (created by create_s3_secret in 00-helpers.sh from the Bucket). - name: AWS_ACCESS_KEY_ID valueFrom: diff --git a/examples/backups/nats/03-create-bucket.sh b/examples/backups/nats/03-create-bucket.sh index 10bf3cf32..b12ae50b3 100755 --- a/examples/backups/nats/03-create-bucket.sh +++ b/examples/backups/nats/03-create-bucket.sh @@ -1,7 +1,7 @@ #!/bin/bash # Step 03: Provision an in-cluster Bucket and cache its S3 coordinates. Unlike # the ClickHouse demo - where the chart emits the backup Secret from -# spec.backup.* - the generic Job strategy has no chart support, so the tenant +# spec.backup.* - the generic Job strategy has no chart support, so the demo # materialises the "-backup-s3" Secret itself. This step only caches the # coordinates; create_s3_secret (00-helpers.sh) turns them into per-app Secrets # in steps 04 and 07. diff --git a/examples/backups/nats/90-scenario-admin-prepare.md b/examples/backups/nats/90-scenario-admin-prepare.md index 2314212e6..e5357443c 100644 --- a/examples/backups/nats/90-scenario-admin-prepare.md +++ b/examples/backups/nats/90-scenario-admin-prepare.md @@ -1,8 +1,6 @@ # Scenario: Cluster admin prepares NATS backups -A cluster administrator performs the cluster-level preparation once. Tenants -will then be able to back up and restore their NATS applications by referencing -the BackupClass created here, with no further admin action. +A cluster administrator performs the cluster-level preparation once. Tenant admins can then back up and restore their NATS applications with a `BackupJob` or `RestoreJob` that references the BackupClass created here. The demo scripts around those jobs still need admin access, because they create Secrets and work through a CLI Pod; the README's step table says which part of each step a tenant admin can do. ## Prerequisites @@ -10,9 +8,7 @@ the BackupClass created here, with no further admin action. backupstrategy-controller installed. - `kubectl` access with permissions to create cluster-scoped `Job.strategy.backups.cozystack.io` and `BackupClass.backups.cozystack.io`. -- Reachable S3-compatible storage. The demo uses the in-cluster `Bucket` app - (step 03); the tenant turns its coordinates into a `-backup-s3` Secret - that the strategy Pod reads (step 04 / 07). +- Reachable S3-compatible storage. The demo uses the in-cluster `Bucket` app (step 03), and steps 04 and 07 turn its coordinates into a `-backup-s3` Secret that the strategy Pod reads. Creating that Secret needs admin access, since no tenant role grants `create` on `secrets`. ## Steps diff --git a/examples/backups/nats/91-scenario-user-backup.md b/examples/backups/nats/91-scenario-user-backup.md index 5af74c5a9..adc5c983d 100644 --- a/examples/backups/nats/91-scenario-user-backup.md +++ b/examples/backups/nats/91-scenario-user-backup.md @@ -2,13 +2,12 @@ This scenario assumes the admin steps (`01-...`, `02-...`) have already run. +The user's own action here, at the tenant admin level, is the `BackupJob` in step 05, plus creating the `Bucket` and the `NATS`. Steps 03 and 04 as scripted need admin access: they read and create Secrets, wait on HelmReleases and the `StatefulSet`, and seed the stream through a CLI Pod, which no tenant role allows. The README's step table has the details. + ## Prerequisites - Tenant namespace (default: `tenant-test`). -- A Cozystack `Bucket` (step 03) and the `-backup-s3` Secret derived from - it (step 04). The generic `Job` strategy has no chart support to emit this - Secret, so the tenant creates it from the bucket's `BucketInfo` (see - `create_s3_secret` in `00-helpers.sh`). +- A Cozystack `Bucket` (step 03) and the `-backup-s3` Secret derived from it (step 04). The generic `Job` strategy has no chart support to emit this Secret, so step 04 creates it from the bucket's `BucketInfo` (see `create_s3_secret` in `00-helpers.sh`). Creating it needs admin access. - A `NATS` application with JetStream enabled and a stream holding data. ## Steps diff --git a/examples/backups/nats/92-scenario-user-restore.md b/examples/backups/nats/92-scenario-user-restore.md index 1dbd1cc35..5aefface0 100644 --- a/examples/backups/nats/92-scenario-user-restore.md +++ b/examples/backups/nats/92-scenario-user-restore.md @@ -2,6 +2,8 @@ Two restore variants are supported. +The user's own action in both variants, at the tenant admin level, is the `RestoreJob`, plus the second `NATS` in variant B. The scripts as written need admin access: variant A deletes and checks the stream through a CLI Pod, and variant B checks the stream the same way, creates the target's Secret and waits on its `HelmRelease` and `StatefulSet`, none of which a tenant role allows. The README's step table has the details. + ## A. In-place restore Restore back into the same NATS application. @@ -53,9 +55,6 @@ The script: - Both flows rely on the strategy template branching on `.Mode`. See `01-create-strategy.sh`. -- The tarball in object storage is not managed by the Cozystack `Backup` - lifecycle: deleting the `Backup` CR removes the reference but leaves the S3 - object in place. Tenants who need to reclaim space should delete the object - (or set a bucket lifecycle policy). +- The tarball in object storage is not managed by the Cozystack `Backup` lifecycle: deleting the `Backup` CR removes the reference but leaves the S3 object in place. Tenants who need to reclaim space should delete the object, or set a lifecycle rule on the bucket. A Simple or MultiZone Cozystack SeaweedFS applies such rules once a day only while its `lifecycle.enabled` is on, which is not the default; a Client instance applies none itself, so the SeaweedFS it connects to must have `lifecycle.enabled` on. Another object store applies them only if it implements bucket lifecycle. - `nats stream restore` recreates the stream's configuration from the snapshot; consumers are restored as captured at backup time. diff --git a/examples/backups/nats/README.md b/examples/backups/nats/README.md index 132526b84..30948e65e 100644 --- a/examples/backups/nats/README.md +++ b/examples/backups/nats/README.md @@ -30,12 +30,12 @@ driver, with tools you already have. | `00-helpers.sh` | Shared bash helpers, env defaults, and the `nats`/S3-secret helpers; sourced by every step. | n/a | | `01-create-strategy.sh` | Creates the cluster-scoped `Job` strategy (the nats-box `PodTemplateSpec`). | admin | | `02-create-backupclass.sh` | Maps `apps.cozystack.io/NATS` to that strategy, with `stream`/`natsUser` parameters. | admin | -| `03-create-bucket.sh` | Provisions a `Bucket` and caches its S3 coordinates into `.bucket-info.env` (chmod 600; raw access keys). `cleanup.sh` removes this file. | tenant | -| `04-create-nats.sh` | Provisions a `NATS` instance, creates the `-backup-s3` Secret, seeds a JetStream stream with sentinel messages. | tenant | +| `03-create-bucket.sh` | Provisions a `Bucket` and caches its S3 coordinates into `.bucket-info.env` (chmod 600; raw access keys). `cleanup.sh` removes this file. | **admin**. A tenant admin can create the `Bucket` itself, but the script also waits on its `HelmRelease` and COSI objects and reads the `bucket--backup` Secret; no tenant role grants access to `helmreleases` or `objectstorage.k8s.io`, or `get` on that Secret | +| `04-create-nats.sh` | Provisions a `NATS` instance, creates the `-backup-s3` Secret, seeds a JetStream stream with sentinel messages. | **admin**. A tenant admin can create the `NATS` itself, but the script also waits on its `HelmRelease` and `StatefulSet`, creates the Secret, and seeds the stream through a CLI Pod it execs into; no tenant role grants access to `helmreleases` or `statefulsets`, `create` on `secrets` or `pods`, or `pods/exec` | | `05-create-backupjob.sh` | Submits a `BackupJob` and waits for Succeeded. | tenant | -| `06-restore-in-place.sh` | Deletes the stream and restores it into the same instance via `RestoreJob`. | tenant | -| `07-restore-to-copy.sh` | Provisions a second `NATS` and restores into it via `RestoreJob.spec.targetApplicationRef`. | tenant | -| `cleanup.sh` | Removes everything created by the demo. | admin or tenant | +| `06-restore-in-place.sh` | Deletes the stream and restores it into the same instance via `RestoreJob`. | **admin**. A tenant admin can submit the `RestoreJob`, but the script deletes and checks the stream through the CLI Pod; no tenant role grants `create` on `pods` or `pods/exec` | +| `07-restore-to-copy.sh` | Provisions a second `NATS` and restores into it via `RestoreJob.spec.targetApplicationRef`. | **admin**, for the same reasons as step 04. The tenant admin's part is the second `NATS` and the `RestoreJob` | +| `cleanup.sh` | Removes everything created by the demo. | **admin**: it deletes Secrets, the `Backup`, and the cluster-scoped `BackupClass` and strategy, and no tenant role grants `delete` on any of them | | `run-all.sh` | Convenience runner that executes 01..07 in order. | demo | | `90-scenario-admin-prepare.md` | Narrative for the admin preparation steps. | docs | | `91-scenario-user-backup.md` | Narrative for the user backup flow. | docs | diff --git a/examples/backups/postgres/00-helpers.sh b/examples/backups/postgres/00-helpers.sh index fef4e7220..ac004e504 100755 --- a/examples/backups/postgres/00-helpers.sh +++ b/examples/backups/postgres/00-helpers.sh @@ -58,124 +58,10 @@ print_header() { echo -e "\n${MAGENTA}${BOLD}== $1 ==${NC}\n" >&2 } -# Wait until a JSONPath value on a resource matches the desired string. -# Optional 7th arg is a TERMINAL failure value: once the field reaches it the -# wait returns 1 immediately instead of polling to the timeout. BackupJob and -# RestoreJob settle on a terminal phase=Failed that never becomes Succeeded, so -# failing fast on it keeps wall-clock (and the snapshot Pod's log, before its -# TTL reaper fires) in reach. -wait_for_field() { - local resource_type="$1" - local resource_name="$2" - local jsonpath="$3" - local desired="$4" - local namespace="${5:-}" - local timeout="${6:-300}" - local fail_value="${7:-}" - - log_substep "Waiting for $resource_type/$resource_name $jsonpath to become '$desired'..." - local elapsed=0 - local ns_flag=() - [[ -n "$namespace" ]] && ns_flag=(-n "$namespace") - - while true; do - local current - current=$(kubectl get "$resource_type" "$resource_name" "${ns_flag[@]}" -o jsonpath="$jsonpath" 2>/dev/null || true) - if [[ "$current" == "$desired" ]]; then - log_success "$resource_type/$resource_name reached '$desired'" - return 0 - fi - if [[ -n "$fail_value" && "$current" == "$fail_value" ]]; then - log_error "$resource_type/$resource_name reached terminal '$current' (expected '$desired')" - return 1 - fi - if [[ $elapsed -ge $timeout ]]; then - log_error "Timeout waiting for $resource_type/$resource_name (current: '$current', expected: '$desired')" - return 1 - fi - sleep 5 - elapsed=$((elapsed + 5)) - done -} - -# Wait for a HelmRelease to become Ready, with an existence backstop (the -# apps controller creates the HR asynchronously, so a bare `kubectl wait` -# right after `kubectl apply` races it) and a fail-fast on Stalled=True — -# a stalled HR has exhausted its remediation retries and will never turn -# Ready, so polling to the timeout only hides the real error. -wait_hr_ready() { - local name="$1" - local timeout="${2:-300}" - local elapsed=0 - local lookup state seen=0 - - log_substep "Waiting for HelmRelease/$name to become Ready..." - while true; do - # --ignore-not-found makes an absent release exit 0, so a non-zero exit - # is kubectl failing to answer. Presence is read off the name line, - # because a warning on stderr lands in the same string. - if ! lookup=$(kubectl -n "$NAMESPACE" get hr "$name" --ignore-not-found -o name 2>&1); then - state=error - elif [[ $'\n'"$lookup"$'\n' != *"/$name"$'\n'* ]]; then - state=absent - else - state=present - seen=1 - local ready stalled - ready=$(kubectl -n "$NAMESPACE" get hr "$name" \ - -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}' || true) - if [[ "$ready" == "True" ]]; then - log_success "HelmRelease/$name is Ready" - return 0 - fi - stalled=$(kubectl -n "$NAMESPACE" get hr "$name" \ - -o jsonpath='{.status.conditions[?(@.type=="Stalled")].status}' || true) - if [[ "$stalled" == "True" ]]; then - log_error "HelmRelease/$name is Stalled (terminal):" - break - fi - fi - if [[ $elapsed -ge $timeout ]]; then - log_error "Timeout waiting for HelmRelease/$name to become Ready:" - case "$state" in - error) - echo " could not look up HelmRelease/$name: $lookup" >&2 - # Seen earlier: the reads below may answer where this lookup - # did not. - [[ $seen -eq 1 ]] || return 1 - ;; - absent) - if [[ $seen -eq 1 ]]; then - echo " HelmRelease/$name was deleted from $NAMESPACE while waiting" >&2 - else - echo " HelmRelease/$name never appeared in $NAMESPACE" >&2 - fi - return 1 - ;; - esac - break - fi - sleep 5 - elapsed=$((elapsed + 5)) - done - # Reached on Stalled or on timeout. Conditions and history rather than the - # Ready message alone: a failed install is retried on an interval, so Ready - # may describe the retry rather than the failure behind it. - kubectl -n "$NAMESPACE" get hr "$name" \ - -o jsonpath='{range .status.conditions[*]} {.type}={.status} ({.reason}): {.message}{"\n"}{end}' >&2 || true - local hist - if ! hist=$(kubectl -n "$NAMESPACE" get hr "$name" \ - -o jsonpath='{range .status.history[*]} history: {.status} {.chartVersion} {.lastDeployed}{"\n"}{end}'); then - echo " history: kubectl could not read it" >&2 - elif [[ -n "${hist//[[:space:]]/}" ]]; then - printf '%s\n' "$hist" >&2 - else - # A release with no history prints nothing and exits 0; say so, - # because a blank in a failure dump reads as a dump that broke. - echo " history: (none recorded)" >&2 - fi - return 1 -} +# wait_for_field, wait_hr_ready and wait_deleted live in one file shared by +# every backup walkthrough, so a fix to one reaches all of them. +# shellcheck source-path=SCRIPTDIR source=../_lib/wait-helpers.sh +source "$(dirname "${BASH_SOURCE[0]}")/../_lib/wait-helpers.sh" # Name of the primary pod of a cnpg.io Cluster (the one accepting writes). cnpg_primary_pod() { diff --git a/examples/backups/postgres/35-restorejob-in-place.yaml b/examples/backups/postgres/35-restorejob-in-place.yaml index 16d7253e7..933d9625d 100644 --- a/examples/backups/postgres/35-restorejob-in-place.yaml +++ b/examples/backups/postgres/35-restorejob-in-place.yaml @@ -6,7 +6,7 @@ # recovery, same as the to-copy variant in 45-restorejob-pitr.yaml (which the # e2e drives with a real, in-window timestamp). Uncomment and set a timestamp # inside your recoverable window - see 45-restorejob-pitr.yaml and -# docs/operations/backup-classes.md ("Point-in-time recovery") for how to find +# https://cozystack.io/docs/v1/operations/services/backup-classes/ ("Point-in-time recovery") for how to find # the earliest/latest restorable time. --- apiVersion: backups.cozystack.io/v1alpha1 diff --git a/examples/backups/postgres/45-restorejob-pitr.yaml b/examples/backups/postgres/45-restorejob-pitr.yaml index 7c9434f0c..b8e1e883d 100644 --- a/examples/backups/postgres/45-restorejob-pitr.yaml +++ b/examples/backups/postgres/45-restorejob-pitr.yaml @@ -11,7 +11,7 @@ # backup's completion and at/before the latest WAL shipped to object storage. # A target past the latest archived WAL cannot converge - the RestoreJob fails # with condition Ready=False/RecoveryTargetUnreachable instead of hanging. See -# docs/operations/backup-classes.md ("Point-in-time recovery") for how to +# https://cozystack.io/docs/v1/operations/services/backup-classes/ ("Point-in-time recovery") for how to # discover the earliest/latest restorable time. # # run-all.sh substitutes REPLACE_WITH_RECOVERY_TIME with a timestamp it captures diff --git a/examples/backups/postgres/run-all.sh b/examples/backups/postgres/run-all.sh index d2e249c01..83e7cfb7a 100755 --- a/examples/backups/postgres/run-all.sh +++ b/examples/backups/postgres/run-all.sh @@ -38,7 +38,9 @@ subst() { print_header "Step 00: Provision Bucket '${BUCKET_NAME}' in ${NAMESPACE}" kubectl -n "$NAMESPACE" apply -f "$SCRIPT_DIR/00-bucket.yaml" -wait_hr_ready "bucket-${BUCKET_NAME}" 300 +# 660s, above this generated release's 600s install timeout; see "Sizing an +# HR-Ready budget" in docs/agents/e2e-testing.md. +wait_hr_ready "bucket-${BUCKET_NAME}" 660 wait_for_field bucketclaims.objectstorage.k8s.io "bucket-${BUCKET_NAME}" \ '{.status.bucketReady}' true "$NAMESPACE" 300 wait_for_field bucketaccesses.objectstorage.k8s.io "bucket-${BUCKET_NAME}-backup" \ @@ -123,7 +125,9 @@ materialise_backup_secrets "$PG_SRC_NAME" print_header "Step 05b: Deploy source Postgres '${PG_SRC_NAME}' and wait for it to be healthy" subst 05-postgres-src.yaml | kubectl -n "$NAMESPACE" apply -f - -wait_hr_ready "postgres-${PG_SRC_NAME}" 360 +# 660s, above this generated release's 600s install timeout; see "Sizing an +# HR-Ready budget" in docs/agents/e2e-testing.md. +wait_hr_ready "postgres-${PG_SRC_NAME}" 660 wait_for_field clusters.postgresql.cnpg.io "$PG_SRC_CLUSTER" \ '{.status.phase}' 'Cluster in healthy state' "$NAMESPACE" 360 # The 'demo' database and 'app' user are created by the chart's init Job, not @@ -167,7 +171,8 @@ materialise_backup_secrets "$PG_TARGET_NAME" kubectl -n "$NAMESPACE" apply -f "$SCRIPT_DIR/30-postgres-target.yaml" # Let the target's first install settle before the RestoreJob driver suspends # its HelmRelease — suspending an HR mid-install races helm-controller. -wait_hr_ready "postgres-${PG_TARGET_NAME}" 360 +# 660s, as for the source above. +wait_hr_ready "postgres-${PG_TARGET_NAME}" 660 kubectl -n "$NAMESPACE" apply -f "$SCRIPT_DIR/40-restorejob-to-copy.yaml" wait_for_field restorejobs.backups.cozystack.io "$RESTOREJOB_TOCOPY_NAME" \ '{.status.phase}' Succeeded "$NAMESPACE" 1200 Failed diff --git a/examples/backups/rabbitmq/00-helpers.sh b/examples/backups/rabbitmq/00-helpers.sh index b61812e06..e283b9bac 100755 --- a/examples/backups/rabbitmq/00-helpers.sh +++ b/examples/backups/rabbitmq/00-helpers.sh @@ -64,120 +64,10 @@ print_header() { echo -e "\n${MAGENTA}${BOLD}== $1 ==${NC}\n" >&2 } -# Wait until a JSONPath value on a resource matches the desired string. -# Optional 7th arg is a TERMINAL failure value: once the field reaches it the -# wait returns 1 immediately instead of polling to the timeout. BackupJob and -# RestoreJob settle on a terminal phase=Failed that never becomes Succeeded, so -# failing fast on it keeps wall-clock in reach. -wait_for_field() { - local resource_type="$1" - local resource_name="$2" - local jsonpath="$3" - local desired="$4" - local namespace="${5:-}" - local timeout="${6:-300}" - local fail_value="${7:-}" - - log_substep "Waiting for $resource_type/$resource_name $jsonpath to become '$desired'..." - local elapsed=0 - local ns_flag=() - [[ -n "$namespace" ]] && ns_flag=(-n "$namespace") - - while true; do - local current - current=$(kubectl get "$resource_type" "$resource_name" "${ns_flag[@]}" -o jsonpath="$jsonpath" 2>/dev/null || true) - if [[ "$current" == "$desired" ]]; then - log_success "$resource_type/$resource_name reached '$desired'" - return 0 - fi - if [[ -n "$fail_value" && "$current" == "$fail_value" ]]; then - log_error "$resource_type/$resource_name reached terminal '$current' (expected '$desired')" - return 1 - fi - if [[ $elapsed -ge $timeout ]]; then - log_error "Timeout waiting for $resource_type/$resource_name (current: '$current', expected: '$desired')" - return 1 - fi - sleep 5 - elapsed=$((elapsed + 5)) - done -} - -# Wait for a HelmRelease to become Ready, with an existence backstop (the apps -# controller creates the HR asynchronously) and a fail-fast on Stalled=True. -wait_hr_ready() { - local name="$1" - local timeout="${2:-300}" - local elapsed=0 - local lookup state seen=0 - - log_substep "Waiting for HelmRelease/$name to become Ready..." - while true; do - # --ignore-not-found makes an absent release exit 0, so a non-zero exit - # is kubectl failing to answer. Presence is read off the name line, - # because a warning on stderr lands in the same string. - if ! lookup=$(kubectl -n "$NAMESPACE" get hr "$name" --ignore-not-found -o name 2>&1); then - state=error - elif [[ $'\n'"$lookup"$'\n' != *"/$name"$'\n'* ]]; then - state=absent - else - state=present - seen=1 - local ready stalled - ready=$(kubectl -n "$NAMESPACE" get hr "$name" \ - -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}' || true) - if [[ "$ready" == "True" ]]; then - log_success "HelmRelease/$name is Ready" - return 0 - fi - stalled=$(kubectl -n "$NAMESPACE" get hr "$name" \ - -o jsonpath='{.status.conditions[?(@.type=="Stalled")].status}' || true) - if [[ "$stalled" == "True" ]]; then - log_error "HelmRelease/$name is Stalled (terminal):" - break - fi - fi - if [[ $elapsed -ge $timeout ]]; then - log_error "Timeout waiting for HelmRelease/$name to become Ready:" - case "$state" in - error) - echo " could not look up HelmRelease/$name: $lookup" >&2 - # Seen earlier: the reads below may answer where this lookup - # did not. - [[ $seen -eq 1 ]] || return 1 - ;; - absent) - if [[ $seen -eq 1 ]]; then - echo " HelmRelease/$name was deleted from $NAMESPACE while waiting" >&2 - else - echo " HelmRelease/$name never appeared in $NAMESPACE" >&2 - fi - return 1 - ;; - esac - break - fi - sleep 5 - elapsed=$((elapsed + 5)) - done - # Reached on Stalled or on timeout. Conditions and history rather than the - # Ready message alone: a failed install is retried on an interval, so Ready - # may describe the retry rather than the failure behind it. - kubectl -n "$NAMESPACE" get hr "$name" \ - -o jsonpath='{range .status.conditions[*]} {.type}={.status} ({.reason}): {.message}{"\n"}{end}' >&2 || true - local hist - if ! hist=$(kubectl -n "$NAMESPACE" get hr "$name" \ - -o jsonpath='{range .status.history[*]} history: {.status} {.chartVersion} {.lastDeployed}{"\n"}{end}'); then - echo " history: kubectl could not read it" >&2 - elif [[ -n "${hist//[[:space:]]/}" ]]; then - printf '%s\n' "$hist" >&2 - else - # A release with no history prints nothing and exits 0; say so, - # because a blank in a failure dump reads as a dump that broke. - echo " history: (none recorded)" >&2 - fi - return 1 -} +# wait_for_field, wait_hr_ready and wait_deleted live in one file shared by +# every backup walkthrough, so a fix to one reaches all of them. +# shellcheck source-path=SCRIPTDIR source=../_lib/wait-helpers.sh +source "$(dirname "${BASH_SOURCE[0]}")/../_lib/wait-helpers.sh" # Wait until the rabbitmq.com/RabbitmqCluster CR reports AllReplicasReady=True # (the cluster-operator's own readiness signal — every server pod is up and the diff --git a/examples/backups/rabbitmq/03-rabbitmq-strategy.yaml b/examples/backups/rabbitmq/03-rabbitmq-strategy.yaml index a8ae0637f..1533ee092 100644 --- a/examples/backups/rabbitmq/03-rabbitmq-strategy.yaml +++ b/examples/backups/rabbitmq/03-rabbitmq-strategy.yaml @@ -92,8 +92,6 @@ spec: - name: s3-ca mountPath: /etc/ssl/rabbitmq-backup-ca readOnly: true - # command is load-bearing: the reused platform-migrations image's - # ENTRYPOINT is run-migrations.sh. command: ["/bin/sh", "-c"] args: - | diff --git a/examples/backups/rabbitmq/run-all.sh b/examples/backups/rabbitmq/run-all.sh index 668acd746..d947b3f48 100755 --- a/examples/backups/rabbitmq/run-all.sh +++ b/examples/backups/rabbitmq/run-all.sh @@ -43,7 +43,9 @@ print_header "RabbitMQ definitions backup/restore demo (namespace: $NAMESPACE)" # --- Bucket ------------------------------------------------------------------ print_header "Step 00: Provision Bucket '${BUCKET_NAME}' in ${NAMESPACE}" kubectl -n "$NAMESPACE" apply -f "$SCRIPT_DIR/00-bucket.yaml" -wait_hr_ready "bucket-${BUCKET_NAME}" 300 +# 660s, above this generated release's 600s install timeout; see "Sizing an +# HR-Ready budget" in docs/agents/e2e-testing.md. +wait_hr_ready "bucket-${BUCKET_NAME}" 660 wait_for_field bucketclaims.objectstorage.k8s.io "bucket-${BUCKET_NAME}" \ '{.status.bucketReady}' true "$NAMESPACE" 300 wait_for_field bucketaccesses.objectstorage.k8s.io "bucket-${BUCKET_NAME}-${BUCKET_USER}" \ diff --git a/examples/backups/redis/00-helpers.sh b/examples/backups/redis/00-helpers.sh index 390381ead..8c7272a57 100755 --- a/examples/backups/redis/00-helpers.sh +++ b/examples/backups/redis/00-helpers.sh @@ -17,6 +17,16 @@ export BOLD='\033[1m' # reaches lives in tenant-root, and the default e2e tenant-test is egress- # isolated from it). export NAMESPACE="${NAMESPACE:-tenant-root}" +# APP_KIND=Valkey runs the same round-trip against a Valkey app: it runs on the +# same RedisFailover operator, and its chart names every resource valkey- +# where the redis chart uses redis-. +export APP_KIND="${APP_KIND:-Redis}" +case "$APP_KIND" in + Redis) APP_PREFIX=redis-; APP_RESOURCE=redis ;; + Valkey) APP_PREFIX=valkey-; APP_RESOURCE=valkeys.apps.cozystack.io ;; + *) echo "APP_KIND must be Redis or Valkey, got '$APP_KIND'" >&2; exit 1 ;; +esac +export APP_PREFIX APP_RESOURCE export REDIS_NAME="${REDIS_NAME:-redis-test}" export REDIS_RESTORE_NAME="${REDIS_RESTORE_NAME:-redis-restore}" export BACKUPJOB_NAME="${BACKUPJOB_NAME:-redis-backup-job}" @@ -64,64 +74,29 @@ print_header() { echo -e "\n${MAGENTA}${BOLD}== $title ==${NC}\n" >&2 } -# Wait until a JSONPath value on a resource matches the desired string. An -# optional 7th arg is a TERMINAL failure value: once the field reaches it the -# wait returns 1 immediately instead of polling to the timeout (a BackupJob / -# RestoreJob settles on phase=Failed that never becomes Succeeded). -wait_for_field() { - local resource_type="$1" resource_name="$2" jsonpath="$3" desired="$4" - local namespace="${5:-}" timeout="${6:-300}" fail_value="${7:-}" - - log_substep "Waiting for $resource_type/$resource_name $jsonpath to become '$desired'..." - local elapsed=0 ns_flag=() - [[ -n "$namespace" ]] && ns_flag=(-n "$namespace") - while true; do - local current - current=$(kubectl get "$resource_type" "$resource_name" "${ns_flag[@]}" -o jsonpath="$jsonpath" || true) - [[ "$current" == "$desired" ]] && { log_success "$resource_type/$resource_name reached '$desired'"; return 0; } - [[ -n "$fail_value" && "$current" == "$fail_value" ]] && { log_error "$resource_type/$resource_name reached terminal '$current' (expected '$desired')"; return 1; } - (( elapsed >= timeout )) && { log_error "Timeout waiting for $resource_type/$resource_name (current: '$current', expected: '$desired')"; return 1; } - sleep 5 - elapsed=$((elapsed + 5)) - done -} - -# Wait for a HelmRelease to become Ready, with an existence backstop (the apps -# controller creates the HR asynchronously) and a fail-fast on Stalled=True. -wait_hr_ready() { - local name="$1" timeout="${2:-300}" elapsed=0 - log_substep "Waiting for HelmRelease/$name to become Ready..." - while true; do - if kubectl -n "$NAMESPACE" get hr "$name" >/dev/null 2>&1; then - local ready stalled - ready=$(kubectl -n "$NAMESPACE" get hr "$name" -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}' || true) - [[ "$ready" == "True" ]] && { log_success "HelmRelease/$name is Ready"; return 0; } - stalled=$(kubectl -n "$NAMESPACE" get hr "$name" -o jsonpath='{.status.conditions[?(@.type=="Stalled")].status}' || true) - [[ "$stalled" == "True" ]] && { log_error "HelmRelease/$name is Stalled (terminal)"; return 1; } - fi - (( elapsed >= timeout )) && { log_error "Timeout waiting for HelmRelease/$name to become Ready"; return 1; } - sleep 5 - elapsed=$((elapsed + 5)) - done -} +# wait_for_field, wait_hr_ready and wait_deleted live in one file shared by +# every backup walkthrough, so a fix to one reaches all of them. +# shellcheck source-path=SCRIPTDIR source=../_lib/wait-helpers.sh +source "$(dirname "${BASH_SOURCE[0]}")/../_lib/wait-helpers.sh" # The cozystack redis chart names its RedisFailover (hence the operator's rfr-/ -# rfs- Services and the -auth Secret) redis-, mirroring the strategy driver -# that derives the same base from .Release.Name. So app X's password lives in -# redis-X-auth. The chart renders that Secret only with authEnabled, so its -# absence reads as no password; any other error still fails the read. +# rfs- Services and the -auth Secret) redis-, the valkey chart valkey-, +# mirroring the strategy driver that derives the same base from .Release.Prefix +# and .Release.Name. So app X's password lives in X-auth. The chart +# renders that Secret only with authEnabled, so its absence reads as no +# password; any other error still fails the read. redis_pw() { - kubectl -n "$NAMESPACE" get secret "redis-$1-auth" --ignore-not-found -o jsonpath='{.data.password}' | base64 -d + kubectl -n "$NAMESPACE" get secret "${APP_PREFIX}$1-auth" --ignore-not-found -o jsonpath='{.data.password}' | base64 -d } # Run a redis-cli command against an application's CURRENT master. Master -# discovery asks a sentinel of the operator's rfs-redis- Deployment +# discovery asks a sentinel of the operator's rfs- Deployment # (master name "mymaster"), so a write always lands on the writable node even # after a failover. Args after the app name are passed verbatim to redis-cli. # redis_cmd redis-test SET sentinel:marker hello # # The command runs by `kubectl exec` in a sentinel Pod, whose image carries -# redis-cli. A throwaway `kubectl run -i` Pod is not usable here: its stdout +# redis-cli (the valkey image ships it as a link to valkey-cli). A throwaway `kubectl run -i` Pod is not usable here: its stdout # comes back over an attach, which only carries what the container writes after # the attach is established, and kubectl falls back to the Pod log only when # the attach fails. A redis-cli that finishes in between comes back as an @@ -134,7 +109,7 @@ redis_pw() { redis_cmd() { local app="$1" pw; shift pw=$(redis_pw "$app") - printf '%s\n' "$pw" | kubectl -n "$NAMESPACE" exec -i "deploy/rfs-redis-$app" -c sentinel -- sh -c ' + printf '%s\n' "$pw" | kubectl -n "$NAMESPACE" exec -i "deploy/rfs-${APP_PREFIX}$app" -c sentinel -- sh -c ' IFS= read -r pw || true addr=$(redis-cli -p 26379 sentinel get-master-addr-by-name mymaster) || exit 1 h=$(echo "$addr" | sed -n 1p); p=$(echo "$addr" | sed -n 2p) diff --git a/examples/backups/redis/01-create-redis.sh b/examples/backups/redis/01-create-redis.sh index 27a049d07..ecc4c6cb1 100755 --- a/examples/backups/redis/01-create-redis.sh +++ b/examples/backups/redis/01-create-redis.sh @@ -10,7 +10,7 @@ print_header "Step 01: Provision Redis '${REDIS_NAME}'" kubectl apply -f - <` resource below is then `valkey-`. - **Master discovery** goes through the operator's sentinel Service `rfs-redis-` (master name `mymaster`), so writes and the dump/replay always target the current master even after a failover. - **Faithful restore.** The restore loads the RDB into a throwaway local redis and replays what a real engine emits, so all logical databases (`SELECT` per db), stream last-ids and consumer groups survive — a merge onto db0 does not happen. - **Endpoint TLS.** The projected `endpoint` in `cozy-backups-creds` is always scheme-stripped, so the strategy prepends `https://` and the transport is always TLS (there is no `http://` path). It verifies against the image's system CA store by default — the platform bucket's ACME cert needs nothing more — honours a private CA from `backupStorage.endpointCASecretName` when set, and skips verification only when `backupStorage.insecureSkipTLSVerify: true` is set explicitly. diff --git a/examples/backups/redis/backupclass.yaml b/examples/backups/redis/backupclass.yaml index a990bbdf7..33dee84c4 100644 --- a/examples/backups/redis/backupclass.yaml +++ b/examples/backups/redis/backupclass.yaml @@ -1,4 +1,4 @@ -# Maps Kind=Redis to this demo's Redis strategy. BackupClass is cluster-scoped, +# Maps Kind=Redis and Kind=Valkey to this demo's Redis strategy. BackupClass is cluster-scoped, # so a single instance covers every namespace. Named redis-default so it does # not collide with the platform cozy-default class, which routes Redis to the # shipped cozy-default-redis strategy. @@ -16,3 +16,10 @@ spec: apiGroup: strategy.backups.cozystack.io kind: Redis name: redis-strategy-default + - application: + apiGroup: apps.cozystack.io + kind: Valkey + strategyRef: + apiGroup: strategy.backups.cozystack.io + kind: Redis + name: redis-strategy-default diff --git a/examples/backups/redis/cleanup.sh b/examples/backups/redis/cleanup.sh index bd6e1e140..81fc7ec68 100755 --- a/examples/backups/redis/cleanup.sh +++ b/examples/backups/redis/cleanup.sh @@ -16,8 +16,8 @@ kubectl -n "$NAMESPACE" delete restorejob "$RESTOREJOB_TOCOPY_NAME" --ignore-not kubectl -n "$NAMESPACE" delete restorejob "$RESTOREJOB_INPLACE_NAME" --ignore-not-found kubectl -n "$NAMESPACE" delete backupjob "$BACKUPJOB_NAME" --ignore-not-found kubectl -n "$NAMESPACE" delete backup "$BACKUPJOB_NAME" --ignore-not-found -kubectl -n "$NAMESPACE" delete redis "$REDIS_RESTORE_NAME" --ignore-not-found -kubectl -n "$NAMESPACE" delete redis "$REDIS_NAME" --ignore-not-found +kubectl -n "$NAMESPACE" delete "$APP_RESOURCE" "$REDIS_RESTORE_NAME" --ignore-not-found +kubectl -n "$NAMESPACE" delete "$APP_RESOURCE" "$REDIS_NAME" --ignore-not-found # Demo-owned backups plumbing: the BackupClass and strategy CR are cluster-scoped # (no -n). Deleting the Bucket releases its S3 objects and the projected keys. diff --git a/examples/backups/redis/redis-strategy.yaml b/examples/backups/redis/redis-strategy.yaml index 0768af97a..6533b0e38 100644 --- a/examples/backups/redis/redis-strategy.yaml +++ b/examples/backups/redis/redis-strategy.yaml @@ -28,7 +28,7 @@ spec: # presence — mirrors the shipped strategy. - name: redis-ca secret: - secretName: "redis-{{ .Release.Name }}.ca-cert" + secretName: '{{ .Release.Prefix | default "redis-" }}{{ .Release.Name }}.ca-cert' optional: true - name: s3-ca secret: @@ -51,7 +51,7 @@ spec: - name: REDIS_PASSWORD valueFrom: secretKeyRef: - name: "redis-{{ .Release.Name }}-auth" + name: '{{ .Release.Prefix | default "redis-" }}{{ .Release.Name }}-auth' key: password optional: true # S3 coordinates come from this demo's Bucket: the access keys are @@ -137,7 +137,7 @@ spec: RTLS="--tls --cacert /etc/redis-ca/ca.crt" fi - SENTINEL="rfs-redis-{{ .Release.Name }}" + SENTINEL="rfs-{{ .Release.Prefix | default "redis-" }}{{ .Release.Name }}" addr=$(redis-cli ${RTLS} -h "${SENTINEL}" -p 26379 sentinel get-master-addr-by-name mymaster) MHOST=$(echo "${addr}" | sed -n '1p') MPORT=$(echo "${addr}" | sed -n '2p') diff --git a/examples/backups/redis/run-all.sh b/examples/backups/redis/run-all.sh index 14d5d57ed..613803bdd 100755 --- a/examples/backups/redis/run-all.sh +++ b/examples/backups/redis/run-all.sh @@ -41,7 +41,9 @@ print_header "Redis backup/restore demo (namespace: $NAMESPACE)" # --- Bucket ------------------------------------------------------------------ print_header "Step 00: Provision Bucket '${BUCKET_NAME}' in ${NAMESPACE}" kubectl -n "$NAMESPACE" apply -f "$SCRIPT_DIR/bucket.yaml" -wait_hr_ready "bucket-${BUCKET_NAME}" 300 +# 660s, above this generated release's 600s install timeout; see "Sizing an +# HR-Ready budget" in docs/agents/e2e-testing.md. +wait_hr_ready "bucket-${BUCKET_NAME}" 660 wait_for_field bucketclaims.objectstorage.k8s.io "bucket-${BUCKET_NAME}" \ '{.status.bucketReady}' true "$NAMESPACE" 300 wait_for_field bucketaccesses.objectstorage.k8s.io "bucket-${BUCKET_NAME}-${BUCKET_USER}" \ diff --git a/examples/backups/vmdisk/00-helpers.sh b/examples/backups/vmdisk/00-helpers.sh new file mode 100755 index 000000000..9bb2b046e --- /dev/null +++ b/examples/backups/vmdisk/00-helpers.sh @@ -0,0 +1,44 @@ +#!/bin/bash +# Helper functions and variables for the VMDisk backup/restore demo. +# Source this file in other scripts: source "$(dirname "$0")/00-helpers.sh" + +# ANSI color codes +export RED='\033[0;31m' +export GREEN='\033[0;32m' +export YELLOW='\033[1;33m' +export MAGENTA='\033[0;35m' +export CYAN='\033[0;36m' +export WHITE='\033[1;37m' +export NC='\033[0m' +export BOLD='\033[1m' + +# Default settings +export NAMESPACE="${NAMESPACE:-tenant-root}" +# The platform ships the SeaweedFS-backed BackupStorageLocation as cozy-default +# (packages/system/backupstrategy-controller). Point the demo/e2e strategy at it +# by default so the flow works out of the box on a backups-enabled cluster; +# override for an external S3 whose BSL carries a different name. +export BACKUP_STORAGE_LOCATION="${BACKUP_STORAGE_LOCATION:-cozy-default}" + +# Logging functions (output to stderr to avoid polluting captured output) +log_info() { echo -e "${CYAN}ℹ${NC} $*" >&2; } +log_success() { echo -e "${GREEN}✔${NC} $*" >&2; } +log_warning() { echo -e "${YELLOW}⚠${NC} $*" >&2; } +log_error() { echo -e "${RED}✖${NC} $*" >&2; } +log_step() { echo -e "\n${MAGENTA}${BOLD}▶ $*${NC}" >&2; } +log_command() { echo -e "${WHITE} \$ $*${NC}" >&2; } +log_substep() { echo -e "${CYAN} → $*${NC}" >&2; } + +separator() { + echo -e "\n${CYAN}────────────────────────────────────────────────────────────${NC}\n" >&2 +} + +print_header() { + local title="$1" + echo -e "\n${MAGENTA}${BOLD}== ${title} ==${NC}\n" >&2 +} + +# wait_for_field, wait_hr_ready and wait_deleted live in one file shared by +# every backup walkthrough, so a fix to one reaches all of them. +# shellcheck source-path=SCRIPTDIR source=../_lib/wait-helpers.sh +source "$(dirname "${BASH_SOURCE[0]}")/../_lib/wait-helpers.sh" diff --git a/examples/backups/vmdisk/01-create-strategy.sh b/examples/backups/vmdisk/01-create-strategy.sh new file mode 100755 index 000000000..d881b35d3 --- /dev/null +++ b/examples/backups/vmdisk/01-create-strategy.sh @@ -0,0 +1,63 @@ +#!/bin/bash +# Step 01: Create the Velero backup/restore strategy for a standalone VMDisk. +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +source "$SCRIPT_DIR/00-helpers.sh" + +print_header "Step 1: Create VMDisk Velero strategy" + +log_step "Creating Velero strategy 'vmdisk-backup-strategy'..." +log_command "kubectl apply -f - (Velero strategy: vmdisk-backup-strategy)" + +# A standalone VMDisk is just an HelmRelease + a DataVolume-backed PVC (+ its +# configmaps), all labelled app.kubernetes.io/instance: vm-disk-. Unlike a +# VMInstance there is no VirtualMachine / VMI / launcher pod to capture. With +# snapshotMoveData the CSI data mover streams the volume through the +# BackupStorageLocation, so no VolumeSnapshotLocation is required (matching the +# platform's own cozy-default-velero-vmdisk strategy). +kubectl apply -f - <<'EOF' +apiVersion: strategy.backups.cozystack.io/v1alpha1 +kind: Velero +metadata: + name: vmdisk-backup-strategy +spec: + template: + restoreSpec: + existingResourcePolicy: update + includedNamespaces: + - '{{ .Application.metadata.namespace }}' + orLabelSelectors: + - matchLabels: + app.kubernetes.io/instance: 'vm-disk-{{ .Application.metadata.name }}' + - matchLabels: + apps.cozystack.io/application.kind: '{{ .Application.kind }}' + apps.cozystack.io/application.name: '{{ .Application.metadata.name }}' + includedResources: + - helmreleases.helm.toolkit.fluxcd.io + - persistentvolumeclaims + - configmaps + includeClusterResources: false + spec: + includedNamespaces: + - '{{ .Application.metadata.namespace }}' + orLabelSelectors: + - matchLabels: + app.kubernetes.io/instance: 'vm-disk-{{ .Application.metadata.name }}' + - matchLabels: + apps.cozystack.io/application.kind: '{{ .Application.kind }}' + apps.cozystack.io/application.name: '{{ .Application.metadata.name }}' + includedResources: + - helmreleases.helm.toolkit.fluxcd.io + - persistentvolumeclaims + - configmaps + includeClusterResources: false + storageLocation: '{{ .Parameters.backupStorageLocationName }}' + snapshotVolumes: true + snapshotMoveData: true + ttl: 720h0m0s + itemOperationTimeout: 24h0m0s +EOF + +log_success "Velero strategy created" +echo -e "\n${GREEN}${BOLD}Next step:${NC} ./02-create-backupclass.sh" >&2 diff --git a/examples/backups/vmdisk/02-create-backupclass.sh b/examples/backups/vmdisk/02-create-backupclass.sh new file mode 100755 index 000000000..4c4bac79b --- /dev/null +++ b/examples/backups/vmdisk/02-create-backupclass.sh @@ -0,0 +1,33 @@ +#!/bin/bash +# Step 02: Create a BackupClass binding VMDisk to the Velero strategy. +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +source "$SCRIPT_DIR/00-helpers.sh" + +print_header "Step 2: Create BackupClass" + +log_step "Creating BackupClass 'vmdisk-velero'..." +log_command "kubectl apply -f - (BackupClass: vmdisk-velero)" + +# BackupClass is cluster-scoped; a single instance covers every namespace. +kubectl apply -f - <&2 diff --git a/examples/backups/vmdisk/03-create-vmdisk.sh b/examples/backups/vmdisk/03-create-vmdisk.sh new file mode 100755 index 000000000..aad26a6be --- /dev/null +++ b/examples/backups/vmdisk/03-create-vmdisk.sh @@ -0,0 +1,43 @@ +#!/bin/bash +# Step 03: Create a standalone VMDisk and wait for it to be ready to back up. +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +source "$SCRIPT_DIR/00-helpers.sh" + +print_header "Step 3: Create VMDisk 'backup-src'" + +log_step "Creating VMDisk 'backup-src' in namespace $NAMESPACE..." +log_info "Imports the Ubuntu Noble cloud image into a 5Gi ${VMI_DISK_STORAGE_CLASS:-replicated} disk" +log_command "kubectl apply -f - (VMDisk: backup-src)" + +kubectl apply -f - <&2 diff --git a/examples/backups/vmdisk/04-create-backupjob.sh b/examples/backups/vmdisk/04-create-backupjob.sh new file mode 100755 index 000000000..a0dc8ac6e --- /dev/null +++ b/examples/backups/vmdisk/04-create-backupjob.sh @@ -0,0 +1,41 @@ +#!/bin/bash +# Step 04: Back up the standalone VMDisk via a BackupJob. +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +source "$SCRIPT_DIR/00-helpers.sh" + +print_header "Step 4: Create BackupJob" + +log_step "Creating BackupJob 'vmdisk-backup' in namespace $NAMESPACE..." +log_command "kubectl apply -f - (BackupJob: vmdisk-backup)" + +kubectl apply -f - <&2 || true +echo -e "\n${GREEN}${BOLD}Next step:${NC} ./05-restore-in-place.sh" >&2 diff --git a/examples/backups/vmdisk/05-restore-in-place.sh b/examples/backups/vmdisk/05-restore-in-place.sh new file mode 100755 index 000000000..f15c50521 --- /dev/null +++ b/examples/backups/vmdisk/05-restore-in-place.sh @@ -0,0 +1,183 @@ +#!/bin/bash +# Step 05: Restore the standalone VMDisk in-place from its backup. +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +source "$SCRIPT_DIR/00-helpers.sh" + +print_header "Step 5: Restore VMDisk In-Place" + +PVC=vm-disk-backup-src +CONSUMER=vm-disk-backup-src-restore-consumer + +orig_uid=$(kubectl -n "$NAMESPACE" get pvc "$PVC" -o jsonpath='{.metadata.uid}') +[[ -n "$orig_uid" ]] || { log_error "PVC $PVC has no uid before the restore"; exit 1; } +log_info "PVC $PVC before restore: uid $orig_uid" + +log_step "Creating RestoreJob 'vmdisk-restore-in-place' in namespace $NAMESPACE..." +log_info "In-place restore: the original PVC is renamed and the disk is restored from backup" +log_command "kubectl apply -f - (RestoreJob: vmdisk-restore-in-place)" + +# The controller suspends the vm-disk- HelmRelease, deletes its DataVolume +# and (keepOriginalPVC) renames the live PVC to -orig-; Velero then +# creates a fresh PVC under the original name for the data mover to populate. +kubectl apply -f - <-orig- before restoring +EOF + +log_success "RestoreJob created" + +# On a WaitForFirstConsumer StorageClass the Velero data mover does not start +# until a scheduled Pod has picked a node for the restored PVC (Velero's +# WaitPVCConsumed). A VMInstance restore gets that from the virt-launcher Pod; a +# detached disk has no consumer, so stand in for the VM that would attach it. +# Only once the new PVC exists: a Pod mounting the original would pin it with +# pvc-protection and block the rename. +start_consumer() { + local mode volume mount + mode=$(kubectl -n "$NAMESPACE" get pvc "$PVC" -o jsonpath='{.spec.volumeMode}') + if [[ "$mode" == "Block" ]]; then + mount='volumeDevices: [{name: disk, devicePath: /dev/disk0}]' + else + mount='volumeMounts: [{name: disk, mountPath: /disk}]' + fi + volume="{name: disk, persistentVolumeClaim: {claimName: $PVC}}" + log_info "Starting consumer Pod $CONSUMER for the restored PVC ($mode)" + kubectl apply -f - <&2 +done +log_success "restorejob/vmdisk-restore-in-place reached 'Succeeded'" + +kubectl -n "$NAMESPACE" delete pod "$CONSUMER" --ignore-not-found --timeout=120s + +# Neither the restore-name label nor a new uid proves the data moved: Velero's +# existingResourcePolicy: update stamps the label on a PVC it only patched, and +# CDI recreating the disk would also give it a new uid. The DataDownload check +# below does; the uid and the -orig- PVC show the original was kept aside. +log_step "Verifying the PVC was recreated from the backup..." +wait_for_field pvc "$PVC" '{.status.phase}' Bound "$NAMESPACE" 120 +new_uid=$(kubectl -n "$NAMESPACE" get pvc "$PVC" -o jsonpath='{.metadata.uid}') +[[ "$new_uid" != "$orig_uid" ]] || { + log_error "PVC $PVC still has its pre-restore uid $orig_uid — the restore did not recreate it" + exit 1 +} +restore_label=$(kubectl -n "$NAMESPACE" get pvc "$PVC" \ + -o "jsonpath={.metadata.labels.velero\.io/restore-name}") +[[ -n "$restore_label" ]] || { + log_error "PVC $PVC carries no velero.io/restore-name label — Velero did not restore it" + exit 1 +} +all_pvcs=$(kubectl -n "$NAMESPACE" get pvc -o name) +[[ "$all_pvcs" == *"persistentvolumeclaim/${PVC}-orig-"* ]] || { + log_error "no ${PVC}-orig-* PVC — keepOriginalPVC did not rename the original disk" + exit 1 +} +# The DataDownload carries the same restore-name label as the PVC; one that +# Completed having written bytes is what shows the data mover filled the disk. +downloads=$(kubectl -n cozy-velero get datadownloads.velero.io -l "velero.io/restore-name=${restore_label}" \ + -o jsonpath='{range .items[*]}{.status.phase} {.status.progress.bytesDone}{"\n"}{end}') +grep -Eq '^Completed [1-9][0-9]*$' <<<"$downloads" || { + log_error "no Completed DataDownload with data for restore ${restore_label} — the data mover did not restore $PVC (got: ${downloads:-none})" + exit 1 +} + +log_step "Waiting for the restored VMDisk to become Ready again..." +# The HelmRelease was Ready before the controller suspended it, and that +# condition outlives the restore; only once Flux has reconciled the restored +# spec does Ready describe the restored release. +hr_generation=$(kubectl -n "$NAMESPACE" get hr vm-disk-backup-src -o jsonpath='{.metadata.generation}') +wait_for_field hr vm-disk-backup-src '{.status.observedGeneration}' "$hr_generation" "$NAMESPACE" 120 +wait_hr_ready vm-disk-backup-src 180 + +# The restore deleted the DataVolume, and a restored release matches its chart +# and values, so Flux does not recreate it: the next Helm upgrade does, usually +# a platform update long after the restore. Force that upgrade here. CDI must +# admit a DataVolume over the claim Velero restored and adopt it as populated; +# refusing it leaves the release failed on every upgrade from then on, and +# re-importing it would overwrite the restored data. +log_step "Forcing a Helm upgrade so the restored VMDisk recreates its DataVolume..." +force_at=$(date -u +%Y-%m-%dT%H:%M:%SZ) +kubectl -n "$NAMESPACE" annotate hr vm-disk-backup-src --overwrite \ + "reconcile.fluxcd.io/requestedAt=${force_at}" "reconcile.fluxcd.io/forceAt=${force_at}" +wait_for_field hr vm-disk-backup-src '{.status.lastHandledForceAt}' "$force_at" "$NAMESPACE" 180 +wait_hr_ready vm-disk-backup-src 180 +wait_for_field datavolume vm-disk-backup-src '{.status.phase}' Succeeded "$NAMESPACE" 120 Failed +read -r adopted_uid owner_kind < <(kubectl -n "$NAMESPACE" get pvc "$PVC" \ + -o jsonpath='{.metadata.uid} {.metadata.ownerReferences[?(@.controller==true)].kind}') || true +[[ "${adopted_uid:-}" == "$new_uid" ]] || { + log_error "PVC $PVC changed uid from $new_uid to '${adopted_uid:-}' — the DataVolume replaced the restored disk instead of adopting it" + exit 1 +} +[[ "${owner_kind:-}" == "DataVolume" ]] || { + log_error "PVC $PVC is controlled by '${owner_kind:-nothing}', not by its DataVolume — CDI did not adopt the restored disk" + exit 1 +} + +kubectl get restorejob vmdisk-restore-in-place -n "$NAMESPACE" -o wide >&2 || true +log_success "Restore completed; VMDisk 'backup-src' recreated from backup (${restore_label}, uid ${new_uid}), Bound and Ready" diff --git a/examples/backups/vmdisk/README.md b/examples/backups/vmdisk/README.md new file mode 100644 index 000000000..3f67d81ac --- /dev/null +++ b/examples/backups/vmdisk/README.md @@ -0,0 +1,29 @@ +# VMDisk backup/restore example + +This directory shows how to back up and restore a standalone Cozystack `VMDisk` (a HelmRelease plus a DataVolume-backed PVC, with no VMInstance attached) using the cluster's `Velero` backup strategy driver. Each `BackupJob` drives a Velero CSI-snapshot backup whose data mover (kopia) streams the LINSTOR block volume to S3; each in-place `RestoreJob` recreates the disk from that artefact. + +The numbered scripts run in order (or via `run-all.sh`): + +1. `01-create-strategy.sh` — a `Velero` strategy for the `VMDisk` kind. +2. `02-create-backupclass.sh` — a `BackupClass` binding `VMDisk` to it. +3. `03-create-vmdisk.sh` — a standalone `VMDisk`, waited until imported. +4. `04-create-backupjob.sh` — an ad-hoc `BackupJob`, waited to `Succeeded`. +5. `05-restore-in-place.sh` — an in-place `RestoreJob`, then asserts that the PVC was recreated from the backup: it has a new uid, carries Velero's `velero.io/restore-name` label, and the original survives as `-orig-`. + +`cleanup.sh` tears everything down non-interactively. + +## In-place restore + +The driver prepares a `VMDisk` restore target the same way it does a VMInstance disk: it suspends the `vm-disk-` HelmRelease and deletes its DataVolume (so Flux/CDI do not recreate the PVC and race the data mover), and, with `keepOriginalPVC: true`, renames the live PVC to `-orig-` so that Velero creates a fresh PVC under the original name. `cleanup.sh` resumes the HelmRelease and reclaims the renamed PVC. + +A disk that a running VM mounts cannot be restored in place: the `RestoreJob` fails before it changes anything and names the Pod that holds the disk. Stop the VM, or restore the VMInstance instead. + +If the restore fails after this preparation, nothing is rolled back. The failure message and a Warning event name the HelmRelease that preparation suspended and the `-orig-` PVC that holds the original data. If Velero got as far as restoring the HelmRelease it is no longer suspended, and Flux may already have recreated the disk; with no restored PVC under the disk's name, CDI imports a fresh disk there. Either way, check what the disk holds, and restore again or bind the original PV back to a PVC under the disk's name if it is not what you expect. + +## Detached disks and WaitForFirstConsumer + +On a StorageClass with `volumeBindingMode: WaitForFirstConsumer`, such as the `local` class the CI lane uses, the Velero data mover does not start until a scheduled Pod has selected a node for the restored PVC. A VMInstance restore gets that from its virt-launcher Pod. A detached disk has no consumer, so its `RestoreJob` stays `Running` until something mounts the PVC, and fails once Velero's expose timeout passes. `05-restore-in-place.sh` therefore starts a minimal `pause` Pod on the restored PVC, standing in for the VM that would attach the disk, and deletes it once the restore has succeeded. On a real cluster, attaching the disk to a VMInstance does the same. + +## Overrides + +Environment variables (see `00-helpers.sh`) tune the flow: `NAMESPACE`, `BACKUP_STORAGE_LOCATION` (defaults to the platform `cozy-default` BSL), `VMI_DISK_STORAGE_CLASS` (defaults to `replicated`; set it to your cluster's class), and the `IMPORT_WAIT` / `BACKUP_WAIT` / `RESTORE_WAIT` budgets. `hack/e2e-chainsaw/vminstance/` drives this directory as the `vmdisk-2-backup-roundtrip` e2e test. diff --git a/examples/backups/vmdisk/cleanup.sh b/examples/backups/vmdisk/cleanup.sh new file mode 100755 index 000000000..d66af5301 --- /dev/null +++ b/examples/backups/vmdisk/cleanup.sh @@ -0,0 +1,70 @@ +#!/bin/bash +# Clean up all resources created by the demo. Non-interactive: safe to call from +# the e2e harness's finally block, and idempotent (a no-op when a gated-out run +# created nothing). --ignore-not-found returns success for an absent resource but +# does NOT mask a stuck delete: the delete still blocks and, under set -e, a +# teardown that never settles fails this script instead of leaking state into the +# next run (docs/agents/e2e-testing.md convention 4). +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +source "$SCRIPT_DIR/00-helpers.sh" + +print_header "Cleanup Demo Resources" + +# The controller suspends the VMDisk's HelmRelease before a restore and never +# resumes it. A restore that gets as far as Velero clears it, but one that fails +# earlier leaves it suspended, so resume it best-effort BEFORE deleting the +# RestoreJob (same reasoning as examples/backups/vmi/cleanup.sh). +if kubectl -n "$NAMESPACE" get hr vm-disk-backup-src >/dev/null 2>&1; then + log_substep "Resuming HelmRelease vm-disk-backup-src (no-op if not suspended)..." + kubectl -n "$NAMESPACE" patch hr vm-disk-backup-src --type=merge \ + -p '{"spec":{"suspend":false}}' >/dev/null || true +fi + +# Namespaced request objects first. Deleting the cozystack BackupJob/RestoreJob +# and Backup CRs cascades to the Velero Backup/Restore the controller created. +log_step "Deleting RestoreJob..." +kubectl delete restorejob vmdisk-restore-in-place -n "$NAMESPACE" --ignore-not-found + +log_step "Deleting BackupJob and Backup..." +kubectl delete backupjob vmdisk-backup -n "$NAMESPACE" --ignore-not-found +kubectl delete backup vmdisk-backup -n "$NAMESPACE" --ignore-not-found + +separator + +log_step "Deleting VMDisk and its PVC..." +kubectl delete pod vm-disk-backup-src-restore-consumer -n "$NAMESPACE" --ignore-not-found +kubectl delete vmdisk backup-src -n "$NAMESPACE" --ignore-not-found +kubectl delete pvc -n "$NAMESPACE" \ + -l app.kubernetes.io/instance=vm-disk-backup-src --ignore-not-found + +# keepOriginalPVC renamed the pre-restore PVC to -orig- with a bare +# ObjectMeta (no labels/owner) and flipped its PV to Retain, so the label delete +# above misses it. Reclaim it by name and flip the PV back to Delete BEFORE +# removing the PVC so the CSI provisioner reclaims the LINSTOR volume rather than +# stranding it. Let the lookup and patch fail the script (see the vmi cleanup). +if ! all_pvcs=$(kubectl -n "$NAMESPACE" get pvc -o name 2>&1); then + log_error "cannot list PVCs to reclaim orphaned disks: $all_pvcs" + exit 1 +fi +orig_pvcs=$(printf '%s\n' "$all_pvcs" | grep -E '/vm-disk-backup-src-orig-' || true) +for pvc in $orig_pvcs; do + pv=$(kubectl -n "$NAMESPACE" get "$pvc" -o jsonpath='{.spec.volumeName}') + log_substep "Reclaiming orphaned ${pvc#*/} and its LINSTOR volume..." + if [[ -n "$pv" ]]; then + kubectl patch pv "$pv" --type=merge \ + -p '{"spec":{"persistentVolumeReclaimPolicy":"Delete"}}' >/dev/null + fi + kubectl -n "$NAMESPACE" delete "$pvc" --ignore-not-found +done + +separator + +log_step "Deleting BackupClass and Velero strategy..." +kubectl delete backupclass vmdisk-velero --ignore-not-found +kubectl delete velero.strategy.backups.cozystack.io vmdisk-backup-strategy --ignore-not-found + +separator + +log_success "Cleanup complete" diff --git a/examples/backups/vmdisk/run-all.sh b/examples/backups/vmdisk/run-all.sh new file mode 100755 index 000000000..0956ad807 --- /dev/null +++ b/examples/backups/vmdisk/run-all.sh @@ -0,0 +1,43 @@ +#!/bin/bash +# Convenience runner + e2e harness for the standalone VMDisk backup/restore demo. +# +# Runs the numbered steps 01..05 a human reads, in order, non-interactively, +# stopping on the first failure (set -e). This is the SAME sequence the docs walk +# through, so the documented demo and the automated test can never drift. +# +# Flow: Velero strategy -> BackupClass -> a standalone VMDisk (waits imported) -> +# ad-hoc BackupJob (waits Succeeded) -> in-place RestoreJob (waits Succeeded, then +# waits for the restored disk to be Bound + Ready). +# +# Override NAMESPACE / BACKUP_STORAGE_LOCATION via the environment; see +# 00-helpers.sh. hack/e2e-chainsaw/vminstance/ drives this file as the +# vmdisk-2-backup-roundtrip e2e test, run un-gated in CI. +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +source "$SCRIPT_DIR/00-helpers.sh" + +print_header "VMDisk Backup & Restore Demo" +log_info "Namespace: ${NAMESPACE} BackupStorageLocation: ${BACKUP_STORAGE_LOCATION}" + +SCRIPTS=( + "01-create-strategy.sh" + "02-create-backupclass.sh" + "03-create-vmdisk.sh" + "04-create-backupjob.sh" + "05-restore-in-place.sh" +) + +for script in "${SCRIPTS[@]}"; do + if [[ -x "$SCRIPT_DIR/$script" ]]; then + "$SCRIPT_DIR/$script" + separator + else + log_error "Script not found or not executable: $script" + exit 1 + fi +done + +print_header "Demo Complete" +log_success "All steps completed successfully!" +log_info "To clean up resources: ./cleanup.sh" diff --git a/examples/backups/vmi/00-helpers.sh b/examples/backups/vmi/00-helpers.sh index 384054952..30ca161f3 100755 --- a/examples/backups/vmi/00-helpers.sh +++ b/examples/backups/vmi/00-helpers.sh @@ -15,7 +15,11 @@ export BOLD='\033[1m' # Default settings export NAMESPACE="${NAMESPACE:-tenant-root}" -export BACKUP_STORAGE_LOCATION="${BACKUP_STORAGE_LOCATION:-default}" +# The platform ships the SeaweedFS-backed BackupStorageLocation as cozy-default +# (packages/system/backupstrategy-controller). Point the demo/e2e strategies at +# it by default so the flow works out of the box on a backups-enabled cluster; +# override for an external S3 whose BSL carries a different name. +export BACKUP_STORAGE_LOCATION="${BACKUP_STORAGE_LOCATION:-cozy-default}" # Logging functions (output to stderr to avoid polluting captured output) log_info() { @@ -65,38 +69,10 @@ resource_exists() { fi } -# Wait for a resource field to reach a desired value -wait_for_field() { - local resource_type="$1" - local resource_name="$2" - local jsonpath="$3" - local desired="$4" - local namespace="${5:-}" - local timeout="${6:-300}" - - log_substep "Waiting for $resource_type/$resource_name $jsonpath to become '$desired'..." - - local elapsed=0 - local ns_flag="" - [[ -n "$namespace" ]] && ns_flag="-n $namespace" - - while true; do - local current - # shellcheck disable=SC2086 - current=$(kubectl get "$resource_type" "$resource_name" $ns_flag -o jsonpath="$jsonpath" 2>/dev/null || true) - if [[ "$current" == "$desired" ]]; then - log_success "$resource_type/$resource_name reached '$desired'" - return 0 - fi - if [[ $elapsed -ge $timeout ]]; then - log_error "Timeout waiting for $resource_type/$resource_name (current: '$current', expected: '$desired')" - return 1 - fi - sleep 5 - elapsed=$((elapsed + 5)) - echo -n "." >&2 - done -} +# wait_for_field, wait_hr_ready and wait_deleted live in one file shared by +# every backup walkthrough, so a fix to one reaches all of them. +# shellcheck source-path=SCRIPTDIR source=../_lib/wait-helpers.sh +source "$(dirname "${BASH_SOURCE[0]}")/../_lib/wait-helpers.sh" # Print a separator line separator() { diff --git a/examples/backups/vmi/01-create-strategies.sh b/examples/backups/vmi/01-create-strategies.sh index 78aa34d31..a12809c54 100755 --- a/examples/backups/vmi/01-create-strategies.sh +++ b/examples/backups/vmi/01-create-strategies.sh @@ -70,8 +70,11 @@ spec: - controllerrevisions.apps includeClusterResources: false storageLocation: '{{ .Parameters.backupStorageLocationName }}' - volumeSnapshotLocations: - - '{{ .Parameters.backupStorageLocationName }}' + # No volumeSnapshotLocations: with snapshotMoveData the CSI data mover + # uploads the volume data through the BackupStorageLocation, so a VSL of + # the same name is not required (and referencing a non-existent one fails + # the backup). The platform's own cozy-default-velero-vminstance strategy + # omits it for the same reason. snapshotVolumes: true snapshotMoveData: true ttl: 720h0m0s @@ -123,8 +126,8 @@ spec: - configmaps includeClusterResources: false storageLocation: '{{ .Parameters.backupStorageLocationName }}' - volumeSnapshotLocations: - - '{{ .Parameters.backupStorageLocationName }}' + # See the VMInstance strategy above: snapshotMoveData routes volume data + # through the BackupStorageLocation, so no VolumeSnapshotLocation is needed. snapshotVolumes: true snapshotMoveData: true ttl: 720h0m0s diff --git a/examples/backups/vmi/03-create-vmdisk.sh b/examples/backups/vmi/03-create-vmdisk.sh index 89d598867..27234a09d 100755 --- a/examples/backups/vmi/03-create-vmdisk.sh +++ b/examples/backups/vmi/03-create-vmdisk.sh @@ -7,8 +7,13 @@ source "$SCRIPT_DIR/00-helpers.sh" print_header "Step 3: Create VMDisk" +# Image + size are overridable so the same flow can run a heavy ubuntu demo or a +# tiny cirros disk for a lightweight e2e (see hack/e2e-chainsaw/vminstance). +VMI_IMAGE_URL="${VMI_IMAGE_URL:-https://cloud-images.ubuntu.com/noble/current/noble-server-cloudimg-amd64.img}" +VMI_DISK_STORAGE="${VMI_DISK_STORAGE:-20Gi}" + log_step "Creating VMDisk 'ubuntu-source' in namespace $NAMESPACE..." -log_info "This will download the Ubuntu Noble cloud image (~700MB)" +log_info "Importing ${VMI_IMAGE_URL} into a ${VMI_DISK_STORAGE} disk" log_command "kubectl apply -f - (VMDisk: ubuntu-source)" kubectl apply -f - < @@ -34,11 +39,24 @@ log_success "VMInstance created" separator +# Wait for the VM to be fully booted before backing it up. Backing up a VM that +# is still importing its disk or has not started yields an incomplete, useless +# backup — so, like the etcd/postgres source steps, block on readiness here. +# The Ubuntu cloud image download (~700MB) plus nested KubeVirt boot is slow, +# hence the generous 900s bound. +log_step "Waiting for the VMInstance to boot (HelmRelease + VirtualMachine Ready)..." +wait_hr_ready vm-instance-test "${IMPORT_WAIT:-900}" +log_command "kubectl -n $NAMESPACE wait virtualmachine.kubevirt.io/vm-instance-test --for=condition=Ready" +kubectl -n "$NAMESPACE" wait virtualmachine.kubevirt.io/vm-instance-test \ + --for=condition=Ready --timeout="${VMI_BOOT_WAIT:-600}s" + +separator + log_step "Verifying VMInstance..." log_command "kubectl get vminstance test -n $NAMESPACE" kubectl get vminstance test -n "$NAMESPACE" separator -log_success "VMInstance is ready" +log_success "VMInstance is running and ready to back up" echo -e "\n${GREEN}${BOLD}Next step:${NC} ./05-create-backupjob.sh" diff --git a/examples/backups/vmi/05-create-backupjob.sh b/examples/backups/vmi/05-create-backupjob.sh index 581490a47..095e0b169 100755 --- a/examples/backups/vmi/05-create-backupjob.sh +++ b/examples/backups/vmi/05-create-backupjob.sh @@ -30,7 +30,11 @@ log_success "BackupJob created" separator log_step "Waiting for BackupJob to complete..." -wait_for_field backupjob test-backup '{.status.phase}' Succeeded "$NAMESPACE" 600 +# Default 1800s: the Velero CSI data mover copies the whole VM disk (20Gi) to S3, +# far heavier than a database dump. Overridable (BACKUP_WAIT) so the CI harness +# can bound it well under the Chainsaw op timeout on its tiny guest. Fail fast if +# the job flips to Failed. +wait_for_field backupjob test-backup '{.status.phase}' Succeeded "$NAMESPACE" "${BACKUP_WAIT:-1800}" Failed separator diff --git a/examples/backups/vmi/06-restore-in-place.sh b/examples/backups/vmi/06-restore-in-place.sh index ea424ed56..95cd5e1ee 100755 --- a/examples/backups/vmi/06-restore-in-place.sh +++ b/examples/backups/vmi/06-restore-in-place.sh @@ -7,6 +7,9 @@ source "$SCRIPT_DIR/00-helpers.sh" print_header "Step 6: Restore VMInstance In-Place" +orig_uid=$(kubectl -n "$NAMESPACE" get pvc vm-disk-ubuntu-source -o jsonpath='{.metadata.uid}') +[[ -n "$orig_uid" ]] || { log_error "PVC vm-disk-ubuntu-source has no uid before the restore"; exit 1; } + log_step "Creating RestoreJob 'restore-in-place-test' in namespace $NAMESPACE..." log_info "In-place restore: the VM will be halted, PVCs renamed, and data restored from backup" log_command "kubectl apply -f - (RestoreJob: restore-in-place-test)" @@ -25,8 +28,8 @@ spec: kind: VMInstance name: test options: - failIfTargetExists: true # if true, restore will fail when the target resource already exists - keepOriginalPVC: true # renames original VMI PVC before restore to `-orig-`, only for in-place restore + failIfTargetExists: true # only enforced for restore-to-copy; a no-op for in-place, whose source is expected to exist + keepOriginalPVC: true # renames original VMI PVC before restore to -orig-, only for in-place restore keepOriginalIpAndMac: true # restores original IP and MAC address of VMI via OVN annotations EOF @@ -35,7 +38,7 @@ log_success "RestoreJob created" separator log_step "Waiting for RestoreJob to complete..." -wait_for_field restorejob restore-in-place-test '{.status.phase}' Succeeded "$NAMESPACE" 600 +wait_for_field restorejob restore-in-place-test '{.status.phase}' Succeeded "$NAMESPACE" "${RESTORE_WAIT:-1800}" Failed separator @@ -45,5 +48,49 @@ kubectl get restorejob restore-in-place-test -n "$NAMESPACE" -o wide separator -log_success "In-place restore completed successfully" +# The RestoreJob reaching Succeeded means Velero re-created the objects; wait +# for the restored VM to come back before checking where its disk came from. +log_step "Waiting for the restored VMInstance to boot again..." +log_command "kubectl -n $NAMESPACE wait virtualmachine.kubevirt.io/vm-instance-test --for=condition=Ready" +kubectl -n "$NAMESPACE" wait virtualmachine.kubevirt.io/vm-instance-test \ + --for=condition=Ready --timeout="${VMI_BOOT_WAIT:-600}s" + +# VirtualMachine Ready is the virt-launcher Pod's readiness, reported before the +# guest runs, so it cannot tell a restored disk from a blank one, and this +# platform offers no guest-side signal (serial-console logging is disabled +# cluster-wide, the cirros guest has no qemu-guest-agent). Prove provenance on the +# PVC instead. Neither the restore-name label nor a new uid proves the data +# moved (existingResourcePolicy: update stamps the label on a PVC it only +# patched, and CDI recreating the disk gives it a new uid); the DataDownload +# check below does, and the uid and -orig- PVC show the original was kept aside. +log_step "Verifying the VM booted off a disk the restore recreated from the backup..." +wait_for_field pvc vm-disk-ubuntu-source '{.status.phase}' Bound "$NAMESPACE" 120 +new_uid=$(kubectl -n "$NAMESPACE" get pvc vm-disk-ubuntu-source -o jsonpath='{.metadata.uid}') +[[ "$new_uid" != "$orig_uid" ]] || { + log_error "PVC vm-disk-ubuntu-source still has its pre-restore uid $orig_uid — the restore did not recreate it" + exit 1 +} +restore_label=$(kubectl -n "$NAMESPACE" get pvc vm-disk-ubuntu-source \ + -o "jsonpath={.metadata.labels.velero\.io/restore-name}") +[[ -n "$restore_label" ]] || { + log_error "restored VM disk PVC carries no velero.io/restore-name label — Velero did not restore it" + exit 1 +} +all_pvcs=$(kubectl -n "$NAMESPACE" get pvc -o name) +[[ "$all_pvcs" == *"persistentvolumeclaim/vm-disk-ubuntu-source-orig-"* ]] || { + log_error "no vm-disk-ubuntu-source-orig-* PVC — keepOriginalPVC did not rename the original disk" + exit 1 +} +# The DataDownload carries the same restore-name label as the PVC; one that +# Completed having written bytes is what shows the data mover filled the disk. +downloads=$(kubectl -n cozy-velero get datadownloads.velero.io -l "velero.io/restore-name=${restore_label}" \ + -o jsonpath='{range .items[*]}{.status.phase} {.status.progress.bytesDone}{"\n"}{end}') +grep -Eq '^Completed [1-9][0-9]*$' <<<"$downloads" || { + log_error "no Completed DataDownload with data for restore ${restore_label} — the data mover did not restore vm-disk-ubuntu-source (got: ${downloads:-none})" + exit 1 +} + +separator + +log_success "In-place restore completed; VM disk recreated from backup (${restore_label}, uid ${new_uid}) and the VM is Running off it" echo -e "\n${GREEN}${BOLD}Next step:${NC} ./07-restore-to-copy.sh" diff --git a/examples/backups/vmi/07-restore-to-copy.sh b/examples/backups/vmi/07-restore-to-copy.sh index 9b84ce558..d7f7b87fb 100755 --- a/examples/backups/vmi/07-restore-to-copy.sh +++ b/examples/backups/vmi/07-restore-to-copy.sh @@ -40,7 +40,7 @@ spec: options: # runtime.RawExtension, typed based on targetApplicationRef and current controller implementation (for additional restore options) targetNamespace: ${TARGET_NAMESPACE} # when set to a different namespace, triggers cross-namespace restore via Velero namespaceMapping failIfTargetExists: true # if true, restore will fail when the target resource already exists - keepOriginalPVC: false # renames original VMI PVC before restore to `-orig-`, only for in-place restore + keepOriginalPVC: false # renames original VMI PVC before restore to -orig-, only for in-place restore keepOriginalIpAndMac: false # restores original IP and MAC address of VMI via OVN annotations EOF @@ -49,7 +49,7 @@ log_success "RestoreJob created" separator log_step "Waiting for RestoreJob to complete..." -wait_for_field restorejob restore-to-copy-test '{.status.phase}' Succeeded "$NAMESPACE" 600 +wait_for_field restorejob restore-to-copy-test '{.status.phase}' Succeeded "$NAMESPACE" 1800 Failed separator diff --git a/examples/backups/vmi/cleanup.sh b/examples/backups/vmi/cleanup.sh index 5965c3f03..3351ce9ee 100755 --- a/examples/backups/vmi/cleanup.sh +++ b/examples/backups/vmi/cleanup.sh @@ -1,5 +1,10 @@ #!/bin/bash -# Clean up all resources created by the demo +# Clean up all resources created by the demo. Non-interactive: safe to call from +# the e2e harness's finally block, and idempotent (a no-op when a gated-out run +# created nothing). --ignore-not-found returns success for an absent resource +# but does NOT mask a stuck delete: the delete still blocks and, under set -e, +# a teardown that never settles fails this script instead of leaking state into +# the next run (docs/agents/e2e-testing.md convention 4). set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" @@ -9,62 +14,74 @@ TARGET_NAMESPACE="${TARGET_NAMESPACE:-tenant-root-copy}" print_header "Cleanup Demo Resources" -log_warning "This script will delete all resources created during the demo" -echo -e "\n${YELLOW}The following will be deleted:${NC}" -echo " - RestoreJobs (restore-in-place-test, restore-to-copy-test)" -echo " - BackupJob (test-backup) and associated Backup" -echo " - VMInstance (test)" -echo " - VMDisk (ubuntu-source)" -echo " - BackupClass (velero)" -echo " - Velero strategies (vminstance-strategy, vmdisk-strategy)" -echo " - Target namespace ($TARGET_NAMESPACE)" -echo "" - -read -p "Continue? (y/N): " -n 1 -r -echo -if [[ ! $REPLY =~ ^[Yy]$ ]]; then - log_info "Cancelled" - exit 0 -fi - -separator +# The driver suspends the VMInstance/VMDisk HelmReleases while a RestoreJob runs +# and never resumes them (suspendHelmRelease only ever sets suspend=true), so an +# aborted or completed restore leaves them suspended. Resume best-effort BEFORE +# deleting the RestoreJobs — deleting a RestoreJob without resuming strands the +# app suspended (same reasoning as examples/backups/postgres/cleanup.sh). +for hr in vm-instance-test vm-disk-ubuntu-source; do + if kubectl -n "$NAMESPACE" get hr "$hr" >/dev/null 2>&1; then + log_substep "Resuming HelmRelease $hr (no-op if not suspended)..." + kubectl -n "$NAMESPACE" patch hr "$hr" --type=merge \ + -p '{"spec":{"suspend":false}}' >/dev/null || true + fi +done +# Namespaced request objects first. Deleting the cozystack BackupJob/RestoreJob +# and Backup CRs cascades to the Velero Backup/Restore the controller created. log_step "Deleting RestoreJobs..." -kubectl delete restorejob restore-to-copy-test -n "$NAMESPACE" 2>/dev/null || log_warning "RestoreJob restore-to-copy-test not found" -kubectl delete restorejob restore-in-place-test -n "$NAMESPACE" 2>/dev/null || log_warning "RestoreJob restore-in-place-test not found" - -separator +kubectl delete restorejob restore-to-copy-test restore-in-place-test \ + -n "$NAMESPACE" --ignore-not-found log_step "Deleting BackupJob and Backup..." -kubectl delete backupjob test-backup -n "$NAMESPACE" 2>/dev/null || log_warning "BackupJob test-backup not found" -kubectl delete backup test-backup -n "$NAMESPACE" 2>/dev/null || log_warning "Backup test-backup not found" +kubectl delete backupjob test-backup -n "$NAMESPACE" --ignore-not-found +kubectl delete backup test-backup -n "$NAMESPACE" --ignore-not-found separator -log_step "Deleting VMInstance..." -kubectl delete vminstance test -n "$NAMESPACE" 2>/dev/null || log_warning "VMInstance test not found" +log_step "Deleting VMInstance and VMDisk..." +kubectl delete vminstance test -n "$NAMESPACE" --ignore-not-found +kubectl delete vmdisk ubuntu-source -n "$NAMESPACE" --ignore-not-found -log_step "Deleting VMDisk..." -kubectl delete vmdisk ubuntu-source -n "$NAMESPACE" 2>/dev/null || log_warning "VMDisk ubuntu-source not found" +# keepOriginalPVC renames the VMInstance's disk PVC to -orig- with a +# bare ObjectMeta (no labels, no ownerRefs) and flips its PV to Retain. Nothing +# above reclaims it: the app delete does not own it and no label selector matches +# it, so under skipDelete a LINSTOR volume and a Released PV leak on every run. +# List loudly (a failed query must abort, not silently skip the reclaim it exists +# for); grep's no-match stays tolerant. +if ! all_pvcs=$(kubectl -n "$NAMESPACE" get pvc -o name 2>&1); then + log_error "cannot list PVCs to reclaim orphaned disks: $all_pvcs" + exit 1 +fi +orig_pvcs=$(printf '%s\n' "$all_pvcs" | grep -E '/vm-disk-ubuntu-source-orig-' || true) +for pvc in $orig_pvcs; do + # Flip the retained PV back to Delete BEFORE removing the PVC, so releasing it + # makes the CSI provisioner call DeleteVolume and reclaim the LINSTOR volume — + # deleting the PV object alone would drop the record and strand the volume. Let + # both the lookup and the patch fail the script: swallowing them would delete + # the PVC anyway and strand the volume with no PVC left to find it by. + pv=$(kubectl -n "$NAMESPACE" get "$pvc" -o jsonpath='{.spec.volumeName}') + log_substep "Reclaiming orphaned ${pvc#*/} and its LINSTOR volume..." + if [[ -n "$pv" ]]; then + kubectl patch pv "$pv" --type=merge \ + -p '{"spec":{"persistentVolumeReclaimPolicy":"Delete"}}' >/dev/null + fi + kubectl -n "$NAMESPACE" delete "$pvc" --ignore-not-found +done separator -log_step "Deleting BackupClass..." -kubectl delete backupclass velero 2>/dev/null || log_warning "BackupClass velero not found" - -separator - -log_step "Deleting Velero strategies..." -kubectl delete velero.strategy.backups.cozystack.io vminstance-strategy 2>/dev/null || log_warning "Strategy vminstance-strategy not found" -kubectl delete velero.strategy.backups.cozystack.io vmdisk-strategy 2>/dev/null || log_warning "Strategy vmdisk-strategy not found" +# Cluster-scoped BackupClass + strategies. +log_step "Deleting BackupClass and Velero strategies..." +kubectl delete backupclass velero --ignore-not-found +kubectl delete velero.strategy.backups.cozystack.io \ + vminstance-strategy vmdisk-strategy --ignore-not-found separator log_step "Deleting target namespace..." -kubectl delete namespace "$TARGET_NAMESPACE" 2>/dev/null || log_warning "Namespace $TARGET_NAMESPACE not found" +kubectl delete namespace "$TARGET_NAMESPACE" --ignore-not-found separator log_success "Cleanup complete" -log_info "All demo resources have been deleted" -echo -e "\n${GREEN}${BOLD}To re-run the demo:${NC} ./01-create-strategies.sh" diff --git a/examples/backups/vmi/run-all.sh b/examples/backups/vmi/run-all.sh index b58f4b9d3..2585bdb30 100755 --- a/examples/backups/vmi/run-all.sh +++ b/examples/backups/vmi/run-all.sh @@ -1,15 +1,25 @@ #!/bin/bash -# Run the full VMInstance backup/restore demo sequentially +# Convenience runner + e2e harness for the VMInstance backup/restore demo. +# +# Runs the numbered steps 01..07 a human reads, in order, non-interactively, +# stopping on the first failure (set -e). This is the SAME sequence the docs +# walk through, so the documented flow and the automated test can never drift. +# +# Flow: Velero strategies -> BackupClass -> VMDisk + VMInstance (waits until the +# VM is booted) -> ad-hoc BackupJob (waits Succeeded) -> in-place RestoreJob +# (waits Succeeded, waits for the VM to boot again) -> cross-namespace to-copy +# RestoreJob (waits Succeeded). +# +# Override NAMESPACE / BACKUP_STORAGE_LOCATION / TARGET_NAMESPACE via the +# environment; see 00-helpers.sh. hack/e2e-chainsaw/vminstance/ drives this file +# as the vminstance-2-backup-roundtrip e2e test, run un-gated in CI. set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" source "$SCRIPT_DIR/00-helpers.sh" print_header "VMInstance Backup & Restore Demo" - -log_info "This script will run all demo steps sequentially" -log_info "There will be a pause between steps for observation" -echo "" +log_info "Namespace: ${NAMESPACE} BackupStorageLocation: ${BACKUP_STORAGE_LOCATION}" SCRIPTS=( "01-create-strategies.sh" @@ -18,29 +28,18 @@ SCRIPTS=( "04-create-vminstance.sh" "05-create-backupjob.sh" "06-restore-in-place.sh" - "07-restore-to-copy.sh" ) - -echo -e "${CYAN}Demo steps:${NC}" -for i in "${!SCRIPTS[@]}"; do - echo " $((i+1)). ${SCRIPTS[$i]}" -done -echo "" - -read -p "Run demo? (y/N): " -n 1 -r -echo -if [[ ! $REPLY =~ ^[Yy]$ ]]; then - log_info "Cancelled" - exit 0 +# Cross-namespace to-copy restore is the heaviest step (a second full VM in a +# fresh namespace). SKIP_RESTORE_TO_COPY=1 drops it — used by the lightweight CI +# round-trip, which proves backup + in-place restore is enough. +if [[ "${SKIP_RESTORE_TO_COPY:-0}" != "1" ]]; then + SCRIPTS+=("07-restore-to-copy.sh") fi -separator - for script in "${SCRIPTS[@]}"; do if [[ -x "$SCRIPT_DIR/$script" ]]; then "$SCRIPT_DIR/$script" separator - wait_for_enter else log_error "Script not found or not executable: $script" exit 1 @@ -50,13 +49,13 @@ done print_header "Demo Complete" log_success "All steps completed successfully!" -echo "" log_info "What was demonstrated:" -echo " 1. Created Velero backup strategies for VMInstance and VMDisk" -echo " 2. Created BackupClass binding strategies to application types" -echo " 3. Provisioned a VMDisk and VMInstance" -echo " 4. Created a backup of the VMInstance via BackupJob" -echo " 5. Restored the VMInstance in-place" -echo " 6. Restored the VMInstance to a copy in a different namespace" -echo "" +echo " 1. Created Velero backup strategies for VMInstance and VMDisk" >&2 +echo " 2. Created BackupClass binding strategies to application types" >&2 +echo " 3. Provisioned a VMDisk and VMInstance" >&2 +echo " 4. Created a backup of the VMInstance via BackupJob" >&2 +echo " 5. Restored the VMInstance in-place" >&2 +if [[ "${SKIP_RESTORE_TO_COPY:-0}" != "1" ]]; then + echo " 6. Restored the VMInstance to a copy in a different namespace" >&2 +fi log_info "To clean up resources: ./cleanup.sh" diff --git a/examples/backups/vmi/scenario-user-restore.md b/examples/backups/vmi/scenario-user-restore.md index 1d35b22b0..9e7eb059c 100644 --- a/examples/backups/vmi/scenario-user-restore.md +++ b/examples/backups/vmi/scenario-user-restore.md @@ -32,13 +32,28 @@ The backup controller performs the following steps automatically: Velero restores them. 5. **Creates Velero Restore** — restores resources from the backup with: - `existingResourcePolicy: update` to overwrite existing objects. - - Resource modifier rules that add `cdi.kubevirt.io/allowClaimAdoption=true` - to restored PVCs so CDI can adopt them. + - Resource modifier rules that add `cdi.kubevirt.io/allowClaimAdoption=true` to restored PVCs. CDI does not read that annotation on a PVC: what lets it adopt the restored PVC is the same annotation, which the vm-disk chart sets on the DataVolume Flux recreates once the HelmRelease resumes. - OVN IP/MAC annotations to preserve the VM's network identity. After the Velero Restore completes, the HelmReleases resume and the VM boots with the restored disk data while retaining its original IP and MAC addresses. +### Reclaiming the kept disks + +With `keepOriginalPVC: true`, the default, step 3 switches each disk's PV to the `Retain` reclaim policy so that it outlives the PVC it is renamed from. Nothing removes the `-orig` PVCs or sets the policy back afterwards: they stay until an operator deletes them. + +The policy the PV had before the restore is recorded in the `backups.cozystack.io/original-reclaim-policy` annotation, on the PV and on the `-orig` PVC. Set it back on the PV before deleting the `-orig` PVC, or a PV that was `Delete` stays `Retain` once released and its volume is never reclaimed. A PVC renamed by an older controller carries no annotation; the snippet then leaves the PV on `Retain` for you to decide. + +```bash +PVC=vm-disk-ubuntu-source-orig-1a2b +PV=$(kubectl -n "$NAMESPACE" get pvc "$PVC" -o jsonpath='{.spec.volumeName}') +POLICY=$(kubectl get pv "$PV" -o jsonpath='{.metadata.annotations.backups\.cozystack\.io/original-reclaim-policy}') +kubectl patch pv "$PV" --type=merge -p "{\"spec\":{\"persistentVolumeReclaimPolicy\":\"${POLICY:-Retain}\"}}" +kubectl -n "$NAMESPACE" delete pvc "$PVC" +``` + +The `` is derived from the RestoreJob name, so an `-orig` PVC left behind by a deleted RestoreJob takes the name a new RestoreJob of the same name would use. That RestoreJob fails before it halts the VM, naming the PVC, rather than restoring without keeping the current disk. Reclaim the leftover PVC as above, or give the new RestoreJob another name. + ## Method 2: Cross-Namespace Restore (Copy) ```bash diff --git a/go.mod b/go.mod index 46105c1d5..cb49f9f24 100644 --- a/go.mod +++ b/go.mod @@ -16,28 +16,31 @@ require ( github.com/go-logr/logr v1.4.4 github.com/go-logr/zapr v1.3.0 github.com/go-task/slim-sprig/v3 v3.0.0 + github.com/google/cel-go v0.29.2 + github.com/minio/minio-go/v7 v7.0.98 github.com/onsi/ginkgo/v2 v2.33.0 github.com/onsi/gomega v1.43.1 github.com/prometheus/client_golang v1.24.1 github.com/robfig/cron/v3 v3.0.1 github.com/spf13/cobra v1.10.2 + github.com/spf13/pflag v1.0.10 github.com/vmware-tanzu/velero v1.18.3 go.uber.org/zap v1.28.0 gomodules.xyz/jsonpatch/v2 v2.5.0 - k8s.io/api v0.35.0 - k8s.io/apiextensions-apiserver v0.35.0 - k8s.io/apimachinery v0.35.2 - k8s.io/apiserver v0.35.0 - k8s.io/client-go v0.35.0 - k8s.io/component-base v0.35.0 + k8s.io/api v0.37.1 + k8s.io/apiextensions-apiserver v0.37.1 + k8s.io/apimachinery v0.37.1 + k8s.io/apiserver v0.37.1 + k8s.io/client-go v0.37.1 + k8s.io/component-base v0.37.1 k8s.io/klog/v2 v2.140.0 - k8s.io/kube-openapi v0.0.0-20250910181357-589584f1c912 + k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad k8s.io/utils v0.0.0-20260707023825-cf1189d6abe3 sigs.k8s.io/container-object-storage-interface-api v0.1.0 - sigs.k8s.io/controller-runtime v0.23.1 + sigs.k8s.io/controller-runtime v0.25.1 sigs.k8s.io/gateway-api v1.4.1 sigs.k8s.io/randfill v1.0.0 - sigs.k8s.io/structured-merge-diff/v6 v6.3.2-0.20260122202528-d9cc6641c482 + sigs.k8s.io/structured-merge-diff/v6 v6.4.2 sigs.k8s.io/yaml v1.6.0 ) @@ -62,6 +65,7 @@ require ( github.com/fsnotify/fsnotify v1.10.1 // indirect github.com/fxamacker/cbor/v2 v2.9.4 // indirect github.com/gkampitakis/go-snaps v0.5.23 // indirect + github.com/go-ini/ini v1.67.0 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-openapi/jsonpointer v1.0.1 // indirect github.com/go-openapi/jsonreference v1.0.2 // indirect @@ -79,41 +83,41 @@ require ( github.com/go-openapi/swag/yamlutils v0.29.2 // indirect github.com/go-openapi/testify/enable/yaml/v2 v2.8.0 // indirect github.com/go-openapi/testify/v2 v2.8.0 // indirect - github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/protobuf v1.5.4 // indirect - github.com/google/btree v1.1.3 // indirect - github.com/google/cel-go v0.29.2 // indirect github.com/google/gnostic-models v0.7.1 // indirect github.com/google/go-cmp v0.7.0 // indirect github.com/google/pprof v0.0.0-20260906184651-6331bc6350fe // indirect github.com/google/uuid v1.6.0 // indirect github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 // indirect + github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus v1.1.0 // indirect github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.4 // indirect - github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/compress v1.20.0 // indirect + github.com/klauspost/cpuid/v2 v2.3.0 // indirect + github.com/klauspost/crc32 v1.3.0 // indirect github.com/kylelemons/godebug v1.1.0 // indirect + github.com/minio/crc64nvme v1.1.1 // indirect + github.com/minio/md5-simd v1.1.2 // indirect github.com/moby/spdystream v0.5.1 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect - github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f // indirect + github.com/philhofer/fwd v1.2.0 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/prometheus/client_model v0.6.3 // indirect github.com/prometheus/common v0.71.0 // indirect github.com/prometheus/procfs v0.22.0 // indirect github.com/rogpeppe/go-internal v1.16.0 // indirect + github.com/rs/xid v1.6.0 // indirect github.com/sirupsen/logrus v1.10.2 // indirect - github.com/spf13/pflag v1.0.10 // indirect - github.com/stretchr/objx v0.5.3 // indirect github.com/tidwall/match v1.2.0 // indirect + github.com/tinylib/msgp v1.6.1 // indirect github.com/x448/float16 v0.8.4 // indirect - go.etcd.io/etcd/api/v3 v3.6.15 // indirect - go.etcd.io/etcd/client/pkg/v3 v3.6.15 // indirect - go.etcd.io/etcd/client/v3 v3.6.15 // indirect - go.etcd.io/etcd/server/v3 v3.6.15 // indirect + go.etcd.io/etcd/api/v3 v3.7.0 // indirect + go.etcd.io/etcd/client/pkg/v3 v3.7.0 // indirect + go.etcd.io/etcd/client/v3 v3.7.0 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.71.0 // indirect go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 // indirect @@ -145,10 +149,8 @@ require ( gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect - k8s.io/kms v0.35.0 // indirect + k8s.io/kms v0.37.1 // indirect + k8s.io/streaming v0.37.1 // indirect sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.36.0 // indirect sigs.k8s.io/json v0.0.0-20260909141634-11ed52e25bc5 // indirect ) - -// See: issues.k8s.io/135537 -replace k8s.io/apimachinery => github.com/cozystack/apimachinery v0.0.0-20260710062224-763e1451713b diff --git a/go.sum b/go.sum index 90ca65b3c..667ca71ee 100644 --- a/go.sum +++ b/go.sum @@ -22,8 +22,6 @@ github.com/coreos/go-semver v0.3.1 h1:yi21YpKnrx1gt5R+la8n5WgS0kCrsPp33dmEyHReZr github.com/coreos/go-semver v0.3.1/go.mod h1:irMmmIw/7yzSRPWryHsK7EYSg09caPQL03VsM8rvUec= github.com/coreos/go-systemd/v22 v22.7.0 h1:LAEzFkke61DFROc7zNLX/WA2i5J8gYqe0rSj9KI28KA= github.com/coreos/go-systemd/v22 v22.7.0/go.mod h1:xNUYtjHu2EDXbsxz1i41wouACIwT7Ybq9o0BQhMwD0w= -github.com/cozystack/apimachinery v0.0.0-20260710062224-763e1451713b h1:/GZSE+YqN4eHfTYbzCFMNiGxxsCa0xm+JuN72yQOuXw= -github.com/cozystack/apimachinery v0.0.0-20260710062224-763e1451713b/go.mod h1:jQCgFZFR1F4Ik7hvr2g84RTJSZegBc8yHgFWKn//hns= github.com/cozystack/cozystack-scheduler/pkg/apis v0.1.1 h1:9uLa/8J4lRx3sNuaVH8UZqgZvnskHATPo5GxEKh0iSM= github.com/cozystack/cozystack-scheduler/pkg/apis v0.1.1/go.mod h1:kPeS9YPB4ENbvNINEkkp0SX8FB+gvwoOHGOHMT3Tg9Y= github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= @@ -63,6 +61,8 @@ github.com/gkampitakis/ciinfo v0.3.4 h1:5eBSibVuSMbb/H6Elc0IIEFbkzCJi3lm94n0+U7Z github.com/gkampitakis/ciinfo v0.3.4/go.mod h1:1NIwaOcFChN4fa/B0hEBdAb6npDlFL8Bwx4dfRLRqAo= github.com/gkampitakis/go-snaps v0.5.23 h1:okh5QR48zpUjpWtu65AtqxdCY8huJq+dEDuUzd1PuKg= github.com/gkampitakis/go-snaps v0.5.23/go.mod h1:uy3lVzCCRRsAwYqSocyw5fY8xRLCYEfqoOJNxr8HonM= +github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A= +github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= @@ -108,14 +108,10 @@ github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1v github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM= github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= -github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= -github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= -github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg= -github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= github.com/google/cel-go v0.29.2 h1:ZtDxkeiMmz0mxbKDYiNkE5Lk7V5edMRcaaDf2jX002k= github.com/google/cel-go v0.29.2/go.mod h1:X0bD6iVNR8pkROSOoHVdgTkzmRcosof7WQqCD6wcMc8= github.com/google/gnostic-models v0.7.1 h1:SisTfuFKJSKM5CPZkffwi6coztzzeYUhc3v4yxLWH8c= @@ -131,13 +127,10 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 h1:JeSE6pjso5THxAzdVpqr6/geYxZytqFMBCOtn/ujyeo= github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674/go.mod h1:r4w70xmWCQKmi1ONH4KIaBptdivuRPyosB9RmPlGEwA= -github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 h1:+9834+KizmvFV7pXQGSXQTsaWhq2GjuNUt0aUU0YBYw= -github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus v1.0.1 h1:qnpSQwGEnkcRpTqNOIR6bJbR0gAorgP9CSALpRcKoAA= -github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus v1.0.1/go.mod h1:lXGCsh6c22WGtjr+qGHj1otzZpV/1kwTMAqkwZsnWRU= +github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus v1.1.0 h1:QGLs/O40yoNK9vmy4rhUGBVyMf1lISBGtXRpsu/Qu/o= +github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus v1.1.0/go.mod h1:hM2alZsMUni80N33RBe6J0e423LB+odMj7d3EMP9l20= github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.4 h1:9ZJYjPEJpcleIKcqysXOo14NLQYwu23fzmKRFpIjPjc= github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.4/go.mod h1:0xydIeg2omQ9DH6zYMP24Kk57793rnLUvP8fwdbFvz8= -github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 h1:Ovs26xHkKqVztRpIrF/92BcuyuQ/YW4NSIpoGtfXNho= -github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 h1:/Tnpcb2E0Pz/tN9s3bfEY2Q8ePCEX9iuS+cneUwncnw= github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0/go.mod h1:zOBXOsUaBSjKgmH4OGzV1esUpR3oUSCPYVd2cUBjKYY= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= @@ -148,10 +141,13 @@ github.com/joshdk/go-junit v1.0.0 h1:S86cUKIdwBHWwA6xCmFlf3RTLfVXYQfvanM5Uh+K6GE github.com/joshdk/go-junit v1.0.0/go.mod h1:TiiV0PqkaNfFXjEiyjWM3XXrhVyCa1K4Zfga6W52ung= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= -github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= -github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/klauspost/compress v1.20.0 h1:a3C1ke2ohxFymNlb2HWAHjDeKCI90scRskErZkR0ezA= github.com/klauspost/compress v1.20.0/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= +github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= +github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= +github.com/klauspost/crc32 v1.3.0 h1:sSmTt3gUt81RP655XGZPElI0PelVTZ6YwCRnPSupoFM= +github.com/klauspost/crc32 v1.3.0/go.mod h1:D7kQaZhnkX/Y0tstFGf8VUzv2UofNGqCjnC3zdHB0Hw= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -162,6 +158,12 @@ github.com/maruel/natural v1.3.0 h1:VsmCsBmEyrR46RomtgHs5hbKADGRVtliHTyCOLFBpsg= github.com/maruel/natural v1.3.0/go.mod h1:v+Rfd79xlw1AgVBjbO0BEQmptqb5HvL/k9GRHB7ZKEg= github.com/mfridman/tparse v0.18.0 h1:wh6dzOKaIwkUGyKgOntDW4liXSo37qg5AXbIhkMV3vE= github.com/mfridman/tparse v0.18.0/go.mod h1:gEvqZTuCgEhPbYk/2lS3Kcxg1GmTxxU7kTC8DvP0i/A= +github.com/minio/crc64nvme v1.1.1 h1:8dwx/Pz49suywbO+auHCBpCtlW1OfpcLN7wYgVR6wAI= +github.com/minio/crc64nvme v1.1.1/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg= +github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34= +github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM= +github.com/minio/minio-go/v7 v7.0.98 h1:MeAVKjLVz+XJ28zFcuYyImNSAh8Mq725uNW4beRisi0= +github.com/minio/minio-go/v7 v7.0.98/go.mod h1:cY0Y+W7yozf0mdIclrttzo1Iiu7mEf9y7nk2uXqMOvM= github.com/moby/spdystream v0.5.1 h1:9sNYeYZUcci9R6/w7KDaFWEWeV4LStVG78Mpyq/Zm/Y= github.com/moby/spdystream v0.5.1/go.mod h1:xBAYlnt/ay+11ShkdFKNAG7LsyK/tmNBVvVOwrfMgdI= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -172,12 +174,12 @@ github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFd github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= -github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f h1:y5//uYreIhSUg3J1GEMiLbxo1LJaP8RfCpH6pymGZus= -github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw= github.com/onsi/ginkgo/v2 v2.33.0 h1:C8gBA6Uc2ZEubiV+SXiu5tZnMTwEmXHgkJwGozKtZf8= github.com/onsi/ginkgo/v2 v2.33.0/go.mod h1:+aXOY+vzZ5mu2iI2HpTZUPmM//oQfsNFX6gU9kNcA44= github.com/onsi/gomega v1.43.1 h1:vGIPFuYrIO6/0Z09s0I0QQQgFchiX4+tb1re3MScJYo= github.com/onsi/gomega v1.43.1/go.mod h1:e/C2HwaZ1DhvjzXXuFhcR7hY7Sh9pl7MmoWKEjzwcdA= +github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM= +github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= @@ -193,6 +195,8 @@ github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= github.com/rogpeppe/go-internal v1.16.0 h1:O9DK+vNMDVGLr2BeZqmpLeMjiMNkuXfcqntWbZV6S5g= github.com/rogpeppe/go-internal v1.16.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52ZOxX7yM1VHvnxs= +github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU= +github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw= github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4= @@ -219,6 +223,8 @@ github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4= github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY= github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28= +github.com/tinylib/msgp v1.6.1 h1:ESRv8eL3u+DNHUoSAAQRE50Hm162zqAnBoGv9PzScPY= +github.com/tinylib/msgp v1.6.1/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA= github.com/tmc/grpc-websocket-proxy v0.0.0-20220101234140-673ab2c3ae75 h1:6fotK7otjonDflCTK0BCfls4SPy3NcCVb5dqqmbRknE= github.com/tmc/grpc-websocket-proxy v0.0.0-20220101234140-673ab2c3ae75/go.mod h1:KO6IkyS8Y3j8OdNO85qEYBsRPuteD+YciPomcXdrMnk= github.com/vmware-tanzu/velero v1.18.3 h1:9uwN5yxTWQl9PsF5ljX4xiG+7VIq3I9mxOQ0DyyZ31A= @@ -227,22 +233,20 @@ github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= github.com/xiang90/probing v0.0.0-20221125231312-a49e3df8f510 h1:S2dVYn90KE98chqDkyE9Z4N61UnQd+KOfgp5Iu53llk= github.com/xiang90/probing v0.0.0-20221125231312-a49e3df8f510/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= -github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -go.etcd.io/bbolt v1.4.3 h1:dEadXpI6G79deX5prL3QRNP6JB8UxVkqo4UPnHaNXJo= -go.etcd.io/bbolt v1.4.3/go.mod h1:tKQlpPaYCVFctUIgFKFnAlvbmB3tpy1vkTnDWohtc0E= -go.etcd.io/etcd/api/v3 v3.6.15 h1:Nysf/QR7vx8bx5oUR/yeMdy0YqtXoeELxn6UvNANrsQ= -go.etcd.io/etcd/api/v3 v3.6.15/go.mod h1:LlBr6CBsOUN/D011XFeIysDxI7JTQuegCX4DgseoOIw= -go.etcd.io/etcd/client/pkg/v3 v3.6.15 h1:6nqIEsCDLjZDh1fgHuQCSjVFv7pzdSYUq8zzpr9V/28= -go.etcd.io/etcd/client/pkg/v3 v3.6.15/go.mod h1:kCC9d5MnlhpVsgf2JVt2c3ydApI6sZo40vlnr79jGKU= -go.etcd.io/etcd/client/v3 v3.6.15 h1:qQUBZNaqSmKKoLRsEcBvnZ0dzwbSrvnCZXxjmRJuHuE= -go.etcd.io/etcd/client/v3 v3.6.15/go.mod h1:peNUITf/Kbpm14YCLIAHeqQFDTkvqLPK71p0Lcz/cqc= -go.etcd.io/etcd/pkg/v3 v3.6.15 h1:LyJ+AOftel5J97A6i5eiDSplXH89y2TpeaHunUBe2sg= -go.etcd.io/etcd/pkg/v3 v3.6.15/go.mod h1:Cka235NdNGX93CscaD5LtEApThVO2HHnBl76pwmWGQs= -go.etcd.io/etcd/server/v3 v3.6.15 h1:IFlqNq0ia29PAcT73gfZjaYO/R+QCOavhenkAP4Y1N0= -go.etcd.io/etcd/server/v3 v3.6.15/go.mod h1:zuF7XwGYkIj7fFtUMYp+AFpa+SdnNj05sbsabmUnGrY= -go.etcd.io/raft/v3 v3.6.0 h1:5NtvbDVYpnfZWcIHgGRk9DyzkBIXOi8j+DDp1IcnUWQ= -go.etcd.io/raft/v3 v3.6.0/go.mod h1:nLvLevg6+xrVtHUmVaTcTz603gQPHfh7kUAwV6YpfGo= +go.etcd.io/bbolt v1.5.0 h1:S7GAl7Fxv12yohbwFfIbQCGDWbQbtDGPET4P/bD4lxU= +go.etcd.io/bbolt v1.5.0/go.mod h1:mkltfYE5aUHQxUct9N9V+Kp7aSjFqjgrhcXIS70Lrdk= +go.etcd.io/etcd/api/v3 v3.7.0 h1:WZlGK7pRtYGDB8ti8wkrQ5D2oWGMbtNL9VA5e+vF2Fg= +go.etcd.io/etcd/api/v3 v3.7.0/go.mod h1:EcTihnwAQ0BQNh5dfAdaFVFdchuo7EP0HlX7TV3jz/A= +go.etcd.io/etcd/client/pkg/v3 v3.7.0 h1:sW9njJzS3vXKcAJjjLQ4nk+avNUJ12Bcijcx8ehUskE= +go.etcd.io/etcd/client/pkg/v3 v3.7.0/go.mod h1:cnzZGIUzSfjEwLC6UBVsSXlEK1eepS/JUD7wE6PLRT0= +go.etcd.io/etcd/client/v3 v3.7.0 h1:5MHO37VbPB87VRPKUXEcicjeQWiTSjpPv3Ume8xPx20= +go.etcd.io/etcd/client/v3 v3.7.0/go.mod h1:DJ382WuwjmbowjPDyaaQ0idWXy4dh91XRhe4FOrb9vM= +go.etcd.io/etcd/pkg/v3 v3.7.0 h1:aUBHGzXnYL2m3AlZfKp0ZhHQLVZIKfu9QsIlYdr+mxc= +go.etcd.io/etcd/pkg/v3 v3.7.0/go.mod h1:fDQYyc8rOC1Yl4EZLh0O1OjHzwJW7jAly80+BpD1M9o= +go.etcd.io/etcd/server/v3 v3.7.0 h1:ScdUdN8ljuimp0lZaNq0otLMrHcFSFT+dQyT1j7JSFo= +go.etcd.io/etcd/server/v3 v3.7.0/go.mod h1:v7N1dPdSW2vzyxGsbDwK4X0sCe3SYNlQ+9eNIMGzdxQ= +go.etcd.io/raft/v3 v3.7.0 h1:BGzlwx07bLv8PW6OU5HObuz1y4hlPZUXA07pM1mPUh4= +go.etcd.io/raft/v3 v3.7.0/go.mod h1:6gX6T2X907DjnjsFLODnTxba77stjs84W9gTTI0GUNA= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.71.0 h1:B2h3uqicet1CT2N5TOFhS+Gq++9i0/CLmaxvhmhtP5s= @@ -276,53 +280,28 @@ go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba h1:Ck8QetSgk912qxWLMCKxd0in+aiyBQyDSMae6e/xmpU= golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba/go.mod h1:50RgIsmK7OwqzTTeqcSXQW8SswW0o8fRcDxmqGluJ8E= -golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues= golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98= golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE= golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE= golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.50.0 h1:c2ifzfcuY7L90lZ2aKd8S4K2NpASF08SZx9ZuJkHmSU= golang.org/x/tools v0.50.0/go.mod h1:7ulVMw3831Mwi5EZD6RomGyffr4VFjuNYXf2BbCEAV0= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gomodules.xyz/jsonpatch/v2 v2.5.0 h1:JELs8RLM12qJGXU4u/TO3V25KW8GreMKl9pdkk14RM0= gomodules.xyz/jsonpatch/v2 v2.5.0/go.mod h1:AH3dM2RI6uoBZxn3LVrfvJ3E0/9dG4cSrbuBJT4moAY= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= @@ -344,37 +323,41 @@ gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -k8s.io/api v0.35.0 h1:iBAU5LTyBI9vw3L5glmat1njFK34srdLmktWwLTprlY= -k8s.io/api v0.35.0/go.mod h1:AQ0SNTzm4ZAczM03QH42c7l3bih1TbAXYo0DkF8ktnA= -k8s.io/apiextensions-apiserver v0.35.0 h1:3xHk2rTOdWXXJM+RDQZJvdx0yEOgC0FgQ1PlJatA5T4= -k8s.io/apiextensions-apiserver v0.35.0/go.mod h1:E1Ahk9SADaLQ4qtzYFkwUqusXTcaV2uw3l14aqpL2LU= -k8s.io/apiserver v0.35.0 h1:CUGo5o+7hW9GcAEF3x3usT3fX4f9r8xmgQeCBDaOgX4= -k8s.io/apiserver v0.35.0/go.mod h1:QUy1U4+PrzbJaM3XGu2tQ7U9A4udRRo5cyxkFX0GEds= -k8s.io/client-go v0.35.0 h1:IAW0ifFbfQQwQmga0UdoH0yvdqrbwMdq9vIFEhRpxBE= -k8s.io/client-go v0.35.0/go.mod h1:q2E5AAyqcbeLGPdoRB+Nxe3KYTfPce1Dnu1myQdqz9o= -k8s.io/component-base v0.35.0 h1:+yBrOhzri2S1BVqyVSvcM3PtPyx5GUxCK2tinZz1G94= -k8s.io/component-base v0.35.0/go.mod h1:85SCX4UCa6SCFt6p3IKAPej7jSnF3L8EbfSyMZayJR0= +k8s.io/api v0.37.1 h1:l6N77U7tjwB5L056bgrBTJIEdevac/naBZ3iSvDNfpM= +k8s.io/api v0.37.1/go.mod h1:zSlbB1YpJ1YQlFVQy20UYll81UJSJJUMLhkhvg6Z78M= +k8s.io/apiextensions-apiserver v0.37.1 h1:7fIQG8eThDSTVYBWg/DOpI8v5wYfKCo0N8/TDMjj+zY= +k8s.io/apiextensions-apiserver v0.37.1/go.mod h1:1Q3ujWwHgnhBoGsdmGORflwK1sDFmuaqH1OsMDWk2Gs= +k8s.io/apimachinery v0.37.1 h1:hGCYyvKHCwtwMitj2vU4vYx0Z16N9GyZk9BBnz0wDAE= +k8s.io/apimachinery v0.37.1/go.mod h1:jF84AyUi/IRIXRot5f+lm6MpxoWI+F1XgjaMmwCdTFw= +k8s.io/apiserver v0.37.1 h1:dUsNwjsvItyVKNpC1N0AhQ0OBSiUJKfWz004vPifOe0= +k8s.io/apiserver v0.37.1/go.mod h1:EWXW6PntGfOC2uD9GGVobnOExgFoX1z0hZo7f7Rs7Ng= +k8s.io/client-go v0.37.1 h1:QTv/5ha4jAHtW9qxxVBkQVFBRDb4jHfFopQqqMdc+wM= +k8s.io/client-go v0.37.1/go.mod h1:dnAPtTnCNY38Ho04D2KdY1F4IKausa9UbqaAZKl60SY= +k8s.io/component-base v0.37.1 h1:93DMmlENnK7gNLkL4pMqLO5M/HVf3p3sM4q/GasLveY= +k8s.io/component-base v0.37.1/go.mod h1:bBrdziT4dreQG5lzTaPVxBwsZe1oxphG+ZVdD56dQWQ= k8s.io/klog/v2 v2.140.0 h1:Tf+J3AH7xnUzZyVVXhTgGhEKnFqye14aadWv7bzXdzc= k8s.io/klog/v2 v2.140.0/go.mod h1:o+/RWfJ6PwpnFn7OyAG3QnO47BFsymfEfrz6XyYSSp0= -k8s.io/kms v0.35.0 h1:/x87FED2kDSo66csKtcYCEHsxF/DBlNl7LfJ1fVQs1o= -k8s.io/kms v0.35.0/go.mod h1:VT+4ekZAdrZDMgShK37vvlyHUVhwI9t/9tvh0AyCWmQ= -k8s.io/kube-openapi v0.0.0-20250910181357-589584f1c912 h1:Y3gxNAuB0OBLImH611+UDZcmKS3g6CthxToOb37KgwE= -k8s.io/kube-openapi v0.0.0-20250910181357-589584f1c912/go.mod h1:kdmbQkyfwUagLfXIad1y2TdrjPFWp2Q89B3qkRwf/pQ= +k8s.io/kms v0.37.1 h1:MD1kA8AdFF/N5sGP8gnvL6vTo/oeaQXbmLjWmmJHLc8= +k8s.io/kms v0.37.1/go.mod h1:0U6zfwLkfJr9O/jLgz2GARnKLh2uIhkq2EeaU66J5ow= +k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad h1:oXImqH8mQNk7PmvzKhmN3ddJoY6OnyM225MXwGHPm0A= +k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad/go.mod h1:0/mqHCVhlumdJ3BhCfnjSZQE037nAhNodh1/hK0T8/I= +k8s.io/streaming v0.37.1 h1:TpzVfQeFuVndn2g9mFqxy1UcUYPwDzqjUmwR/IzJCWc= +k8s.io/streaming v0.37.1/go.mod h1:APlJR26ZWRcVy5bIEj0QRrKUXROtBHPcxl2NT7EAzPU= k8s.io/utils v0.0.0-20260707023825-cf1189d6abe3 h1:jVkFFVfXdXP74B/zbO3hM3hpSFD0xvhQ5U686DPurkE= k8s.io/utils v0.0.0-20260707023825-cf1189d6abe3/go.mod h1:M2s5JB1lIYP3jzZdorPLHXIPJzt9vv2muW5a6L9DtNM= sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.36.0 h1:/YpDJ4vReG7ZmzSpBGxduXgywWkJU9zHubgJG03MT+Y= sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.36.0/go.mod h1:tJo1aepTXyR+8Xs3sUsGBDk4Ub2AM5dPAPKJx0mpm5c= sigs.k8s.io/container-object-storage-interface-api v0.1.0 h1:8tB6JFQhbQIC1hwGQ+q4+tmSSNfjKemb7bFI6C0CK/4= sigs.k8s.io/container-object-storage-interface-api v0.1.0/go.mod h1:YiB+i/UGkzqgODDhRG3u7jkbWkQcoUeLEJ7hwOT/2Qk= -sigs.k8s.io/controller-runtime v0.23.1 h1:TjJSM80Nf43Mg21+RCy3J70aj/W6KyvDtOlpKf+PupE= -sigs.k8s.io/controller-runtime v0.23.1/go.mod h1:B6COOxKptp+YaUT5q4l6LqUJTRpizbgf9KSRNdQGns0= +sigs.k8s.io/controller-runtime v0.25.1 h1:BKgU9OeE8xv8EbbM8cY0NVzTQs35rokkdq1jh12fMb4= +sigs.k8s.io/controller-runtime v0.25.1/go.mod h1:4QqLdT6z/L6Olj8JJCtvztid4/fnIiYsfaTFScegctc= sigs.k8s.io/gateway-api v1.4.1 h1:NPxFutNkKNa8UfLd2CMlEuhIPMQgDQ6DXNKG9sHbJU8= sigs.k8s.io/gateway-api v1.4.1/go.mod h1:AR5RSqciWP98OPckEjOjh2XJhAe2Na4LHyXD2FUY7Qk= sigs.k8s.io/json v0.0.0-20260909141634-11ed52e25bc5 h1:k9jo7ED/fsfOcz3L1P20P5tjTNtsdQNwMOG2aKzHrl8= sigs.k8s.io/json v0.0.0-20260909141634-11ed52e25bc5/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg= sigs.k8s.io/randfill v1.0.0 h1:JfjMILfT8A6RbawdsK2JXGBR5AQVfd+9TbzrlneTyrU= sigs.k8s.io/randfill v1.0.0/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxOY= -sigs.k8s.io/structured-merge-diff/v6 v6.3.2-0.20260122202528-d9cc6641c482 h1:2WOzJpHUBVrrkDjU4KBT8n5LDcj824eX0I5UKcgeRUs= -sigs.k8s.io/structured-merge-diff/v6 v6.3.2-0.20260122202528-d9cc6641c482/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE= +sigs.k8s.io/structured-merge-diff/v6 v6.4.2 h1:qdOxHwrl2Kaag1aQEarlYcOA9vSyGCp3CIki3aW8c4Q= +sigs.k8s.io/structured-merge-diff/v6 v6.4.2/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE= sigs.k8s.io/yaml v1.6.0 h1:G8fkbMSAFqgEFgh4b1wmtzDnioxFCUgTZhlbj5P9QYs= sigs.k8s.io/yaml v1.6.0/go.mod h1:796bPqUfzR/0jLAl6XjHl3Ck7MiyVv8dbTdyT3/pMf4= diff --git a/hack/admin-kubeconfig-invariant.bats b/hack/admin-kubeconfig-invariant.bats index 310590ae0..fb764f557 100644 --- a/hack/admin-kubeconfig-invariant.bats +++ b/hack/admin-kubeconfig-invariant.bats @@ -18,6 +18,8 @@ # project's CI runners and on the maintainer workstation. # ----------------------------------------------------------------------------- +load test_helper + @test "every Deployment mounting admin-kubeconfig has optional:true and wait-for-kubeconfig init" { values_file="packages/apps/kubernetes/tests/values-ci.yaml" [ -f "$values_file" ] diff --git a/hack/alert-severity-contract.bats b/hack/alert-severity-contract.bats new file mode 100644 index 000000000..44f197000 --- /dev/null +++ b/hack/alert-severity-contract.bats @@ -0,0 +1,422 @@ +#!/usr/bin/env bats + +load test_helper + +# Alerta's default alarm model, the set the webhook accepts. `none` is left out +# on purpose: the Alertmanager config routes severity="none" to a blackhole +# receiver, so such an alert is never delivered, which is the outcome this +# contract exists to catch. Rule files under packages/**/charts/** are out of +# scope: they are re-vendored by `make update`, so a bad severity there is +# fixed upstream or in patches/, not by editing the label. +ALERT_SEVERITY_ALLOWED=" security critical major minor warning indeterminate informational normal ok cleared debug trace unknown " +# The alerts that exist only to be dropped, the one place `none` is right. +# InfoInhibitor is the source side of an Alertmanager inhibit rule, which the +# platform config does not have, so delivering it at any severity is noise. +ALERT_SEVERITY_BLACKHOLED=" InfoInhibitor " + +helm_actions_stripped() { + awk ' + function strip_comments(s, pre, rest) { + while (1) { + if (incomment) { + if (match(s, /\*\/[ \t]*-?[}][}]/)) { s = substr(s, RSTART + RLENGTH); incomment = 0 } else { return "" } + } + if (match(s, /[{][{]-?[ \t]*\/\*/)) { + pre = substr(s, 1, RSTART - 1); rest = substr(s, RSTART + RLENGTH) + if (match(rest, /\*\/[ \t]*-?[}][}]/)) { s = pre substr(rest, RSTART + RLENGTH) } else { incomment = 1; return pre } + } else { return s } + } + } + { + line = strip_comments($0) + if (incomment && line ~ /^[ \t]*$/) { next } + if (line ~ /^[ \t]*[{][{].*[}][}][ \t]*$/) { next } + gsub(/[{][{][^}]*[}][}]/, "TEMPLATED", line) + print line + } + ' "$1" +} + +alert_severity_rows() { + severity_root=${ALERT_SEVERITY_ROOT:-"$(dirname "${BATS_TEST_FILENAME:-$0}")/.."} + severity_files=$(mktemp) || return 1 + severity_rows=$(mktemp) || { + rm -f "$severity_files" + return 1 + } + severity_stripped=$(mktemp) || { + rm -f "$severity_files" "$severity_rows" + return 1 + } + + if ! ( + cd "$severity_root" && + git grep -Il -E "kind:[[:space:]]*[\"']?(PrometheusRule|VMRule)[\"']?([[:space:]#,}]|\$)" -- \ + 'packages/**/*.yaml' \ + 'packages/**/*.yml' \ + ':(exclude)packages/**/charts/**' + ) > "$severity_files"; then + rm -f "$severity_files" "$severity_rows" "$severity_stripped" + return 1 + fi + + if ! : > "$severity_rows"; then + rm -f "$severity_files" "$severity_rows" "$severity_stripped" + return 1 + fi + while IFS= read -r file; do + if ! (cd "$severity_root" && helm_actions_stripped "$file" > "$severity_stripped" && FILE="$file" yq 'select(.kind == "PrometheusRule" or .kind == "VMRule") | .spec.groups[]? | .rules[]? | select(has("alert")) | [strenv(FILE), .alert, ((.labels.severity // "") | tostring)] | @tsv' "$severity_stripped") >> "$severity_rows"; then + echo "$file: failed to parse alert rules" >&2 + rm -f "$severity_files" "$severity_rows" "$severity_stripped" + return 1 + fi + if ! severity_hidden=$(yq 'select(.kind == "PrometheusRule" or .kind == "VMRule") | ((select(((.spec.groups // []) | length) == 0) | ["a rule document without rule groups"] | @tsv), (.spec.groups[]? | select(((.rules // []) | map(select(tag == "!!map" and (has("alert") or has("record")))) | length) == 0) | ["rule group " + ((.name // "") | tostring)] | @tsv))' "$severity_stripped"); then + echo "$file: failed to parse alert rules" >&2 + rm -f "$severity_files" "$severity_rows" "$severity_stripped" + return 1 + fi + severity_hidden=$(printf '%s\n' "$severity_hidden" | sed '/^[[:space:]]*$/d') + if [ -n "$severity_hidden" ]; then + printf '%s\n' "$severity_hidden" | while IFS= read -r what; do + echo "$file: $what shows no alert or recording rule once template actions are stripped" >&2 + done + rm -f "$severity_files" "$severity_rows" "$severity_stripped" + return 1 + fi + done < "$severity_files" + + if ! sed '/^[[:space:]]*$/d' "$severity_rows"; then + rm -f "$severity_files" "$severity_rows" "$severity_stripped" + return 1 + fi + rm -f "$severity_files" "$severity_rows" "$severity_stripped" +} + +alert_severity_contract() { + rows=$(mktemp) || return 1 + if ! alert_severity_rows > "$rows"; then + rm -f "$rows" + return 1 + fi + bad=0 + tab=$(printf '\t') + while IFS="$tab" read -r file alert severity; do + accepted=0 + for allowed in $ALERT_SEVERITY_ALLOWED; do + if [ "$allowed" = "$severity" ]; then + accepted=1 + break + fi + done + if [ "$severity" = "none" ]; then + for blackholed in $ALERT_SEVERITY_BLACKHOLED; do + if [ "$blackholed" = "$alert" ]; then + accepted=1 + break + fi + done + fi + if [ "$accepted" -eq 0 ]; then + echo "$file: $alert -> '$severity'" >&2 + bad=$((bad + 1)) + fi + done < "$rows" + rm -f "$rows" + [ "$bad" -eq 0 ] || return 1 +} + +@test "alert rules are discovered" { + rows=$(mktemp) || return 1 + if ! alert_severity_rows > "$rows"; then + rm -f "$rows" + return 1 + fi + count=$(wc -l < "$rows" | tr -d ' ') + rm -f "$rows" + [ "$count" -gt 0 ] +} + +@test "every alert rule carries a severity the alert sink accepts" { + alert_severity_contract +} + +@test "InfoInhibitor is labelled for the blackhole route" { + rows=$(mktemp) || return 1 + if ! alert_severity_rows > "$rows"; then + rm -f "$rows" + return 1 + fi + tab=$(printf '\t') + found=$(grep -c "${tab}InfoInhibitor${tab}" "$rows" || true) + delivered=$(grep "${tab}InfoInhibitor${tab}" "$rows" | grep -vc "${tab}none\$" || true) + rm -f "$rows" + [ "$found" -gt 0 ] + [ "$delivered" -eq 0 ] +} + +@test "severity none passes only on an alert that exists to be dropped" { + fixture=$(mktemp -d) + mkdir -p "$fixture/packages/system/example/alerts" + printf '%s\n' \ + 'apiVersion: operator.victoriametrics.com/v1beta1' \ + 'kind: VMRule' \ + 'spec:' \ + ' groups:' \ + ' - name: general' \ + ' rules:' \ + ' - alert: InfoInhibitor' \ + ' labels:' \ + ' severity: none' \ + > "$fixture/packages/system/example/alerts/00-inhibitor.yaml" + git -C "$fixture" init -q + git -C "$fixture" add packages/system/example/alerts/00-inhibitor.yaml + + inhibitor_succeeded=0 + ALERT_SEVERITY_ROOT="$fixture" alert_severity_contract >/dev/null 2>&1 || inhibitor_succeeded=$? + + printf '%s\n' \ + 'apiVersion: operator.victoriametrics.com/v1beta1' \ + 'kind: VMRule' \ + 'spec:' \ + ' groups:' \ + ' - name: silent' \ + ' rules:' \ + ' - alert: SilentAlert' \ + ' labels:' \ + ' severity: none' \ + > "$fixture/packages/system/example/alerts/01-silent.yaml" + git -C "$fixture" add packages/system/example/alerts/01-silent.yaml + + silent_succeeded=0 + ALERT_SEVERITY_ROOT="$fixture" alert_severity_contract >/dev/null 2>&1 || silent_succeeded=$? + rm -rf "$fixture" + [ "$inhibitor_succeeded" -eq 0 ] + [ "$silent_succeeded" -ne 0 ] +} + +@test "an alert that exists to be dropped still fails on a refused severity" { + fixture=$(mktemp -d) + mkdir -p "$fixture/packages/system/example/alerts" + printf '%s\n' \ + 'apiVersion: operator.victoriametrics.com/v1beta1' \ + 'kind: VMRule' \ + 'spec:' \ + ' groups:' \ + ' - name: general' \ + ' rules:' \ + ' - alert: InfoInhibitor' \ + ' labels:' \ + ' severity: info' \ + > "$fixture/packages/system/example/alerts/00-inhibitor.yaml" + git -C "$fixture" init -q + git -C "$fixture" add packages/system/example/alerts/00-inhibitor.yaml + + contract_succeeded=0 + ALERT_SEVERITY_ROOT="$fixture" alert_severity_contract >/dev/null 2>&1 || contract_succeeded=$? + rm -rf "$fixture" + [ "$contract_succeeded" -ne 0 ] +} + +@test "a parser failure cannot leave the contract green" { + fixture=$(mktemp -d) + mkdir -p "$fixture/packages/system/example/alerts" + printf '%s\n' \ + 'apiVersion: operator.victoriametrics.com/v1beta1' \ + 'kind: VMRule' \ + 'spec:' \ + ' groups:' \ + ' - name: valid' \ + ' rules:' \ + ' - alert: ValidAlert' \ + ' labels:' \ + ' severity: warning' \ + > "$fixture/packages/system/example/alerts/00-valid.yaml" + printf '%s\n' \ + 'apiVersion: operator.victoriametrics.com/v1beta1' \ + 'kind: VMRule' \ + 'spec: [' \ + > "$fixture/packages/system/example/alerts/99-malformed.yaml" + git -C "$fixture" init -q + git -C "$fixture" add packages/system/example/alerts/00-valid.yaml packages/system/example/alerts/99-malformed.yaml + + parser_succeeded=0 + ALERT_SEVERITY_ROOT="$fixture" alert_severity_rows >/dev/null 2>&1 || parser_succeeded=$? + rm -rf "$fixture" + [ "$parser_succeeded" -ne 0 ] +} + +@test "template rule sources cannot bypass the severity contract" { + fixture=$(mktemp -d) + mkdir -p "$fixture/packages/extra/example/templates" + printf '%s\n' \ + 'apiVersion: monitoring.coreos.com/v1' \ + 'kind: PrometheusRule' \ + 'spec:' \ + ' groups:' \ + ' - name: template' \ + ' rules:' \ + ' - alert: InvalidTemplateSeverity' \ + ' labels:' \ + ' severity: warn' \ + > "$fixture/packages/extra/example/templates/prometheus-rules.yaml" + git -C "$fixture" init -q + git -C "$fixture" add packages/extra/example/templates/prometheus-rules.yaml + + contract_succeeded=0 + ALERT_SEVERITY_ROOT="$fixture" alert_severity_contract >/dev/null 2>&1 || contract_succeeded=$? + rm -rf "$fixture" + [ "$contract_succeeded" -ne 0 ] +} + +@test "helm template actions do not hide a rule from the contract" { + fixture=$(mktemp -d) + mkdir -p "$fixture/packages/system/example/templates" + printf '%s\n' \ + '{{- if .Values.alerts.enabled }}' \ + '{{- /*' \ + 'Rules gated on a value, behind a comment that spans lines.' \ + '*/}}' \ + 'apiVersion: monitoring.coreos.com/v1' \ + 'kind: PrometheusRule' \ + 'metadata:' \ + ' name: example' \ + ' namespace: {{ .Release.Namespace }}' \ + 'spec:' \ + ' groups:' \ + ' - name: example' \ + ' rules:' \ + ' {{- /* one-line comment */}}' \ + ' - alert: TemplatedRuleWithBadSeverity' \ + ' expr: up == 0' \ + ' labels:' \ + ' severity: warn' \ + ' annotations:' \ + ' description: {{ "{{ $labels.instance }}" }} is down' \ + '{{- end }}' \ + > "$fixture/packages/system/example/templates/alerts.yaml" + git -C "$fixture" init -q + git -C "$fixture" add packages/system/example/templates/alerts.yaml + + rows=$(mktemp) + parser_succeeded=0 + ALERT_SEVERITY_ROOT="$fixture" alert_severity_rows > "$rows" 2>/dev/null || parser_succeeded=$? + found=$(grep -c 'TemplatedRuleWithBadSeverity' "$rows" || true) + contract_succeeded=0 + ALERT_SEVERITY_ROOT="$fixture" alert_severity_contract >/dev/null 2>&1 || contract_succeeded=$? + rm -rf "$fixture" "$rows" + [ "$parser_succeeded" -eq 0 ] + [ "$found" -eq 1 ] + [ "$contract_succeeded" -ne 0 ] +} + +@test "two accepted words in one severity are rejected" { + fixture=$(mktemp -d) + mkdir -p "$fixture/packages/system/example/alerts" + printf '%s\n' \ + 'apiVersion: operator.victoriametrics.com/v1beta1' \ + 'kind: VMRule' \ + 'spec:' \ + ' groups:' \ + ' - name: joined' \ + ' rules:' \ + ' - alert: JoinedSeverity' \ + ' labels:' \ + ' severity: critical major' \ + > "$fixture/packages/system/example/alerts/00-joined.yaml" + git -C "$fixture" init -q + git -C "$fixture" add packages/system/example/alerts/00-joined.yaml + + contract_succeeded=0 + ALERT_SEVERITY_ROOT="$fixture" alert_severity_contract >/dev/null 2>&1 || contract_succeeded=$? + rm -rf "$fixture" + [ "$contract_succeeded" -ne 0 ] +} + +@test "quoted kinds and trailing comments do not hide a rule source" { + fixture=$(mktemp -d) + mkdir -p "$fixture/packages/system/example/alerts" + printf '%s\n' \ + 'apiVersion: operator.victoriametrics.com/v1beta1' \ + 'kind: "VMRule"' \ + 'spec:' \ + ' groups:' \ + ' - name: quoted' \ + ' rules:' \ + ' - alert: QuotedKindSeverity' \ + ' labels:' \ + ' severity: warn' \ + > "$fixture/packages/system/example/alerts/00-quoted.yaml" + printf '%s\n' \ + 'apiVersion: monitoring.coreos.com/v1' \ + 'kind: PrometheusRule # served by the operator' \ + 'spec:' \ + ' groups:' \ + ' - name: commented' \ + ' rules:' \ + ' - alert: CommentedKindSeverity' \ + ' labels:' \ + ' severity: warn' \ + > "$fixture/packages/system/example/alerts/01-commented.yaml" + git -C "$fixture" init -q + git -C "$fixture" add packages/system/example/alerts/00-quoted.yaml packages/system/example/alerts/01-commented.yaml + + rows=$(mktemp) + ALERT_SEVERITY_ROOT="$fixture" alert_severity_rows > "$rows" 2>/dev/null || true + found=$(grep -cE 'QuotedKindSeverity|CommentedKindSeverity' "$rows" || true) + contract_succeeded=0 + ALERT_SEVERITY_ROOT="$fixture" alert_severity_contract >/dev/null 2>&1 || contract_succeeded=$? + rm -rf "$fixture" "$rows" + [ "$found" -eq 2 ] + [ "$contract_succeeded" -ne 0 ] +} + +@test "a rule group that only template actions fill fails the contract" { + fixture=$(mktemp -d) + mkdir -p "$fixture/packages/system/example/templates" + printf '%s\n' \ + 'apiVersion: monitoring.coreos.com/v1' \ + 'kind: PrometheusRule' \ + 'metadata:' \ + ' name: example' \ + 'spec:' \ + ' groups:' \ + ' - name: generated' \ + ' rules:' \ + ' {{- include "example.rules" . | nindent 4 }}' \ + > "$fixture/packages/system/example/templates/alerts.yaml" + git -C "$fixture" init -q + git -C "$fixture" add packages/system/example/templates/alerts.yaml + + errors=$(mktemp) + parser_succeeded=0 + ALERT_SEVERITY_ROOT="$fixture" alert_severity_rows >/dev/null 2>"$errors" || parser_succeeded=$? + named=$(grep -c '^packages/system/example/templates/alerts.yaml: rule group generated shows no alert or recording rule' "$errors" || true) + contract_succeeded=0 + ALERT_SEVERITY_ROOT="$fixture" alert_severity_contract >/dev/null 2>&1 || contract_succeeded=$? + rm -rf "$fixture" "$errors" + [ "$parser_succeeded" -ne 0 ] + [ "$named" -eq 1 ] + [ "$contract_succeeded" -ne 0 ] +} + +@test "a group of recording rules alone passes the contract" { + fixture=$(mktemp -d) + mkdir -p "$fixture/packages/system/example/alerts" + printf '%s\n' \ + 'apiVersion: operator.victoriametrics.com/v1beta1' \ + 'kind: VMRule' \ + 'spec:' \ + ' groups:' \ + ' - name: recording' \ + ' rules:' \ + ' - record: job:up:sum' \ + ' expr: sum by (job) (up)' \ + > "$fixture/packages/system/example/alerts/00-recording.yaml" + git -C "$fixture" init -q + git -C "$fixture" add packages/system/example/alerts/00-recording.yaml + + contract_succeeded=0 + ALERT_SEVERITY_ROOT="$fixture" alert_severity_contract >/dev/null 2>&1 || contract_succeeded=$? + rm -rf "$fixture" + [ "$contract_succeeded" -eq 0 ] +} diff --git a/hack/altinity-backup-strategy.bats b/hack/altinity-backup-strategy.bats new file mode 100644 index 000000000..070b6bad5 --- /dev/null +++ b/hack/altinity-backup-strategy.bats @@ -0,0 +1,531 @@ +#!/usr/bin/env bats +# Behavioural tests for the shipped ClickHouse (Altinity) strategy script, +# extracted from the rendered cozy-default-altinity Strategy CR and EXECUTED +# against a stubbed clickhouse-backup sidecar API. +# +# The contract pinned here is the start gate: the sidecar serialises its +# operations and answers any new one with HTTP 423 while another is "in +# progress", so a strategy Pod that starts its operation without waiting for +# an idle sidecar burns a Job attempt in seconds. The gate has to fail the Pod +# rather than proceed when the sidecar never becomes idle. Once started, an +# operation the sidecar no longer lists (its action log lives in memory and a +# restart empties it) has to fail the Pod too, since the Job has no deadline. +# A Job retry must not start its operation twice: it takes over the +# restore_remote, or the create_remote of the archive the controller named, +# that the attempt before it left running, and a few lost polls do not end an +# attempt in the first place. +# +# Which archive a restore reads back is decided by the script's own jq +# selection over list/remote, so it is exercised against several archives +# rather than string-matched: exactly the archive the Backup recorded, or for +# a Backup that records none, the newest one stamped no later than its takenAt. +# +# Run from the repo root with make bats-unit-tests. The rendered script is run +# with `bash`, not `sh`: it opens `set -euo pipefail`, which the production +# image's busybox ash supports but the CI runner's /bin/sh (dash) rejects. + +load test_helper + +CHART=packages/system/backupstrategy-controller + +# Render the shipped strategy's in-Pod script into $1 and substitute the +# controller-render placeholders the way the driver fills them: $2 mode, $3 +# app (release and source application), $4 the archive name the controller +# chose or the Backup recorded (empty, the default, for none), $5 the Backup +# name, $6 its takenAt in the archive-name layout (default: later than every +# archive the stub lists). An empty render fails early, as does a placeholder +# left unsubstituted: these tests EXECUTE it. +render_script() { + out=$1; mode=$2; app=$3; archive=${4-}; backup=${5-bkp}; takenat=${6-99991231T235959Z} + helm template t "$CHART" -n cozy-backup-controller \ + --set backupStorage.bucketNameOverride=test-bucket 2>/dev/null \ + | yq eval 'select(.kind == "Altinity") | .spec.template.spec.containers[0].args[0]' - \ + | sed -e "s#{{ .Mode }}#${mode}#g" \ + -e "s#{{ .Release.Name }}#${app}#g" \ + -e "s#{{ .Release.Namespace }}#tenant-x#g" \ + -e "s#{{ .Backup.ApplicationRef.Name }}#${app}#g" \ + -e "s#{{ .Backup.Name }}#${backup}#g" \ + -e "s#{{ .ArchiveName | default \"\" }}#${archive}#g" \ + -e "s#{{ .Backup.TakenAt | default \"\" }}#${takenat}#g" > "$out" + [ -s "$out" ] || return 1 + if grep -q '{{' "$out"; then + echo "rendered script still holds a controller placeholder" >&2 + return 1 + fi +} + +# A curl stub standing in for the sidecar API, put first on PATH next to a +# no-op sleep. State lives in $1: +# unreachable present: every request fails as a refused connection (7) +# down a number: that many next requests fail the same way, as +# before the sidecar has started +# busy a number: that many GET /backup/actions answers still list +# an operation of someone else "in progress" +# op the command line of the sidecar's own operation, written +# by an accepted POST the way the sidecar logs it ("--resume" +# before the name of a create_remote asking for it), or +# seeded by a test as the operation +# an earlier attempt of the same Job started +# op_left how many more GET /backup/actions answers list op as +# "in progress" before it ends with op_result +# op_duration op_left given to an operation a POST starts (default 0) +# op_result the status op ends with (default success) +# prior extra action-log rows, verbatim, older than op +# remote present: the list/remote answer, verbatim, in place of the +# one archive listed by default +# restarted present: the action log no longer lists op, as after the +# sidecar restarted and lost its in-memory log +# fail_on_post a POST that is accepted makes that many following +# GET /backup/actions requests fail (curl exit 7) +# idle created by an answer that lists nothing in progress; a +# POST is refused (423, curl -f exit 22) unless one was seen +# since the last accepted POST, and while anything runs +# accepted one line per POST the sidecar accepted +# requests one line per request: method and URL +# runaway created when the script exceeds 200 requests; that request +# and every later one fails, so a polling loop that never ends +# stops the test instead of hanging it +make_stubs() { + bin=$1; state=$2 + mkdir -p "$bin" "$state" + cat > "$bin/curl" <> "\$state/requests" +if [ "\$(wc -l < "\$state/requests")" -gt 200 ]; then touch "\$state/runaway"; exit 7; fi +if [ -e "\$state/unreachable" ]; then exit 7; fi +num() { cat "\$state/\$1" 2>/dev/null || echo 0; } +down=\$(num down) +if [ "\$down" -gt 0 ]; then echo \$((down - 1)) > "\$state/down"; exit 7; fi +running=0 +if [ -s "\$state/op" ] && [ ! -e "\$state/restarted" ] && [ "\$(num op_left)" -gt 0 ]; then running=1; fi +case "\$method \$url" in + "POST "*) + if [ "\$(num busy)" -gt 0 ] || [ "\$running" = 1 ] || [ ! -e "\$state/idle" ]; then exit 22; fi + case "\$url" in + */create_remote\?name=*) + name=\${url#*name=}; name=\${name%%&*} + case "\$url" in *[?\&]resume=true*) cmd="create_remote --resume \$name" ;; *) cmd="create_remote \$name" ;; esac + ;; + */restore_remote/*) cmd="restore_remote \${url##*/}" ;; + *) exit 22 ;; + esac + echo "\$cmd" > "\$state/op" + echo "\$cmd" >> "\$state/accepted" + num op_duration > "\$state/op_left" + num fail_on_post > "\$state/fail_polls" + rm -f "\$state/idle" + ;; + "GET "*/backup/actions) + fail=\$(num fail_polls) + if [ "\$fail" -gt 0 ]; then echo \$((fail - 1)) > "\$state/fail_polls"; exit 7; fi + echo '{"command":"create_remote clickhouse-myapp-20260101T000000Z","status":"error","start":"2026-01-01 00:00:00","error":"old"}' + cat "\$state/prior" 2>/dev/null || true + inprog=0 + busy=\$(num busy) + if [ "\$busy" -gt 0 ]; then + echo \$((busy - 1)) > "\$state/busy" + echo '{"command":"upload --resumable=1 clickhouse-myapp-20260101T000000Z","status":"in progress","start":"2026-01-01 00:01:00"}' + inprog=1 + fi + if [ -s "\$state/op" ] && [ ! -e "\$state/restarted" ]; then + left=\$(num op_left) + if [ "\$left" -gt 0 ]; then + echo \$((left - 1)) > "\$state/op_left" + status="in progress" + inprog=1 + else + status=\$(cat "\$state/op_result" 2>/dev/null || echo success) + fi + echo "{\"command\":\"\$(cat "\$state/op")\",\"status\":\"\$status\",\"start\":\"2026-01-01 00:02:00\",\"error\":\"boom\"}" + fi + if [ "\$inprog" = 0 ]; then touch "\$state/idle"; fi + ;; + "GET "*/backup/list/remote) + if [ -e "\$state/remote" ]; then cat "\$state/remote"; else + echo '{"name":"clickhouse-myapp-20260101T000000Z","created":"2026-01-01 00:00:00"}' + fi + ;; +esac +exit 0 +STUB + cat > "$bin/sleep" <<'STUB' +#!/bin/sh +exit 0 +STUB + chmod 0755 "$bin/curl" "$bin/sleep" +} + +# One list/remote row per argument, "name" or "name|desc"; created mirrors +# the name's timestamp. +remote_rows() { + for row in "$@"; do + name=${row%%|*}; desc="tar, regular" + if [ "$row" != "$name" ]; then desc=${row#*|}; fi + ts=${name##*-} + printf '{"name":"%s","created":"%s","location":"remote","required":"","desc":"%s"}\n' "$name" "$ts" "$desc" + done +} + +accepted() { + if [ -e "$1/state/accepted" ]; then wc -l < "$1/state/accepted" | tr -d ' '; else echo 0; fi +} + +run_script() { + tmp=$1 + API_USERNAME=u API_PASSWORD=p PATH="$tmp/bin:$PATH" bash "$tmp/s.sh" +} + +@test "an empty render fails the fixture instead of passing as a no-op" { + tmp=$(mktemp -d) + CHART=$tmp/no-such-chart + if render_script "$tmp/s.sh" backup myapp 2>/dev/null; then + echo "FAIL: render_script reported success with no chart" + false + fi +} + +@test "backup on an idle sidecar starts create_remote and waits for its success" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + render_script "$tmp/s.sh" backup myapp + run_script "$tmp" + grep -q '^POST .*/backup/create_remote?name=clickhouse-myapp-' "$tmp/state/requests" +} + +@test "backup waits until the running operation finishes before create_remote" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + echo 3 > "$tmp/state/busy" + render_script "$tmp/s.sh" backup myapp + run_script "$tmp" + grep -q '^create_remote --resume clickhouse-myapp-' "$tmp/state/accepted" + [ "$(cat "$tmp/state/busy")" = 0 ] +} + +@test "restore on an idle sidecar starts restore_remote of the listed archive" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + render_script "$tmp/s.sh" restore myapp + run_script "$tmp" + grep -q '^POST .*/backup/restore_remote/clickhouse-myapp-20260101T000000Z$' "$tmp/state/requests" +} + +@test "backup fails without starting create_remote when the sidecar stays busy" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + echo 1000 > "$tmp/state/busy" + render_script "$tmp/s.sh" backup myapp + if run_script "$tmp"; then echo "FAIL: a busy sidecar must fail the Pod"; false; fi + if grep -q '^POST ' "$tmp/state/requests"; then echo "FAIL: no operation may start on a busy sidecar"; false; fi +} + +@test "backup fails without starting create_remote when the sidecar never answers" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + touch "$tmp/state/unreachable" + render_script "$tmp/s.sh" backup myapp + if run_script "$tmp"; then echo "FAIL: an unreachable sidecar must fail the Pod"; false; fi + if grep -q '^POST ' "$tmp/state/requests"; then echo "FAIL: no operation may start on an unreachable sidecar"; false; fi +} + +@test "restore fails without starting restore_remote when the sidecar never answers" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + touch "$tmp/state/unreachable" + render_script "$tmp/s.sh" restore myapp + if run_script "$tmp" 2> "$tmp/err"; then echo "FAIL: an unreachable sidecar must fail the Pod"; false; fi + if grep -q '^POST ' "$tmp/state/requests"; then echo "FAIL: no restore may start on an unreachable sidecar"; false; fi + grep -q 'list/remote failed 60 times in a row' "$tmp/err" + [ "$(grep -c '^GET .*/backup/list/remote$' "$tmp/state/requests")" = 60 ] +} + +@test "restore fails without starting restore_remote when the sidecar stays busy" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + echo 1000 > "$tmp/state/busy" + render_script "$tmp/s.sh" restore myapp + if run_script "$tmp"; then echo "FAIL: a busy sidecar must fail the Pod"; false; fi + if grep -q '^POST ' "$tmp/state/requests"; then echo "FAIL: no restore may start on a busy sidecar"; false; fi +} + +@test "backup fails instead of polling forever when the sidecar restarts after create_remote" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + touch "$tmp/state/restarted" + render_script "$tmp/s.sh" backup myapp + if run_script "$tmp" 2> "$tmp/err"; then echo "FAIL: an operation lost from the action log must fail the Pod"; false; fi + grep -q 'no longer in the sidecar action log' "$tmp/err" + grep -q '^POST .*/backup/create_remote?name=clickhouse-myapp-' "$tmp/state/requests" + if [ -e "$tmp/state/runaway" ]; then echo "FAIL: the script kept polling for an operation the sidecar no longer lists"; false; fi +} + +@test "restore waits for a sidecar that has not started yet" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + echo 10 > "$tmp/state/down" + render_script "$tmp/s.sh" restore myapp + run_script "$tmp" + [ "$(accepted "$tmp")" = 1 ] +} + +@test "restore waits until another operation finishes, then starts its own" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + echo 3 > "$tmp/state/busy" + render_script "$tmp/s.sh" restore myapp + run_script "$tmp" + [ "$(accepted "$tmp")" = 1 ] + grep -qx 'restore_remote clickhouse-myapp-20260101T000000Z' "$tmp/state/accepted" +} + +@test "failed polls after restore_remote, short of six in a row, do not fail the attempt" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + echo 3 > "$tmp/state/op_duration" + echo 5 > "$tmp/state/fail_on_post" + render_script "$tmp/s.sh" restore myapp + run_script "$tmp" + [ "$(accepted "$tmp")" = 1 ] +} + +@test "a retry after an attempt lost its polls joins the running restore instead of starting another" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + echo 20 > "$tmp/state/op_duration" + echo 6 > "$tmp/state/fail_on_post" + render_script "$tmp/s.sh" restore myapp + if run_script "$tmp"; then echo "FAIL: six failed polls in a row must fail the attempt"; false; fi + [ "$(accepted "$tmp")" = 1 ] + echo 0 > "$tmp/state/fail_polls" + run_script "$tmp" + if [ "$(accepted "$tmp")" != 1 ]; then echo "FAIL: the retry started restore_remote a second time"; false; fi + [ "$(cat "$tmp/state/op_left")" = 0 ] +} + +@test "restore does not join an operation running on another archive" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + echo 'restore_remote clickhouse-myapp-20251231T000000Z' > "$tmp/state/op" + echo 3 > "$tmp/state/op_left" + render_script "$tmp/s.sh" restore myapp + run_script "$tmp" + [ "$(accepted "$tmp")" = 1 ] + grep -qx 'restore_remote clickhouse-myapp-20260101T000000Z' "$tmp/state/accepted" +} + +# The sidecar never trims its action log, so a finished restore_remote row of +# the same archive may belong to an earlier RestoreJob; only a running one may +# be taken over. +@test "restore starts restore_remote again when the log holds a finished one of the same archive" { + for status in success error cancel; do + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + echo "{\"command\":\"restore_remote clickhouse-myapp-20260101T000000Z\",\"status\":\"$status\",\"start\":\"2026-01-01 00:01:30\"}" > "$tmp/state/prior" + render_script "$tmp/s.sh" restore myapp + run_script "$tmp" + if [ "$(accepted "$tmp")" != 1 ]; then echo "FAIL: a $status row of an earlier restore must not stand in for this one"; false; fi + done +} + +@test "a restore that ends in error fails the Pod" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + echo error > "$tmp/state/op_result" + render_script "$tmp/s.sh" restore myapp + if run_script "$tmp"; then echo "FAIL: a failed restore must fail the Pod"; false; fi + [ "$(accepted "$tmp")" = 1 ] +} + +@test "a cancelled backup fails the Pod instead of polling forever" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + echo cancel > "$tmp/state/op_result" + render_script "$tmp/s.sh" backup myapp + if run_script "$tmp"; then echo "FAIL: a cancelled operation must fail the Pod"; false; fi + if [ -e "$tmp/state/runaway" ]; then echo "FAIL: the script kept polling a cancelled operation"; false; fi +} + +@test "restore reads back the archive the Backup recorded, not the newest one" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + render_script "$tmp/s.sh" restore myapp clickhouse-myapp-20260304T050607Z bkp-a 20260304T050622Z + remote_rows clickhouse-myapp-20260304T040000Z clickhouse-myapp-20260304T050607Z \ + clickhouse-myapp-20260304T060000Z clickhouse-myapp-20260304T070000Z > "$tmp/state/remote" + run_script "$tmp" + grep -qxF 'POST http://chi-clickhouse-myapp-clickhouse-0-0.tenant-x.svc:7171/backup/restore_remote/clickhouse-myapp-20260304T050607Z' "$tmp/state/requests" + [ "$(accepted "$tmp")" = 1 ] +} + +@test "restore fails naming the recorded archive when remote storage lacks it" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + render_script "$tmp/s.sh" restore myapp clickhouse-myapp-20260304T050607Z bkp-a 20260304T050622Z + remote_rows clickhouse-myapp-20260304T040000Z clickhouse-myapp-20260304T060000Z > "$tmp/state/remote" + out="" + if out=$(run_script "$tmp" 2>&1); then + echo "FAIL: restore succeeded without the recorded archive: $out" + false + fi + printf '%s\n' "$out" | grep -qF 'archive clickhouse-myapp-20260304T050607Z recorded on Backup bkp-a is not in remote storage' + if grep -qF '/backup/restore_remote/' "$tmp/state/requests"; then + echo "FAIL: restored another archive: $(cat "$tmp/state/requests")" + false + fi +} + +@test "restore of a Backup without a recorded archive takes the newest one stamped by its takenAt, and warns" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + render_script "$tmp/s.sh" restore myapp "" bkp-a 20260304T050800Z + # Each decoy sorts after the expected archive and is ruled out by one + # filter: broken, not a bare timestamp after the prefix, or stamped after + # takenAt. + remote_rows clickhouse-myapp-20260304T040000Z clickhouse-myapp-20260304T050607Z \ + "clickhouse-myapp-20260304T050700Z|broken (can't stat metadata.json)" \ + clickhouse-myapp-20260304T050710Z-copy \ + myapp-20260304050720-0f3c9a1e5b7d \ + clickhouse-myapp-20260304T060000Z > "$tmp/state/remote" + out=$(run_script "$tmp" 2>&1) + grep -qxF 'POST http://chi-clickhouse-myapp-clickhouse-0-0.tenant-x.svc:7171/backup/restore_remote/clickhouse-myapp-20260304T050607Z' "$tmp/state/requests" + [ "$(accepted "$tmp")" = 1 ] + printf '%s\n' "$out" | grep -qF 'WARNING: Backup bkp-a records no archive name' +} + +@test "restore of a Backup without a recorded archive fails when no archive is stamped by its takenAt" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + render_script "$tmp/s.sh" restore myapp "" bkp-a 20260304T050800Z + remote_rows clickhouse-myapp-20260304T060000Z clickhouse-myapp-20260304T070000Z > "$tmp/state/remote" + out="" + if out=$(run_script "$tmp" 2>&1); then + echo "FAIL: restore succeeded with every archive newer than takenAt: $out" + false + fi + printf '%s\n' "$out" | grep -qF 'no archive of myapp stamped no later than 20260304T050800Z' + if grep -qF '/backup/restore_remote/' "$tmp/state/requests"; then + echo "FAIL: restored an archive newer than takenAt: $(cat "$tmp/state/requests")" + false + fi +} + +@test "backup writes the archive under the name the controller chose" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + render_script "$tmp/s.sh" backup myapp clickhouse-myapp-20260304T050607Z + run_script "$tmp" + grep -qxF 'POST http://chi-clickhouse-myapp-clickhouse-0-0.tenant-x.svc:7171/backup/create_remote?name=clickhouse-myapp-20260304T050607Z&resume=true' "$tmp/state/requests" +} + +@test "backup falls back to a timestamped name when the controller supplies none" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + render_script "$tmp/s.sh" backup myapp "" + run_script "$tmp" + grep -qE '^POST http://[^ ]*/backup/create_remote\?name=clickhouse-myapp-[0-9]{8}T[0-9]{6}Z&resume=true$' "$tmp/state/requests" +} + +# The sidecar answers a second operation with 423 while one runs, so a retry +# that POSTed over its predecessor's upload would burn every attempt left. +@test "a retried backup takes over the upload of its archive the sidecar is still running" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + echo 'create_remote --resume clickhouse-myapp-20260304T050607Z' > "$tmp/state/op" + echo 3 > "$tmp/state/op_left" + render_script "$tmp/s.sh" backup myapp clickhouse-myapp-20260304T050607Z + run_script "$tmp" + if grep -q '^POST ' "$tmp/state/requests"; then + echo "FAIL: started another operation over the running one: $(cat "$tmp/state/requests")" + false + fi + [ "$(cat "$tmp/state/op_left")" = 0 ] +} + +@test "a taken-over backup that ends in error fails the Pod" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + echo 'create_remote --resume clickhouse-myapp-20260304T050607Z' > "$tmp/state/op" + echo 2 > "$tmp/state/op_left" + echo error > "$tmp/state/op_result" + render_script "$tmp/s.sh" backup myapp clickhouse-myapp-20260304T050607Z + if run_script "$tmp"; then echo "FAIL: a taken-over upload that failed must fail the Pod"; false; fi + if grep -q '^POST ' "$tmp/state/requests"; then + echo "FAIL: started another operation over the running one: $(cat "$tmp/state/requests")" + false + fi +} + +@test "a retried backup after a failed attempt resumes the same archive" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + echo '{"command":"create_remote clickhouse-myapp-20260304T050607Z","status":"error","start":"2026-01-01 00:01:30","error":"S3 PutObject 403"}' > "$tmp/state/prior" + render_script "$tmp/s.sh" backup myapp clickhouse-myapp-20260304T050607Z + run_script "$tmp" + grep -qxF 'POST http://chi-clickhouse-myapp-clickhouse-0-0.tenant-x.svc:7171/backup/create_remote?name=clickhouse-myapp-20260304T050607Z&resume=true' "$tmp/state/requests" +} + +@test "backup does not take over an upload running for another archive" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + echo 'create_remote --resume clickhouse-myapp-20260304T040000Z' > "$tmp/state/op" + echo 3 > "$tmp/state/op_left" + render_script "$tmp/s.sh" backup myapp clickhouse-myapp-20260304T050607Z + run_script "$tmp" + [ "$(accepted "$tmp")" = 1 ] + grep -qx 'create_remote --resume clickhouse-myapp-20260304T050607Z' "$tmp/state/accepted" +} + +# The archive is named per BackupJob, so a success row of exactly this +# upload is an earlier attempt of the same BackupJob that finished while it +# could not see it. Uploading again with resume would re-upload over the +# finished archive and break it if that second upload dies halfway. +@test "a retried backup takes the upload of its archive an earlier attempt finished as its result" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + echo '{"command":"create_remote --resume clickhouse-myapp-20260304T050607Z","status":"success","start":"2026-01-01 00:01:30"}' > "$tmp/state/prior" + render_script "$tmp/s.sh" backup myapp clickhouse-myapp-20260304T050607Z + run_script "$tmp" + if grep -q '^POST ' "$tmp/state/requests"; then + echo "FAIL: uploaded again over a finished archive: $(cat "$tmp/state/requests")" + false + fi +} + +@test "a retried backup resumes an upload of its archive that ended in error or was cancelled" { + for status in error cancel; do + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + echo "{\"command\":\"create_remote --resume clickhouse-myapp-20260304T050607Z\",\"status\":\"$status\",\"start\":\"2026-01-01 00:01:30\"}" > "$tmp/state/prior" + render_script "$tmp/s.sh" backup myapp clickhouse-myapp-20260304T050607Z + run_script "$tmp" + if [ "$(accepted "$tmp")" != 1 ]; then echo "FAIL: a $status row must lead to a resumed upload"; false; fi + done +} + +@test "a retried backup resumes when its latest upload failed after an earlier one succeeded" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + printf '%s\n' \ + '{"command":"create_remote --resume clickhouse-myapp-20260304T050607Z","status":"success","start":"2026-01-01 00:01:00"}' \ + '{"command":"create_remote --resume clickhouse-myapp-20260304T050607Z","status":"error","start":"2026-01-01 00:01:30"}' > "$tmp/state/prior" + render_script "$tmp/s.sh" backup myapp clickhouse-myapp-20260304T050607Z + run_script "$tmp" + [ "$(accepted "$tmp")" = 1 ] +} + +@test "backup does not take another archive's finished upload as its own" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp/state" + echo '{"command":"create_remote --resume clickhouse-myapp-20260304T040000Z","status":"success","start":"2026-01-01 00:01:30"}' > "$tmp/state/prior" + render_script "$tmp/s.sh" backup myapp clickhouse-myapp-20260304T050607Z + run_script "$tmp" + [ "$(accepted "$tmp")" = 1 ] +} diff --git a/hack/app-cleanup-hooks_test.bats b/hack/app-cleanup-hooks_test.bats index 006d7474c..672dcc541 100644 --- a/hack/app-cleanup-hooks_test.bats +++ b/hack/app-cleanup-hooks_test.bats @@ -19,12 +19,15 @@ # already-clean namespace exits 0; # * a listing that FAILED is distinguishable from one that returned nothing. # -# Run via hack/cozytest.sh from the repo root (make bats-unit-tests); relative -# paths resolve against that cwd. The runner has no setup/teardown, so each -# @test builds its own fixture and removes it at the end of the body. No EXIT +# Run from the repo root through `make bats-unit-tests`; relative paths resolve +# against that cwd. The file also remains compatible with the legacy +# `hack/cozytest.sh` translator, so each @test builds and removes its fixture +# inline instead of relying on setup()/teardown(). No EXIT # trap: docs/agents/e2e-testing.md bans them in hack/*.bats, and under the bats # binary a test that installs one and then fails prints no TAP line at all. +load test_helper + QDRANT_CHART=packages/apps/qdrant HARBOR_CHART=packages/apps/harbor diff --git a/hack/backport-batch-scheduled.bats b/hack/backport-batch-scheduled.bats new file mode 100644 index 000000000..e844869e8 --- /dev/null +++ b/hack/backport-batch-scheduled.bats @@ -0,0 +1,186 @@ +#!/usr/bin/env bats +# Tests for hack/backport-batch-scheduled.sh, the scheduled backport batch, and +# for the workflow that runs it, .github/workflows/backport-batch.yaml. +# +# The backport-batch binary is stubbed through BACKPORT_BATCH: every call is +# recorded with the tokens gh would see, `lines` answers with $STUB_LINES, and +# a subcommand fails for the line named in $STUB_FAIL_. +# +# Run with: bats hack/backport-batch-scheduled.bats + +load test_helper + +SCRIPT="${BATS_TEST_DIRNAME}/backport-batch-scheduled.sh" +WF="${BATS_TEST_DIRNAME}/../.github/workflows/backport-batch.yaml" + +setup() { + strict_setup + export TMPDIR="$BATS_TEST_TMPDIR" + export CALLS="${BATS_TEST_TMPDIR}/calls" + export BACKPORT_BATCH="${BATS_TEST_TMPDIR}/backport-batch" + cat > "$BACKPORT_BATCH" <<'EOF' +#!/usr/bin/env bash +printf 'GH_TOKEN=%s GITHUB_TOKEN=%s %s\n' "${GH_TOKEN-unset}" "${GITHUB_TOKEN-unset}" "$*" >> "$CALLS" +line=${3:-} +case "$1" in + lines) printf '%s\n' $STUB_LINES ;; + run) [ "${STUB_FAIL_run:-}" != "$line" ] || exit 2 ;; + check) [ "${STUB_FAIL_check:-}" != "$line" ] || exit 1 ;; + notify) + [ "${STUB_FAIL_notify:-}" != "$line" ] || exit 2 + echo "$line: something waits" + ;; +esac +EOF + chmod +x "$BACKPORT_BATCH" + export STUB_LINES="release-1.7 release-1.6" + unset STUB_FAIL_run STUB_FAIL_check STUB_FAIL_notify + unset BACKPORT_ALERT_TEAM GITHUB_STEP_SUMMARY GH_TOKEN + export GITHUB_TOKEN=job-token + export BACKPORT_BATCH_TOKEN=batch-token + : > "$CALLS" +} + +# The calls recorded, without the token fields. +calls() { + sed 's/^GH_TOKEN=[^ ]* GITHUB_TOKEN=[^ ]* //' "$CALLS" +} + +@test "runs, checks and reports each line, newest first, pushing with the batch's token alone" { + run "$SCRIPT" + [ "$status" -eq 0 ] + [ "$(calls)" = "lines +run --line release-1.7 --continue --push +check --line release-1.7 +notify --line release-1.7 --push +run --line release-1.6 --continue --push +check --line release-1.6 +notify --line release-1.6 --push" ] + # Every call sees the batch's token, and the job's token is gone. + [ "$(grep -c '^GH_TOKEN=batch-token GITHUB_TOKEN=unset ' "$CALLS")" -eq 7 ] +} + +@test "a dry run pushes, opens and comments nothing, and needs no token" { + unset BACKPORT_BATCH_TOKEN + run "$SCRIPT" --dry-run + [ "$status" -eq 0 ] + if grep -q -- '--push' "$CALLS"; then + echo "a dry run passed --push:"; cat "$CALLS" + false + fi + [ "$(calls | grep -c '^run --line release-.* --continue$')" -eq 2 ] + [ "$(calls | grep -c '^notify --line release-.*[0-9]$')" -eq 2 ] +} + +@test "--no-workflow-files reaches run alone, and an unknown argument stops the script" { + run "$SCRIPT" --no-workflow-files + [ "$status" -eq 0 ] + [ "$(calls | grep -c '^run --line release-.* --continue --no-workflow-files --push$')" -eq 2 ] + if calls | grep -v '^run ' | grep -q -- '--no-workflow-files'; then + echo "the flag reached another command:"; calls + false + fi + + : > "$CALLS" + run "$SCRIPT" --dry-run --no-workflow-files + [ "$status" -eq 0 ] + [ "$(calls | grep -c '^run --line release-.* --continue --no-workflow-files$')" -eq 2 ] + + : > "$CALLS" + run "$SCRIPT" --no-workflows + [ "$status" -eq 2 ] + [ ! -s "$CALLS" ] +} + +@test "without BACKPORT_BATCH_TOKEN it stops before anything, even with the job's token" { + unset BACKPORT_BATCH_TOKEN + run "$SCRIPT" + [ "$status" -eq 2 ] + [[ "$output" == *"BACKPORT_BATCH_TOKEN is empty"* ]] + [ ! -s "$CALLS" ] +} + +@test "outside a worktree of the repository it stops before anything" { + export GIT_CEILING_DIRECTORIES="$BATS_TEST_TMPDIR" + mkdir "$BATS_TEST_TMPDIR/elsewhere" + cd "$BATS_TEST_TMPDIR/elsewhere" + run "$SCRIPT" + [ "$status" -eq 2 ] + [[ "$output" == *"not in a worktree of the repository"* ]] + [ ! -s "$CALLS" ] +} + +@test "the team is mentioned only when BACKPORT_ALERT_TEAM is set" { + export BACKPORT_ALERT_TEAM=cozystack/maintainers + run "$SCRIPT" + [ "$status" -eq 0 ] + [ "$(calls | grep -c '^notify --line release-.* --mention cozystack/maintainers --push$')" -eq 2 ] + + export BACKPORT_ALERT_TEAM= + : > "$CALLS" + run "$SCRIPT" + [ "$status" -eq 0 ] + if grep -q -- '--mention' "$CALLS"; then + echo "an empty team was mentioned:"; cat "$CALLS" + false + fi +} + +@test "a line that fails goes into the summary, the other line still runs, and the job fails" { + export GITHUB_STEP_SUMMARY="${BATS_TEST_TMPDIR}/summary" + export STUB_FAIL_run=release-1.7 STUB_FAIL_check=release-1.6 + run "$SCRIPT" + [ "$status" -eq 1 ] + [ "$(calls | grep -c '^run --line release-1.6 ')" -eq 1 ] + grep -qx -- '- release-1.7: the run failed with exit 2' "$GITHUB_STEP_SUMMARY" + grep -qx -- '- release-1.6: the check exited 1; see its output above' "$GITHUB_STEP_SUMMARY" + grep -qx -- '- release-1.7: something waits' "$GITHUB_STEP_SUMMARY" + + # Each failure fails the job on its own. + export STUB_FAIL_run=release-1.7 STUB_FAIL_check= + run "$SCRIPT" + [ "$status" -eq 1 ] + export STUB_FAIL_run= STUB_FAIL_check=release-1.6 + run "$SCRIPT" + [ "$status" -eq 1 ] + export STUB_FAIL_check= STUB_FAIL_notify=release-1.6 + run "$SCRIPT" + [ "$status" -eq 1 ] + export STUB_FAIL_notify= + run "$SCRIPT" + [ "$status" -eq 0 ] +} + +@test "the workflow runs Monday and Thursday as the cozystack-ci App and never with the job's token" { + [ "$(yq -r '.on.schedule[0].cron' "$WF")" = "23 6 * * 1,4" ] + [ "$(yq -r '.on.schedule | length' "$WF")" -eq 1 ] + [ "$(yq -o=json -I=0 '.permissions' "$WF")" = "{}" ] + [ "$(yq -o=json -I=0 '.jobs.batch.permissions' "$WF")" = '{"contents":"read"}' ] + [ "$(yq -r '.jobs.batch.steps[] | select(.uses == "actions/checkout*") | .with."persist-credentials"' "$WF")" = "false" ] + run_step='.jobs.batch.steps[] | select(.name == "Run the batch")' + [ "$(yq -r "$run_step | .run" "$WF")" = "hack/backport-batch-scheduled.sh --no-workflow-files" ] + [ "$(yq -r "$run_step | .env.BACKPORT_BATCH_TOKEN" "$WF")" = '${{ steps.app-token.outputs.token }}' ] + [ "$(yq -r "$run_step | .env.BACKPORT_BATCH_BOT" "$WF")" = '${{ steps.app-token.outputs.app-slug }}[bot]' ] + + # The App token covers this repository alone, with Contents and Pull + # requests and nothing else: no workflows, no packages. + mint='.jobs.batch.steps[] | select(.id == "app-token")' + [ "$(yq -r "$mint | .uses" "$WF")" = "actions/create-github-app-token@d72941d797fd3113feb6b93fd0dec494b13a2547" ] + [ "$(yq -r "$mint | .with.owner" "$WF")" = "cozystack" ] + [ "$(yq -r "$mint | .with.repositories" "$WF")" = "cozystack" ] + [ "$(yq -r "$mint | .with | to_entries | map(select(.key | test(\"^permission-\"))) | map(.key + \"=\" + .value) | join(\",\")" "$WF")" = "permission-contents=write,permission-pull-requests=write" ] + # A token minted after the checkout lives an hour; the job ends before. + [ "$(yq -r '.jobs.batch."timeout-minutes"' "$WF")" -le 45 ] + + # The commits carry the App's bot, read from the token, not a person. + identity='.jobs.batch.steps[] | select(.name == "Use the App'"'"'s bot as git identity and credential")' + [ "$(yq -r "$identity | .env.APP_SLUG" "$WF")" = '${{ steps.app-token.outputs.app-slug }}' ] + yq -r "$identity | .run" "$WF" | grep -qF 'gh api "/users/${APP_SLUG}[bot]" --jq .id' + yq -r "$identity | .run" "$WF" | grep -qF 'user.email "${id}+${APP_SLUG}[bot]@users.noreply.github.com"' + + # No step reaches for the job's own token or a person's batch token. + if grep -v '^[[:space:]]*#' "$WF" | grep -Eq 'secrets\.GITHUB_TOKEN|github\.token|secrets\.BACKPORT_BATCH_TOKEN|gh api user'; then + echo "the workflow reads the job's own token or a person's" + false + fi +} diff --git a/hack/backport-batch-scheduled.sh b/hack/backport-batch-scheduled.sh new file mode 100755 index 000000000..ddc7f886d --- /dev/null +++ b/hack/backport-batch-scheduled.sh @@ -0,0 +1,122 @@ +#!/usr/bin/env bash +# The scheduled backport batch (docs/release/backports.md): for each line the +# batch runs for, newest first, continue the open batch pull request or open +# one, check the line, and report what waits on the batch. This is what +# .github/workflows/backport-batch.yaml runs; a maintainer can run it by hand +# from a clean worktree of the repository. +# +# Usage: backport-batch-scheduled.sh [--dry-run] [--no-workflow-files] +# +# --dry-run builds and checks each batch in this worktree and prints what it +# would report, but pushes nothing, opens or edits no pull request and writes +# no comment. Its check sees the line without the batch it just built, so it +# can exit 1 where the real run's check passes. Without --dry-run the batch's +# token has to be in BACKPORT_BATCH_TOKEN, and it is the only token gh sees: +# the job's own GITHUB_TOKEN is never a fallback, because a push made with it +# starts no CI on the batch pull request. The workflow passes the cozystack-ci +# App's token; a maintainer running this by hand passes their own. +# +# --no-workflow-files goes to run: an original that changes .github/workflows/ +# is left on the batch pull request for a maintainer instead of picked, for a +# token that may not push such a commit, as the workflow's is. +# +# Environment: +# BACKPORT_BATCH the backport-batch binary (default: built from this tree) +# BACKPORT_BATCH_TOKEN the token the batch pushes, opens and comments with +# BACKPORT_BATCH_BOT the bot the scheduled batch writes as, [bot], +# whose batch pull request and comment are trusted; +# cozystack-ci[bot] when unset +# BACKPORT_ALERT_TEAM the team or person the batch's comment mentions, +# org/team or a login; nobody is mentioned when it is +# unset +# GITHUB_STEP_SUMMARY when set, each finding is appended to it as a line +# +# Exits 0 when every line ran and its check passed, 1 when a line's run, +# check or report failed, and 2 on a usage or setup error. +set -euo pipefail + +die() { + echo "backport-batch-scheduled: $*" >&2 + exit 2 +} + +usage="usage: backport-batch-scheduled.sh [--dry-run] [--no-workflow-files]" +dry_run=false +# An empty array expands under set -u only as ${a[@]+"${a[@]}"} on bash before +# 4.4, which is what macOS ships. +workflows=() +for arg in "$@"; do + case "$arg" in + --dry-run) dry_run=true ;; + --no-workflow-files) workflows=(--no-workflow-files) ;; + *) die "$usage" ;; + esac +done + +push=() +if ! $dry_run; then + [ -n "${BACKPORT_BATCH_TOKEN:-}" ] || + die "BACKPORT_BATCH_TOKEN is empty; the workflow sets it to the cozystack-ci App's token, a run by hand to your own (docs/release/backports.md#the-scheduled-run). The job's GITHUB_TOKEN is not used: its pushes start no CI." + export GH_TOKEN="$BACKPORT_BATCH_TOKEN" + unset GITHUB_TOKEN + push=(--push) +fi + +mention=() +if [ -n "${BACKPORT_ALERT_TEAM:-}" ]; then + mention=(--mention "$BACKPORT_ALERT_TEAM") +fi + +top=$(git rev-parse --show-toplevel) || die "not in a worktree of the repository" +cd "$top" +out=$(mktemp -d) +bin=${BACKPORT_BATCH:-} +if [ -z "$bin" ]; then + # Built before the first run switches this tree to a batch branch, whose + # line may not have the tool at all. + bin="$out/backport-batch" + go build -o "$bin" ./cmd/backport-batch +fi + +report() { + echo "$1" + if [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then + printf -- '- %s\n' "$1" >> "$GITHUB_STEP_SUMMARY" + fi +} + +if [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then + printf '## Backport batch\n\n' >> "$GITHUB_STEP_SUMMARY" +fi +lines=$("$bin" lines) || die "cannot list the release lines" +[ -n "$lines" ] || die "no release line to run the batch for" + +status=0 +for line in $lines; do + echo "::group::$line" + rc=0 + "$bin" run --line "$line" --continue ${workflows[@]+"${workflows[@]}"} ${push[@]+"${push[@]}"} > "$out/$line.md" || rc=$? + if [ "$rc" -ne 0 ]; then + report "$line: the run failed with exit $rc" + status=1 + elif $dry_run; then + report "$line: the batch is built in this tree, its body in $out/$line.md" + fi + rc=0 + "$bin" check --line "$line" || rc=$? + if [ "$rc" -ne 0 ]; then + report "$line: the check exited $rc; see its output above" + status=1 + fi + rc=0 + notes=$("$bin" notify --line "$line" ${mention[@]+"${mention[@]}"} ${push[@]+"${push[@]}"}) || rc=$? + while IFS= read -r note; do + [ -z "$note" ] || report "$note" + done <<< "$notes" + if [ "$rc" -ne 0 ]; then + report "$line: reporting what waits on the batch failed with exit $rc" + status=1 + fi + echo "::endgroup::" +done +exit "$status" diff --git a/hack/backport-batch-tests-needed.bats b/hack/backport-batch-tests-needed.bats new file mode 100644 index 000000000..9f37e768f --- /dev/null +++ b/hack/backport-batch-tests-needed.bats @@ -0,0 +1,87 @@ +#!/usr/bin/env bats +# Unit tests for hack/backport-batch-tests-needed.sh, which decides whether a +# pull request runs `make test-backport-batch`, and for its wiring into the +# checks job of pull-requests.yaml. +# +# Test-level EXIT traps replace Bats' own handler and hide failing TAP results. +# Cleanup follows aborting assertions; see docs/agents/e2e-testing.md. + +load test_helper + +CLASSIFIER="hack/backport-batch-tests-needed.sh" +WF=".github/workflows/pull-requests.yaml" + +classify() { + list="$1" + shift + printf '%s\n' "$@" > "$list" + "$CLASSIFIER" "$list" +} + +@test "a change to the tool, an imported package, a page its tests read or the module runs the tests" { + tmp=$(mktemp) + [ "$(classify "$tmp" cmd/backport-batch/report_test.go)" = true ] + [ "$(classify "$tmp" internal/apigate/surface.go)" = true ] + [ "$(classify "$tmp" pkg/config/config.go)" = true ] + [ "$(classify "$tmp" docs/release/backports.md)" = true ] + [ "$(classify "$tmp" docs/release/backport-tasks/conflict.md)" = true ] + [ "$(classify "$tmp" go.sum)" = true ] + # One input among unrelated paths is enough. + [ "$(classify "$tmp" packages/apps/mariadb/values.yaml pkg/config/config.go)" = true ] + rm -f "$tmp" +} + +@test "a change that reaches none of its inputs does not run the tests" { + tmp=$(mktemp) + [ "$(classify "$tmp" packages/apps/mariadb/values.yaml)" = false ] + [ "$(classify "$tmp" cmd/api-gate/main.go)" = false ] + [ "$(classify "$tmp" hack/backport-batch-scheduled.sh)" = false ] + [ "$(classify "$tmp" docs/release.md docs/release/other.md)" = false ] + # A file entry is not a prefix: backports.md does not cover backports.md.bak, + # and a directory entry does not cover a sibling sharing its name as prefix. + [ "$(classify "$tmp" docs/release/backports.md.bak)" = false ] + [ "$(classify "$tmp" pkg/configx/x.go)" = false ] + [ "$(classify "$tmp" internal/apigate-old/x.go)" = false ] + rm -f "$tmp" +} + +@test "entries are trimmed as the Go test trims them" { + tmp=$(mktemp -d) + printf '%s\n' cmd/backport-batch/main.go > "$tmp/diff" + printf ' cmd/backport-batch/ \r\n' > "$tmp/inputs" + [ "$("$CLASSIFIER" "$tmp/diff" "$tmp/inputs")" = true ] + rm -rf "$tmp" +} + +@test "an inputs file with no entry is refused rather than read as never" { + tmp=$(mktemp -d) + printf '%s\n' cmd/backport-batch/main.go > "$tmp/diff" + printf '# only a comment\n\n' > "$tmp/inputs" + if "$CLASSIFIER" "$tmp/diff" "$tmp/inputs" >"$tmp/out" 2>"$tmp/err"; then + echo "an empty inputs file must fail, it printed: $(cat "$tmp/out")" >&2 + exit 1 + fi + grep -q 'lists no path' "$tmp/err" + rm -rf "$tmp" +} + +@test "the checks job runs the target on the classifier's answer alone" { + plan_run=$(yq -r '.jobs.plan.steps[] | select(.id == "p") | .run' "$WF") + printf '%s\n' "$plan_run" | grep -qF 'backport_batch="$(hack/backport-batch-tests-needed.sh /tmp/changed_norenames.txt)"' + [ "$(yq -r '.jobs.plan.outputs.backport_batch' "$WF")" = '${{ steps.p.outputs.backport_batch }}' ] + + step_if=$(yq -r '.jobs.checks.steps[] | select(.name == "Run backport-batch tests") | .if' "$WF") + step_run=$(yq -r '.jobs.checks.steps[] | select(.name == "Run backport-batch tests") | .run' "$WF") + # !cancelled(): a failed unit lane above must not skip this suite too. + [ "$step_if" = "\${{ !cancelled() && needs.plan.outputs.backport_batch == 'true' }}" ] + [ "$step_run" = 'make test-backport-batch' ] + + # And nowhere else: the unit lane every code PR runs must not carry it. + prereqs=$(sed -n 's/^unit-tests:[[:space:]]*//p' Makefile) + [ -n "$prereqs" ] + case " $prereqs " in + *" test-backport-batch "*) + echo "make unit-tests still runs test-backport-batch on every code PR: $prereqs" >&2 + exit 1 ;; + esac +} diff --git a/hack/backport-batch-tests-needed.sh b/hack/backport-batch-tests-needed.sh new file mode 100755 index 000000000..71803e730 --- /dev/null +++ b/hack/backport-batch-tests-needed.sh @@ -0,0 +1,44 @@ +#!/bin/sh +# Print whether a changed-path list touches an input of +# `go test ./cmd/backport-batch/...`, as listed in +# cmd/backport-batch/test-inputs.txt. An entry ending in / matches every path +# below it, any other entry matches that file alone. The caller supplies the +# rename-blind list so both sides of a rename are classified. +# +# Usage: hack/backport-batch-tests-needed.sh [] +set -eu + +inputs="${2:-cmd/backport-batch/test-inputs.txt}" +if [ "$#" -lt 1 ] || [ "$#" -gt 2 ] || [ ! -r "$1" ] || [ ! -r "$inputs" ]; then + echo "usage: backport-batch-tests-needed.sh []" >&2 + exit 2 +fi + +# An inputs file with no entry would answer false for every diff and switch the +# tests off without a word; refuse instead. +if ! grep -qvE '^[[:space:]]*(#|$)' "$inputs"; then + echo "backport-batch-tests-needed: $inputs lists no path" >&2 + exit 2 +fi + +# Entries are trimmed the way TestInputsListed trims them, so a trailing space +# or a CR cannot make the Go test accept an entry this never matches. +awk ' + NR == FNR { + e = $0 + sub(/^[[:space:]]+/, "", e) + sub(/[[:space:]]+$/, "", e) + if (e != "" && e !~ /^#/) entries[++n] = e + next + } + { + for (i = 1; i <= n; i++) { + e = entries[i] + if ((substr(e, length(e)) == "/" && index($0, e) == 1) || $0 == e) { + found = 1 + exit + } + } + } + END { print (found ? "true" : "false") } +' "$inputs" "$1" diff --git a/hack/backport-batch-verify-job.bats b/hack/backport-batch-verify-job.bats new file mode 100644 index 000000000..5cc0c1597 --- /dev/null +++ b/hack/backport-batch-verify-job.bats @@ -0,0 +1,59 @@ +#!/usr/bin/env bats +# Contract for the backport-batch-verify job of .github/workflows/pr-labeler.yaml, +# which runs `backport-batch verify` on every push to a batch pull request. +# +# The job runs under pull_request_target, so it holds a token on a pull +# request's events and must never run code from the pull request. These tests +# pin what keeps it that way: the tool is built from main, the head is only +# fetched, the token reads contents and nothing more, and no expression +# reaches a shell. +# +# Run with: bats hack/backport-batch-verify-job.bats + +load test_helper + +WF="${BATS_TEST_DIRNAME}/../.github/workflows/pr-labeler.yaml" +JOB='.jobs.backport-batch-verify' + +@test "the job runs on pull_request_target, so main's copy reaches release lines" { + [ "$(yq -r '.on | keys | .[]' "$WF")" = "pull_request_target" ] + [ "$(yq -r "$JOB.name" "$WF")" = "Backport batch shape" ] +} + +@test "the job runs only for a batch branch of this repository into a release line" { + cond="$(yq -r "$JOB.if" "$WF")" + [[ "$cond" == *"startsWith(github.event.pull_request.base.ref, 'release-')"* ]] + [[ "$cond" == *"startsWith(github.event.pull_request.head.ref, 'backport-batch/')"* ]] + [[ "$cond" == *"github.event.pull_request.head.repo.full_name == github.repository"* ]] + [ "$(grep -o '&&' <<<"$cond" | wc -l)" -eq 2 ] +} + +@test "the token reads contents and nothing else" { + [ "$(yq -o=json -I=0 "$JOB.permissions" "$WF")" = '{"contents":"read"}' ] +} + +@test "main is checked out, without credentials, and the head only fetched" { + [ "$(yq -r "$JOB.steps[0].uses" "$WF")" = "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" ] + [ "$(yq -r "$JOB.steps[0].with.ref" "$WF")" = "main" ] + [ "$(yq -r "$JOB.steps[0].with.persist-credentials" "$WF")" = "false" ] + [ "$(yq -r "[$JOB.steps[] | select(.uses == \"actions/checkout*\")] | length" "$WF")" -eq 1 ] + [ "$(yq -r "$JOB.steps[] | select(.name == \"Build backport-batch from main\") | .run" "$WF")" = 'go build -o "$RUNNER_TEMP/backport-batch" ./cmd/backport-batch' ] + [ "$(yq -r "$JOB.steps[] | select(.name == \"Fetch the batch head as data\") | .run" "$WF")" = 'git fetch --no-tags --quiet origin "$HEAD_SHA"' ] +} + +@test "the tool is built before the head is fetched, and verify gets it through env" { + names="$(yq -r "$JOB.steps[].name" "$WF")" + [ "$(grep -n 'Build backport-batch from main' <<<"$names" | cut -d: -f1)" -lt "$(grep -n 'Fetch the batch head as data' <<<"$names" | cut -d: -f1)" ] + run_line="$(yq -r "$JOB.steps[] | select(.name == \"Verify every original on the batch\") | .run" "$WF")" + [ "$run_line" = '"$RUNNER_TEMP/backport-batch" verify --line "$BASE_REF" --head "$HEAD_SHA"' ] +} + +@test "no expression reaches a shell in the job" { + runs="$(yq -r "$JOB.steps[] | select(has(\"run\")) | .run" "$WF")" + [ -n "$runs" ] + if grep -q '\${{' <<<"$runs"; then + echo "a run: line carries an expression:" + echo "$runs" + false + fi +} diff --git a/hack/backup-access-preflight.bats b/hack/backup-access-preflight.bats index 38983848d..3892c8bcf 100644 --- a/hack/backup-access-preflight.bats +++ b/hack/backup-access-preflight.bats @@ -2,6 +2,8 @@ # Unit tests for the E2E-only S3 access gate that runs before expensive backup # workloads. All cluster and S3 calls are shell stubs. +load test_helper + @test "preflight helper remains sourceable by the POSIX test runner" { helper=hack/e2e-chainsaw/_lib/backup-access-preflight.sh [ "$(sed -n '1p' "$helper")" = '#!/bin/sh' ] @@ -270,3 +272,259 @@ } done } + +@test "preflight reports the port-forward log when the S3 client cannot be configured" { + . hack/e2e-chainsaw/_lib/backup-access-preflight.sh + out=$(mktemp) + pf_ready=$(mktemp) + kubectl() { + case "$*" in + *" get secret bucket-demo-backup "*) + printf '%s' '{"spec":{"secretS3":{"accessKeyID":"access","accessSecretKey":"secret"},"bucketName":"bucket-real"}}' | base64 | tr -d '\n' + ;; + *" port-forward "*) + echo 'Forwarding from 127.0.0.1:18333 -> 8333' + printf 'ready\n' > "$pf_ready" + while :; do command sleep 1; done + ;; + *) return 1 ;; + esac + } + timeout() { + shift + if [ "$1" = sh ]; then + waited=0 + while [ ! -s "$pf_ready" ] && [ "$waited" -lt 100 ]; do + waited=$(( waited + 1 )) + command sleep 0.1 + done + return 0 + fi + "$@" + } + mc() { + case "$1" in + alias) echo 'mc: Unable to initialize new alias: not an S3 endpoint' >&2; return 1 ;; + *) echo "preflight continued after the S3 client failed: mc $*" >&2; return 1 ;; + esac + } + + if cozy_backup_access_preflight tenant-test bucket-demo-backup 0 >"$out" 2>&1; then + echo "a failed S3 client setup passed the preflight" >&2 + exit 1 + fi + grep -q 'failed to configure S3 client for BucketAccess tenant-test/bucket-demo-backup' "$out" + grep -q 'port-forward: Forwarding from 127.0.0.1:18333' "$out" || { + echo "the S3 client failure dropped the port-forward log" >&2 + cat "$out" >&2 + exit 1 + } +} + +@test "preflight cleanup deletes a failed round trip's object through a live tunnel" { + . hack/e2e-chainsaw/_lib/backup-access-preflight.sh + out=$(mktemp) + pf_state=$(mktemp) + calls=$(mktemp) + kubectl() { + case "$*" in + *" get secret bucket-demo-backup "*) + printf '%s' '{"spec":{"secretS3":{"accessKeyID":"access","accessSecretKey":"secret"},"bucketName":"bucket-real"}}' | base64 | tr -d '\n' + ;; + *" port-forward "*) + # The PID of this background subshell, which is what the + # helper kills; the delete below probes it. + sh -c 'echo $PPID' > "$pf_state" + while :; do command sleep 1; done + ;; + *) return 1 ;; + esac + } + timeout() { + shift + if [ "$1" = sh ]; then + waited=0 + while [ ! -s "$pf_state" ] && [ "$waited" -lt 100 ]; do + waited=$(( waited + 1 )) + command sleep 0.1 + done + return 0 + fi + "$@" + } + mc() { + case "$1" in + alias) return 0 ;; + cp) + case "$3" in + backup-preflight/*) echo 'mc: Unable to download: connection reset by peer' >&2; return 1 ;; + *) return 0 ;; + esac + ;; + rm) + if kill -0 "$(cat "$pf_state")" 2>/dev/null; then + printf 'rm with tunnel alive\n' >> "$calls" + else + printf 'rm with tunnel gone\n' >> "$calls" + echo 'mc: dial tcp 127.0.0.1:18333: connect: connection refused' >&2 + return 1 + fi + ;; + *) return 1 ;; + esac + } + + if cozy_backup_access_preflight tenant-test bucket-demo-backup 0 >"$out" 2>&1; then + echo "a failed download passed the preflight" >&2 + exit 1 + fi + [ "$(cat "$calls")" = "rm with tunnel alive" ] || { + echo "cleanup did not delete the uploaded object while the port-forward was still up:" >&2 + cat "$calls" "$out" >&2 + exit 1 + } + if grep -q 'could not remove' "$out"; then + echo "cleanup warned about a delete that succeeded" >&2 + cat "$out" >&2 + exit 1 + fi +} + +@test "preflight cleanup tries the delete when the upload timed out after landing" { + . hack/e2e-chainsaw/_lib/backup-access-preflight.sh + out=$(mktemp) + pf_state=$(mktemp) + calls=$(mktemp) + kubectl() { + case "$*" in + *" get secret bucket-demo-backup "*) + printf '%s' '{"spec":{"secretS3":{"accessKeyID":"access","accessSecretKey":"secret"},"bucketName":"bucket-real"}}' | base64 | tr -d '\n' + ;; + *" port-forward "*) + printf alive > "$pf_state" + while :; do command sleep 1; done + ;; + *) return 1 ;; + esac + } + # The PUT reaches the server and then outlives its bound, so timeout + # reports 124 while the object is already in the bucket. + timeout() { + shift + if [ "$1" = sh ]; then + waited=0 + while [ ! -s "$pf_state" ] && [ "$waited" -lt 100 ]; do + waited=$(( waited + 1 )) + command sleep 0.1 + done + return 0 + fi + case "$1 $2 ${5:-}" in + "mc cp backup-preflight/"*) + printf 'put\n' >> "$calls" + return 124 + ;; + esac + "$@" + } + mc() { + case "$1" in + alias) return 0 ;; + rm) printf 'rm\n' >> "$calls" ;; + *) return 1 ;; + esac + } + + if cozy_backup_access_preflight tenant-test bucket-demo-backup 0 >"$out" 2>&1; then + echo "a timed-out upload passed the preflight" >&2 + exit 1 + fi + grep -qx put "$calls" + grep -qx rm "$calls" || { + echo "cleanup skipped the delete of an upload that may have landed:" >&2 + cat "$calls" "$out" >&2 + exit 1 + } +} + +@test "preflight cleanup neither deletes nor warns when every PUT was refused" { + . hack/e2e-chainsaw/_lib/backup-access-preflight.sh + out=$(mktemp) + calls=$(mktemp) + kubectl() { + case "$*" in + *" get secret bucket-demo-backup "*) + printf '%s' '{"spec":{"secretS3":{"accessKeyID":"access","accessSecretKey":"secret"},"bucketName":"bucket-real"}}' | base64 | tr -d '\n' + ;; + *" port-forward "*) while :; do command sleep 1; done ;; + *) return 1 ;; + esac + } + timeout() { + shift + if [ "$1" = sh ]; then return 0; fi + "$@" + } + mc() { + case "$1" in + alias) return 0 ;; + cp) echo 'AccessDenied' >&2; return 1 ;; + rm) printf 'rm\n' >> "$calls"; echo 'AccessDenied' >&2; return 1 ;; + *) return 1 ;; + esac + } + + if cozy_backup_access_preflight tenant-test bucket-demo-backup 0 >"$out" 2>&1; then + echo "a refused PUT passed the preflight" >&2 + exit 1 + fi + if [ -s "$calls" ] || grep -q 'could not remove' "$out"; then + echo "cleanup tried to delete an object no PUT created:" >&2 + cat "$calls" "$out" >&2 + exit 1 + fi +} + +@test "preflight cleanup names the timeout when the delete itself times out" { + . hack/e2e-chainsaw/_lib/backup-access-preflight.sh + out=$(mktemp) + kubectl() { + case "$*" in + *" get secret bucket-demo-backup "*) + printf '%s' '{"spec":{"secretS3":{"accessKeyID":"access","accessSecretKey":"secret"},"bucketName":"bucket-real"}}' | base64 | tr -d '\n' + ;; + *" port-forward "*) while :; do command sleep 1; done ;; + *) return 1 ;; + esac + } + # The delete hangs until its bound kills it: exit 124, nothing written. + timeout() { + shift + if [ "$1" = sh ]; then return 0; fi + if [ "$1 $2" = "mc rm" ]; then return 124; fi + "$@" + } + mc() { + case "$1" in + alias) return 0 ;; + cp) + case "$3" in + backup-preflight/*) echo 'mc: Unable to download: connection reset by peer' >&2; return 1 ;; + *) return 0 ;; + esac + ;; + *) return 1 ;; + esac + } + + if cozy_backup_access_preflight tenant-test bucket-demo-backup 0 >"$out" 2>&1; then + echo "a failed download passed the preflight" >&2 + exit 1 + fi + grep -q 'could not remove failed S3 preflight object' "$out" + grep -q 's3-cleanup: mc rm timed out after 15s' "$out" || { + echo "a delete that timed out left the warning without a reason:" >&2 + cat "$out" >&2 + exit 1 + } +} diff --git a/hack/backup-examples-shared-helpers.bats b/hack/backup-examples-shared-helpers.bats new file mode 100644 index 000000000..1821c0192 --- /dev/null +++ b/hack/backup-examples-shared-helpers.bats @@ -0,0 +1,95 @@ +#!/usr/bin/env bats +# Contract for the wait helpers the backup walkthroughs share: each is defined +# once, in examples/backups/_lib/wait-helpers.sh, so a fix made there reaches +# every walkthrough; each walkthrough's 00-helpers.sh provides them; and +# wait_for_field reports why kubectl could not read a field while staying quiet +# about a resource that does not exist yet. + +load test_helper + +SHARED=examples/backups/_lib/wait-helpers.sh +SHARED_HELPERS="wait_for_field wait_hr_ready wait_deleted" + +@test "each shared wait helper is defined once, in the shared file" { + fail= + for fn in $SHARED_HELPERS; do + definers=$(grep -rlE --include='*.sh' "^[[:space:]]*(function[[:space:]]+)?${fn}[[:space:]]*\(\)" examples packages | sort) + if [ "$definers" != "$SHARED" ]; then + fail="$fail +${fn} is defined in: +${definers:- (nowhere)}" + fi + done + [ -z "$fail" ] || { + echo "a walkthrough carries its own copy of a shared helper; use the one in $SHARED:$fail" >&2 + exit 1 + } +} + +@test "every walkthrough's helpers provide the shared wait helpers" { + # Some helpers read the cluster while being sourced (kafka resolves its + # image from the operator); a stub keeps this test off any real cluster. + stub=$(mktemp -d) + printf '#!/bin/sh\nexit 1\n' > "$stub/kubectl" + chmod +x "$stub/kubectl" + for helpers in examples/backups/*/00-helpers.sh; do + PATH="$stub:$PATH" bash -c ' + set -euo pipefail + . "$1" + for fn in $2; do + declare -F "$fn" >/dev/null || { echo "$1 does not provide $fn" >&2; exit 1; } + done + ' _ "$helpers" "$SHARED_HELPERS" + done +} + +@test "wait_for_field shows why kubectl could not read the field" { + # A Forbidden read has to reach the caller; swallowed, it looks like a + # field that is still empty. + stub=$(mktemp -d) + printf '#!/bin/sh\necho "Error from server (Forbidden): backupjobs is forbidden" >&2\nexit 1\n' > "$stub/kubectl" + chmod +x "$stub/kubectl" + err=$(mktemp) + if PATH="$stub:$PATH" bash -c ' + set -euo pipefail + . examples/backups/postgres/00-helpers.sh + wait_for_field backupjob demo "{.status.phase}" Succeeded tenant-test 0 + ' 2>"$err"; then + echo "wait_for_field succeeded against a kubectl that cannot read" >&2 + exit 1 + fi + grep -q 'backupjobs is forbidden' "$err" || { + echo "wait_for_field dropped kubectl's reason:" >&2 + cat "$err" >&2 + exit 1 + } +} + +@test "wait_for_field stays quiet while the resource does not exist yet" { + # The stub answers like kubectl: NotFound on stderr and exit 1, unless the + # read asks for --ignore-not-found, which makes an absent resource empty. + stub=$(mktemp -d) + cat > "$stub/kubectl" <<'EOF' +#!/bin/sh +case " $* " in +*" --ignore-not-found "*) exit 0 ;; +esac +echo 'Error from server (NotFound): backupjobs.backups.cozystack.io "demo" not found' >&2 +exit 1 +EOF + chmod +x "$stub/kubectl" + err=$(mktemp) + if PATH="$stub:$PATH" bash -c ' + set -euo pipefail + . examples/backups/postgres/00-helpers.sh + wait_for_field backupjob demo "{.status.phase}" Succeeded tenant-test 0 + ' 2>"$err"; then + echo "wait_for_field succeeded against a resource that does not exist" >&2 + exit 1 + fi + if grep -q 'NotFound' "$err"; then + echo "wait_for_field printed kubectl's NotFound for a resource it is waiting on:" >&2 + cat "$err" >&2 + exit 1 + fi +} diff --git a/hack/backupstrategy-crd-gate.bats b/hack/backupstrategy-crd-gate.bats new file mode 100644 index 000000000..fac48f35e --- /dev/null +++ b/hack/backupstrategy-crd-gate.bats @@ -0,0 +1,171 @@ +#!/usr/bin/env bats +# backupstrategy-controller ships its strategy.backups.cozystack.io CRDs as +# ordinary templates in the same release as the default Strategy CRs. Helm maps +# every document of a release through the RESTMapper before it applies any, so +# one Strategy CR whose CRD is not served yet fails the whole release with "no +# matches for kind" and applies nothing, the CRDs included. That happens on the +# upgrade that first ships a kind, and on the first render of an external-S3 +# install, where the bucket gate is already open. Every default Strategy must +# therefore also gate on its CRD being established (the crdEstablished helper). +# +# helm-unittest can only pin the templates someone remembered to list. These +# cases discover the templates from the render itself, so a new +# strategy-*-default.yaml without the CRD gate fails here without anyone +# touching a test. +# +# Harness compatibility note: CI runs this file under Bats through +# `make bats-unit-tests`. It also remains compatible with the narrower legacy +# `hack/cozytest.sh` translator, so it avoids `run`, `$status`, `$output`, +# `skip`, and setup()/teardown(). Paths stay repo-root-relative for both +# runners. +# +# Run with: bats hack/backupstrategy-crd-gate.bats + +load test_helper + +CHART=packages/system/backupstrategy-controller +STRATEGY_API='strategy.backups.cozystack.io/' + +# Every Strategy CR in the render under $1, one "